Skip to content

Enable stack canaries - #119039

Merged
Algunenano merged 32 commits into
ClickHouse:masterfrom
Algunenano:stack-protector
Sep 24, 2026
Merged

Algunenano merged 32 commits into
ClickHouse:masterfrom
Algunenano:stack-protector

Conversation

@Algunenano

@Algunenano Algunenano commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Related: #119037

Build with -fstack-protector-strong. A guard value is placed between the local variables and the return address and checked before returning, so that an overflow of a local buffer aborts instead of returning to an address the attacker wrote.

strong instruments only the functions that can actually be overflowed: those with a local array, an address-taken local or an alloca. all instruments every function, including leaves that cannot overflow, which is not worth the cost.

The flag is set through COMPILER_FLAGS, which is folded into the compiler flags before cmake/linux/default_libs.cmake and add_subdirectory (contrib) run, so it applies to the bundled libraries as well, including libc++, libc++abi, libunwind and base/glibc-compatibility. The sanitizer and XRay runtimes keep their own -fno-stack-protector, which is transcribed from upstream compiler-rt: the sanitizer runtimes execute before thread local storage is set up and inside interceptors and signal handlers, and XRay inherits the same flag set upstream.

In the static musl build, libc is compiled with canaries too, except for the objects upstream musl itself excludes (NOSSP_OBJS in its Makefile): the CRT objects, __init_ssp and the thread-pointer setup it runs through (__libc_start_main, __init_tls, __set_thread_area), and the memcpy/memset called from that path. Instrumenting those would read the canary before it exists, or see a different value on return than the one __init_ssp had installed on entry.

The compiler-rt runtime objects and musl's early-init objects are built without canaries. So are, on x86-64, the memcpy/memmove/memset entry points of the bundled LLVM libc (contrib/libllvmlibc-cmake), which already carry an explicit no_stack_protector so that their CPU dispatch stays a plain tail call. No other bundled object is left out.

our_syscall and remapToHugeStep3 in src/Common/remapExecutable.cpp read and write the return address at a fixed offset from the stack pointer, which a canary would shift, so they are marked no_stack_protector explicitly.

Kept separate from the full RELRO change so that the performance cost of each can be measured on its own.

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Harden official builds by compiling with -fstack-protector-strong.


Workflow [PR]
Sync PR [sync-upstream/pr/119039]

Version info

  • Merged into: 26.10.1.596-master (included in 26.10 and later)

Algunenano and others added 3 commits September 9, 2026 16:06
`our_syscall` reads its seventh argument from `8(%rsp)` and
`remapToHugeStep3` corrects its own return address at the same offset. A
stack canary is placed between the locals and the return address, so it
shifts what that offset refers to.

`-fstack-protector-strong` does not instrument either function, since
neither has locals, but relying on that heuristic is fragile. Mark them
explicitly instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`-fno-stack-protector` is transcribed from upstream
`SANITIZER_COMMON_CFLAGS`, it is not a choice of ours. Say so, and say
why upstream needs it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build with `-fstack-protector-strong`, so that a guard value is placed
between the local variables and the return address and checked before
returning. An overflow of a local buffer then aborts instead of
returning to an address the attacker wrote.

`strong` instruments only the functions that can actually be
overflowed: those with a local array, an address-taken local or an
alloca. `all` instruments every function, including leaves that cannot
overflow, which is not worth the cost.

The flag is set before `add_subdirectory (contrib)`, so it applies to
the bundled libraries as well. The sanitizer runtimes keep their own
`-fno-stack-protector`, which comes from upstream compiler-rt.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Algunenano Algunenano self-assigned this Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [632f473]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
hash_join_with_row_store #16 FAIL dashboard IGNORED

AI Review

Summary

