Skip to content

Statically linked binary - #109239

Merged
alexey-milovidov merged 221 commits into
masterfrom
static-binary
Nov 18, 2026
Merged

alexey-milovidov merged 221 commits into
masterfrom
static-binary

Conversation

@thevar1able

@thevar1able thevar1able commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

Resolves: #75847

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Build statically linked binaries with musl libc for amd64 and aarch64.


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

Version info

  • Merged into: 26.11.1.2779-master (included in 26.11 and later)

thevar1able and others added 2 commits July 2, 2026 23:59
Build musl libc from the contrib/musl submodule (fork branch ClickHouse/v1.2.6)
instead of using vendored binaries from the sysroot. The glibc sysroot is used
only for kernel headers; musl provides all libc headers, the static library and
the CRT objects. Supported on x86_64 and aarch64 via the toolchain-*-musl.cmake
toolchains.

Squashed content of #97452.

Co-Authored-By: Claude Fable 5 <[email protected]>
The amd_release and arm_release CI builds (and the fast test) now use the
musl toolchains and produce fully static binaries. glibc builds remain
available via the cmake/linux/toolchain-x86_64.cmake and toolchain-aarch64.cmake
toolchain files (still used by debug and sanitizer builds).

The dedicated amd_musl special build is removed as it is now identical to
amd_release. The compatibility check no longer inspects glibc symbol
versions; instead it verifies the binary is fully static (no PT_INTERP,
no DT_NEEDED). The install script no longer needs the amd64musl fallback:
the default amd64 binary works on musl systems.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1490a2]

Summary: ✅


AI Review

Summary

The PR makes bundled, statically linked musl the default libc for Linux amd64 and aarch64, updates artifact publication and compatibility checks, and adapts startup and trace tests. Reviewed head: c1490a210e567d06d8f7aa29622a7ff6ed3075ba. No new inline findings; one previously dismissed experimental Silk scheduling issue remains in the pinned source.

Artifact consumers traced include the universal installer and publication aliases, self-extracting compressor and smoke checks, compatibility ELF checks, symbolization and trace storage, and filesystem isolation of dynamically linked subprocesses. These paths account for static executables; subprocess dependency collection also retains the host NSS modules.

Missing context / blind spots
  • ⚠️ Current-head build checks were still running at review completion. The fetched Praktika report contains successful prior results and does not establish completion for this head. Completed head-specific checks would close this gap.
  • ⚠️ No local ClickHouse build or runtime tests were run; the retained concurrency finding is based on the concrete source interleaving below.
Findings

⚠️ Majors

  • contrib/silk, pinned revision 1173488ee8fbcde03edf287ca09c54c370157c0f, src/fibers/fiber.cpp:2039–2051: [dismissed by author -- https://github.com/Statically linked binary #109239#discussion_r4271475992] The timed backlog observer can still lose its appointment during prefix growth. startProcessor calls postWakeup for processor k+1 before publishing width k+1. That processor can be observed awake, announce sleep, read the old width k, and select an indefinite park. Its backlog sweep can return false during the growth holdoff established by claimGrow; the grower then publishes the new width and wakes only processor k. The new standby therefore remains asleep without a timeout. If the active processors subsequently remain in non-yielding fibers, queued work can stall indefinitely. This remains real because the wakeup check still precedes publication of the role it is meant to protect. Scope is experimental Silk execution; no production Silk::spawn caller was found. Publish the role before the paired sleeping check, or use an explicit appointment observed by the park path. If deliberately deferred, link a tracking issue. The existing thread was left resolved and received no reply.
Tests
  • ⚠️ For the retained Silk issue, a focused scheduler test should force the next standby to park between the grower's wakeup check and width publication, then verify that aged ready work is serviced without another external wakeup.
Final Verdict

Status: ⚠️ Request changes. Fix the retained standby-appointment race with focused coverage, or link an issue explicitly tracking its deferral for the experimental runtime. No new inline review or thread-state changes were posted.

@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 Jul 2, 2026
thevar1able and others added 2 commits July 3, 2026 00:41
cmake/linux/toolchain-x86_64.cmake and toolchain-aarch64.cmake are now the
musl toolchains; the separate toolchain-*-musl.cmake files are gone. Since
PreLoad.cmake selects these toolchains by default, every Linux x86_64 and
aarch64 build - including debug and sanitizer builds - now targets musl and
produces a fully static binary.

Because the native-tools sub-build also picks the musl toolchain through
PreLoad.cmake (which used to recurse infinitely), and a musl-built protoc is
a static binary that runs on the build host anyway, the USE_MUSL native-tools
redirect is removed: when host and target match, the target-built protoc,
grpc_cpp_plugin and pre_compressor are used directly, as before.

PIE configurations (SANITIZE or no ThinLTO, see the -no-pie block) are linked
as static-PIE: they use musl's self-relocating rcrt1 instead of crt1 and
-static-pie instead of -static. The CRT object selection is centralized in
MUSL_CRT_OBJECTS. musl and its CRT objects are never instrumented by
sanitizers (-fno-sanitize=all): their early-init code runs before sanitizer
runtimes are initialized, and sanitizers hook the public libc functions with
interceptors instead, as with uninstrumented glibc.

Known limitation: sanitizer runtimes cannot resolve the real libc functions
via dlsym in a static musl binary, so sanitizer builds do not work yet;
this requires follow-up work in compiler-rt's interception layer.

Co-Authored-By: Claude Fable 5 <[email protected]>
Containers share the host kernel, so running the binary in ubuntu:12.04 and
centos:5 images only ever exercised the old userland (glibc and its dynamic
loader), which a fully static binary does not touch at all. The check is
reduced to verifying that the binary is fully static (no PT_INTERP segment,
no DT_NEEDED entries).

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread CMakeLists.txt Resolved
Comment thread ci/jobs/compatibility_check.py Resolved
thevar1able and others added 5 commits July 3, 2026 01:15
Sanitizer interceptors cannot find the real libc functions with dlsym() in a
static binary. Instead, compiler-rt is built with
SANITIZER_STATIC_LIBC_INTERCEPTION (see the llvm-project submodule): REAL()
binds at link time to __real_<func> symbols. The intercepted functions are
extracted from the runtime's trampoline symbols and renamed to __real_<func>
in a copy of the musl archive with llvm-objcopy; references inside musl are
renamed too, so libc-internal calls bypass the interceptors - the same
binding behaviour as dynamic musl, where libc-internal calls are
non-interposable. A generated object with strong references pulls the renamed
archive members in (the runtime's own references are weak, and weak
references do not extract archive members).

Sanitizer builds link the renamed archive (MUSL_LIBC_TARGET) instead of musl.

Verified: an ASan+UBSan static-PIE binary starts, runs, and reports a
heap-buffer-overflow with full symbolized stacks and allocation tracking.

Co-Authored-By: Claude Fable 5 <[email protected]>
ThreadFuzzer uses the internal __pthread_mutex_lock/__pthread_mutex_unlock
symbols under musl even with ASan: they are ordinary strong symbols there
(not versioned, not intercepted), while dlsym cannot look up symbols in a
statically linked binary.

Move a few more traps under the existing #ifndef USE_MUSL block: the
sanitizer builds force-extract every intercepted musl archive member (see
contrib/compiler-rt-cmake), and members like network/ent.c define these
functions alongside the intercepted ones, producing duplicate symbols with
the traps.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sanitizer builds use boost::context's ucontext backend (BOOST_USE_UCONTEXT
with the BOOST_USE_*SAN fiber annotations), but musl deliberately does not
implement getcontext/setcontext/swapcontext/makecontext. Take them from
libucontext, the de-facto standard implementation for musl systems, built
with EXPORT_UNPREFIXED so the standard names are provided as weak aliases.

None of these functions are intercepted by the sanitizers on musl targets
(those interceptors are glibc-gated), so the library needs no __real_
renaming treatment.

Co-Authored-By: Claude Fable 5 <[email protected]>
With statically linked release binaries the check cannot fail through the
normal course of events: a dynamic dependency would already fail the link.
What remains worth guarding is build-system drift (losing -static or the
musl toolchain selection), and a one-line readelf assertion in the build
job right after packaging covers that. Remove the dedicated jobs.

Co-Authored-By: Claude Fable 5 <[email protected]>
Fix build_arm_tidy under musl (now the default aarch64 toolchain):

- ShellCommand.cpp and ReplxxLineReader.cpp take the address of vfork
  directly under USE_MUSL (no dlsym, see the comment above), which
  clang-tidy's bugprone-unsafe-functions/cert-msc24-c/cert-msc33-c flag
  as an insecure function reference. This is the intentional, documented
  musl code path, so suppress with NOLINT.

- gtest's death-test macros (EXPECT_EXIT et al.) expand to a bare stderr,
  which on musl is '#define stderr (stderr)' (see contrib/musl/include/stdio.h,
  so its address can be taken); -Wdisabled-macro-expansion flags this
  self-referential but valid expansion. Suppress locally around the
  EXPECT_EXIT calls in gtest_backup_info.cpp, same technique already used
  for fmt::print(stderr, ...) in ReplxxLineReader.cpp's TemporaryFile.

Verified against the actual project compile flags: the disabled-macro-expansion
error reproduces without the pragma and is silenced with it; the vfork
NOLINT is confirmed against clang-tidy with the exact check list from the
CI failure.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread ci/jobs/build_clickhouse.py Resolved
thevar1able and others added 2 commits July 3, 2026 10:15
musl's <limits.h> defines PAGE_SIZE as a macro (glibc does not, in the
headers this test transitively includes), so the local constant of the
same name broke the declaration once aarch64/x86_64 switched to musl by
default. Rename to TEST_PAGE_SIZE; no functional change.

Co-Authored-By: Claude Fable 5 <[email protected]>
rustc rejects combining -Zsanitizer=* with a statically linked libc, which
the x86_64/aarch64-unknown-linux-musl targets default to (crt-static):
'sanitizer is incompatible with statically linked libc, disable it using
-C target-feature=-crt-static', failing the build_arm_tsan job while
compiling core/std for _ch_rust_prql.

Verified locally with the exact toolchain and invocation from CI
(cargo rustc --target=x86_64-unknown-linux-musl -Zbuild-std=... with
RUSTFLAGS="-Zsanitizer=thread"): reproduces the error, and disabling
crt-static fixes it. Checked that this doesn't reintroduce a dynamic
dependency: the only symbol the resulting staticlib needs that crt-static
would otherwise avoid is __tls_get_addr (general-dynamic TLS model),
which musl's static libc already defines for this exact case, so the
final static-PIE link and runtime remain unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread ci/defs/job_configs.py Resolved
Bump contrib/llvm-project to pick up the aarch64 sigcontext/sysinfo header
conflict fix and the MSan getrlimit64/prlimit64 fix.

pre_compressor and hash-binary used plain add_executable instead of
clickhouse_add_executable, so under USE_MUSL they never got the CRT
objects that -nostartfiles requires: pre_compressor linked with no
_start (lld only warns, doesn't fail) and segfaulted immediately when
run, breaking the self-extracting packaging step for every non-cross
Linux build. hash-binary has the same gap in its host-tool branch,
latent today since USE_BINARY_HASH is release-build-only.

gtest_lsan.cpp's EXPECT_DEATH hits the same musl stderr macro expansion
warning already worked around in ReplxxLineReader.cpp and
gtest_backup_info.cpp.

Verified: pre_compressor built locally now links without the lld
'cannot find entry symbol _start' warning and runs (exit 0, was 139);
built and ran the self-extracting target end-to-end, including running
the resulting self-extracting clickhouse binary.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread base/harmful/harmful.c Resolved
thevar1able and others added 11 commits July 3, 2026 17:12
…sinfo on aarch64

Bump contrib/llvm-project to drop the per-file compiler-rt workaround from
the previous bump (see that submodule commit): it only covered the one
TU the first aarch64 build failure showed, and a different compiler-rt
file hit the identical struct redefinition through the same headers in
the opposite include order, proving this can surface in any translation
unit, not just ones in compiler-rt.

Fix it once, for every translation unit built against this toolchain -
ClickHouse's own code and any contrib, present or future - by predefining
the three kernel UAPI header guards (asm/sigcontext.h, linux/prctl.h,
linux/sysinfo.h) whose musl equivalents (bits/signal.h, sys/prctl.h,
sys/sysinfo.h) already define the same structs, so musl's copy always
wins regardless of include order. Confirmed musl's sys/prctl.h already
covers a superset of the kernel header's PR_* macros in our sysroot, so
nothing is lost by preferring it.

Co-Authored-By: Claude Fable 5 <[email protected]>
The scan that decides which musl functions to rename to __real_<func>
only looked at the runtime's __interceptor_trampoline_* symbols. TSan's
setjmp/_setjmp/sigsetjmp/__sigsetjmp on aarch64 are handled specially -
hand-written asm, direct strong-symbol replacement, no
INTERCEPTOR-generated trampoline - so _setjmp/__sigsetjmp were never
renamed, leaving REAL(_setjmp) null (see the companion
tsan_interceptors_posix.cpp fix), while setjmp/sigsetjmp (strongly
defined by the runtime but never renamed in musl's copy) caused a
duplicate-symbol link error once _setjmp/__sigsetjmp were fixed and
their containing musl objects got pulled into the link.

Rescan as the union of the runtime's weak undefined __real_<func>
references (every REAL(func) use, regardless of whether it goes through
an INTERCEPTOR) and its own strongly-defined bare names that also exist
in musl (every name the runtime means to own outright). Verified this is
a strict superset of the old trampoline-derived list, plus exactly the
four setjmp-family names.
Includes the fix for MSan's stat/lstat interceptors being disabled on
musl (SI_STAT_LINUX) and the fix for TSan's setjmp interceptor
clobbering REAL(_setjmp)/REAL(__sigsetjmp) with null under
SANITIZER_STATIC_LIBC_INTERCEPTION, which was the root cause of the
arm_tsan silent segfault.
The static-interception scheme renames every intercepted function to
__real_<func> throughout the musl archive - definitions and musl-internal
call sites alike - so that libc-internal calls bypass the sanitizer
interceptors, matching how dynamic musl binds its non-interposable
internal calls.

That bypass is wrong for the plain allocation primitives (malloc,
calloc, realloc, free and friends): unlike a purely internal helper,
the pointer they return escapes to the application. musl's getdelim
allocates the output buffer through its internal realloc call - under
the rename that is musl's own allocator - and hands it to the caller,
who frees it through the interposed free() and thus the sanitizer's
allocator. TSan's secondary allocator then aborts on the foreign
pointer: "CHECK failed: sanitizer_allocator_secondary.h:297
IsAligned(p, page_size_)". First hit in libnuma's constructor
(numa_init -> set_nodemask_size, getline + free) on every aarch64 TSan
binary at startup, before main.

objcopy --redefine-syms cannot rename a definition but keep a call site,
so exclude the allocation functions from renaming entirely. This is
safe: the sanitizer runtimes strongly define the bare names, never call
REAL() on any of them (they manage memory via direct mmap), and with the
bare names unrenamed musl's defining objects are simply never extracted
from the archive, while every musl-internal allocation call site keeps
resolving to the same interposed allocator the application frees
through.

With this, all local smoke tests pass on a full TSan musl clickhouse
binary on both aarch64 (under qemu-system-aarch64 full-system emulation)
and x86_64: SELECT 1, multi-threaded aggregation over numbers_mt,
exception propagation via throwIf, and array/string functions.
Replaces the SIGILL-probing CPU feature detection with the
getauxval/HWCAP path on musl, fixing an unrecoverable startup failure
(null pointer call inside OPENSSL_cpuid_setup's constructor) in every
TSan aarch64 musl binary.
In a static musl link the strong TRAP(nl_langinfo) definition from
harmful.c wins over musl's own, so the trap is reached from inside libc
itself: musl's strptime calls nl_langinfo to resolve locale-dependent
format specifiers (%c, %p, %r, %x, %a, %b, ...), aborting the process
on an otherwise valid strptime call.

The trap exists because glibc's nl_langinfo returns a pointer to a
mutable static buffer and is not thread-safe. musl's implementation
returns pointers to constant strings, so it is not harmful there -
guard the trap with #ifndef USE_MUSL like the other musl-incompatible
traps in this file.
Fixes the arm_msan build failure: MSan-instrumented llvm-min-tblgen
aborted with a false-positive use-of-uninitialized-value on fstat
results while generating GenVT.inc, because the fstat/fstatat
interceptors were compiled out on musl (a second copy of the
already-fixed SI_STAT_LINUX glibc-version gate, local to
msan_interceptors.cpp).
Whenever -fprofile-instr-generate appears on the link line, clang
injects the profile runtime from its own resource directory. That
archive is built against the host glibc - it references the
_FORTIFY_SOURCE __*_chk functions - so it cannot link into a musl
binary, and llvm_coverage_build failed with undefined __snprintf_chk
and friends from libclang_rt.profile-x86_64.a(InstrProfilingFile.c.o).

Build clang_rt_profile from compiler-rt/lib/profile in
contrib/compiler-rt-cmake, like the sanitizer runtimes, and suppress
the resource-directory copy with -noprofilelib. Two gating quirks:
the file's early return did not know about coverage-only builds
(no SANITIZE, no ENABLE_XRAY), and contrib/CMakeLists.txt shadows
WITH_COVERAGE to OFF for the whole directory scope (third-party code
is never coverage-instrumented), so both checks read the cache-level
$CACHE{WITH_COVERAGE} instead.

Verified on x86_64 musl: protoc links under the exact configuration
that failed in CI and writes a valid (empty - contrib code is not
instrumented) profraw on exit, and a fully instrumented test binary
linked against the same archive collects real counters that
llvm-profdata parses.
The interceptor assumed Linux implies glibc's GNU char* strerror_r;
musl only has the POSIX int variant, so a successful call returned 0,
which the interceptor dereferenced via internal_strlen. Crashed every
MSan aarch64 musl clickhouse-local run through libc++'s system_error
machinery; the same latent bug was linked into ASan and TSan.

With this, the full 4-query smoke battery passes on the aarch64 MSan
musl binary under qemu-system-aarch64.
The style check greps contrib/*-cmake for dynamic compiler-check
command names, comments included; the clang_rt_profile comment
mentioned the upstream probe by name.
Comment thread ci/jobs/fast_test.py Resolved
thevar1able and others added 4 commits November 17, 2026 19:21
# Conflicts:
#	ci/jobs/compatibility_check.py
#	contrib/libllvmlibc-cmake/CMakeLists.txt
The fast test hardcoded `toolchain-aarch64.cmake`, so the local
`python -m ci.praktika run "Fast test"` on an x86_64 host built aarch64
binaries it then could not run. `PreLoad.cmake` already selects the native
toolchain for a clang compiler, and both Linux toolchains link musl.

Related: #109239 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings ClickHouse/musl#18 (keep `__dls2` in LTO builds of
the static PIE startup) and ClickHouse/musl#19 (build with
Clang CFI, keep the vDSO function pointers read-only).

PR: #109239

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings ClickHouse/llvm-project#158 (exempt
`__assume_aligned` from Clang CFI).

PR: #109239

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/FilesystemIsolation.cpp Resolved
thevar1able and others added 2 commits November 18, 2026 01:05
…uffers

The definition was `PRIVATE` to `_flatbuffers`, but `flatbuffers/util.h` reads
it in every translation unit that includes it, and otherwise selects
`strtoll_l` / `strtoull_l`, which musl does not have. A consumer that includes
`util.h` failed to compile in the static build.

PR: #109239

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…c build

A glibc-linked bridge loads the NSS modules of `/etc/nsswitch.conf` itself, on
its first host, user or group lookup, whatever the C library of the server is.
`DT_NEEDED` does not name them, so with the static server they and the sockets
of their services were missing from the isolated filesystem, and lookups
through `sss`, `mdns` or `libnss_dns.so.2` failed in the bridge.

Collect them whenever the server or a program it starts uses a dynamic loader,
and look them up also next to the libraries of the started programs.

Related: #109239 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026

This branch was successfully deployed

1 active deployment
staging - docs — c1490a21 Deployed Nov 18, 2026 by mintlify[bot]
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.

Migrate to Musl

6 participants