This PR enables -fstack-protector-strong for the shipped builds, keeps the required runtime carve-outs in compiler-rt and musl, and rewrites several hot paths so the new hardening does not fall back into common per-row code. I re-checked the current head against the full review-thread history and the current diff; the previously reported named-tuple duplicate-key bug in JSONExtractTree is fixed on this head, and I did not find a new correctness, safety, or compatibility issue worth blocking on.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 632f473.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 280/317 (88.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement submodule changed At least one submodule changed in this PR. labels Sep 9, 2026
Comment thread CMakeLists.txt Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-build-system Build system (CMake, compilation, platform builds). label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 632f473c7c206a3d2b32c796a7be9f3f25400100 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Comment thread CMakeLists.txt Resolved
The `musl` target had a blanket `-fno-stack-protector`, so in the static
musl build libc itself was the only part left without canaries.

Restrict the opt-out to upstream musl's own `NOSSP_OBJS` list: the CRT
objects, `__init_ssp` and the thread-pointer setup it runs through, and
the `memcpy`/`memset` called from that path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread CMakeLists.txt Resolved
Algunenano and others added 2 commits September 11, 2026 14:16
`-fstack-protector-strong` instruments a whole function whenever a local array or
an escaping local survives to codegen, and it charges every call for it even when
the reason sits on a cold path. Remove the reason in the functions the perf run
flagged: outline the throws in `WriteBuffer::write`, outline the paths above 128
bits in `itoa` and take the 256 bit values by reference, use `PODArray` for the
`LIMIT BY` slice buffer, and share one stateless `NullOutput` in
`skipFieldByEscapingRule`. `clock_gettime_ns` cannot drop the `timespec` it hands
to the kernel, so it opts out with `NO_STACK_PROTECTOR`, which moves from
`remapExecutable.cpp` to `base/defines.h`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Common/Stopwatch.h Resolved
`no_stack_protector` on an inline function does nothing for its callers: the stack
protector pass runs after inlining, so a caller that inlined the `timespec` still
got a canary, and only the unused out-of-line copies were clean. Move the
definition into `Stopwatch.cpp` so the buffer never reaches a caller, which drops
the canary from `StepWallClock::onEnter` and `onLeave`, `Stopwatch` construction,
`ProfileEvents::Timer` and `WorkloadResources`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/IO/WriteBuffer.cpp Resolved
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review September 14, 2026 17:50
@alexey-milovidov alexey-milovidov self-assigned this Sep 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Comment thread CMakeLists.txt Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code changes are very good!

@alexey-milovidov

Copy link
Copy Markdown
Member

But the WASM build has failed.

alexey-milovidov and others added 4 commits September 15, 2026 02:15
`clock_gettime_ns` moved out of line into `src/Common/Stopwatch.cpp`, and the standalone
wasm parser build names every translation unit it links explicitly, so `Build (wasm_parser)`
failed with `undefined symbol: clock_gettime_ns`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119039&sha=091c46e6720f16725f9a620b229ee25d3c371fdc&name_0=PR&name_1=Build%20%28wasm_parser%29
PR: ClickHouse#119039

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`throwWriteToFinalizedBuffer` and `throwWriteToCanceledBuffer` are defined in the same
translation unit as `WriteBuffer::write`, so without `NO_INLINE` the optimizer can inline them
back into the hot path and restore the exception-construction stack slot and the stack canary
that moving them out of line was meant to remove.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Appending the flag to `CMAKE_C_FLAGS`/`CMAKE_CXX_FLAGS` after `cmake/linux/default_libs.cmake` left
every subdirectory that file adds without a canary: libc++, libc++abi, libunwind,
`base/glibc-compatibility` and `base/harmful` (a subdirectory sees the flags as they were when it was
added). Verified from `compile_commands.json`: 145 translation units in those directories lacked the
flag before the move, and only compiler-rt lacks it afterwards, which is deliberate, since
`contrib/compiler-rt-cmake` resets inherited flags to an allowlist and its sanitizer runtimes add
`-fno-stack-protector` on top.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 3 commits September 23, 2026 02:32
`JSONExtract` into a named tuple skipped the fixup whenever the number of insertions matched the
tuple size, but a repeated key inserts into the same element twice, so `{"a":1,"a":2}` for
`Tuple(a UInt8, b UInt8)` left `a` two rows long and `b` empty. Reading that result goes out of
bounds: a `LOGICAL_ERROR` in the lucky case and a crash in the rest. Track which elements took a
value in a bit set instead of counting insertions.

ClickHouse#119039 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

The rest of the reports are unrelated. Merging

@groeneai

Copy link
Copy Markdown
Collaborator

Correction to my headroom figure above: 29.1 MiB was right for master on 2026-09-20, but it fell to 15.4 MiB by 2026-09-27 (nightly clickhouse_fuzzer artifacts), and PRs that only add ordinary code now fail Build (amd_fuzzers) with the same R_X86_64_PC32 out of range link error, e.g. https://github.com/ClickHouse/ClickHouse/actions/runs/36279394633/job/108542433658. #122521 moves SanitizerCoverage's 258.6 MiB PC table past .bss, which gives that pair 274 MiB of headroom; the next limit, .rodata to the end of .text, is 93 MiB away, about five weeks at the average growth since 2026-09-10.

jmcarp pushed a commit to oxidecomputer/ClickHouse that referenced this pull request Oct 7, 2026
`ColumnArray::insertFrom` calls the element column's virtual `insertRangeFrom`
once per row (e.g. `FunctionIf::executeGeneric` for `if(cond, [DateTime], [Date])`).
Its bound check threw inline and formatted `start`/`length` through
`toString(const T &)`, which takes their addresses, so since
`-fstack-protector-strong` (ClickHouse#119039) every call paid a canary store and check,
a 0xa8-byte frame and two spills. The `conditional` ClickHouse#2/ClickHouse#3 perf queries stepped
+9% on amd and arm at that merge.

Move the throws of `insertRangeFrom` in `ColumnVector`, `ColumnDecimal`,
`ColumnFixedString`, `ColumnString` and `ColumnArray` into `[[noreturn]] NO_INLINE`
helpers taking values by value, as ClickHouse#119039 does for its own hot paths
(`DataTypesDecimal.cpp`). `NO_INLINE` keeps them out of line under ThinLTO.
Conditions, positions and error codes are unchanged; the out-of-bound message
of `ColumnString` and `ColumnArray` now carries start, length and size.

Measured on an x86 release build against master 7cbb8ad: the 27
`insertRangeFrom` instantiations of these columns go from 5-7 `%fs:0x28`
references to 0 (aarch64 `ColumnVector.cpp`: 18/18 `__stack_chk_guard`
sequences gone), and `conditional` ClickHouse#2/ClickHouse#3 run at 0.91-0.93x of master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
original-brownbear pushed a commit to original-brownbear/ClickHouse that referenced this pull request Nov 17, 2026
…` on a quarter of the rows

The `JSONEachRow` and `Avro` expansions of queries 0 and 2-10 (20 entries) took 1.00-2.51 s
on MasterCI amd and 1.09-2.90 s on arm: each reads all 2M rows of its `File` table, `Avro` on
one thread, `JSONEachRow` from a 1 GB file.

No existing query number or text changes: the 11 queries (entries 0-87) are disabled and 22
(88 entries) appended as 88-175. The 66 sub-second entries return verbatim through
`{fast_format}`; the 22 `JSONEachRow` / `Avro` ones run through `{slow_format}` on new `_500k`
tables written by the same create and fill on `id < 250000` (`Avro` still 2 files,
`JSONEachRow` one, read whole with default parallel parsing). Master's 2M-row `JSONEachRow` /
`Avro` tables are no longer created: only the disabled entries read them.

Local A/B on official builds across ClickHouse#119039 (845c709 -> 8a7ac31):
- `Avro` (2 swapped passes, 12 runs): originals moved 1.048-1.056, copies 1.044-1.058
  (retention 0.87-1.12); per-row user time copy / original 0.998-1.024.
- `JSONEachRow` (4 swapped passes, 20 runs): median over the ten, originals 1.0172, copies
  1.0145 (pooled retention 0.84), no pair apart by more than 0.015; per row 1.000-1.016.
On the base build the copies take 0.25-0.30 of the originals' time (per row 0.98-1.04), at
most 0.635 s projected on amd and 0.733 s on arm; the 66 verbatim copies 0.88-1.31 of their
originals (median 1.000).

About 21 s less query time per master perf job on amd and 23 s on arm (8 runs per copy;
26 / 28 s at CI's 5), and about 2.6 s less setup.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 18, 2026
…r of their rows

No existing query number or text changes: 2 queries (entries 2-7) are
disabled and 4 (6 entries) appended as 8-13. The `disabled` marker covers
every expansion of a query, so the four low-distinctness patterns return
verbatim as 9, 10, 12, 13 through two new substitutions.

Entries 2 and 5 (`like` / `match` with an all-unique non-constant
pattern) compile one regexp per row of `numbers_mt(1500000)` and take
1.79 / 1.57 s on MasterCI amd, 1.30 / 1.15 s on arm. Their copies (8, 11)
run on every 4th number of the same range, `numbers_mt(0, 1500000, 4)`,
with `max_block_size = 16384`: the same 23 blocks, a quarter of the rows
each, one compilation per row (375000 regexp cache misses) and a full
1000-bucket local cache per block.

Probe on official builds (paired user time, n = 12): per row the copies
take 0.97-1.01 of the originals' user time; the ClickHouse#119039 merge moved the
originals by 1.029 / 1.028 and the copies by 1.027 / 1.027, the ClickHouse#117346
merge 0.960 / 0.976 and 0.964 / 0.970 (MasterCI: 1.03-1.05 and 0.97-0.99).

In a local perf.py run the copies take 0.253 / 0.254 of the originals'
time; projected onto MasterCI that is 0.45 / 0.40 s on amd and
0.33 / 0.29 s on arm, about 30 s (amd) and 22 s (arm) less query time per
master perf job.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-build-system Build system (CMake, compilation, platform builds). pr-build Pull request with build/testing/packaging improvement pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants