commit 3932a5c6d464770f040bf10066c32eb65057c647
parent 8dc39fc2f639057c328240cc6d9fda66fd86bd90
Author: cowmonk <cowmonk@based.pt>
Date: Thu, 19 Nov 2026 12:00:31 -0700
musllvm can build static llvm tools with musl
The static mode bootstraps native musl runtimes before building LLVM.
Release builds check the host ELF files and run the tools in a chroot.
LLVM bootstrap configuration and python scripts were graciously done
by a good friend of mine who wishes not to be named (thanks once again!)
Diffstat:
12 files changed, 428 insertions(+), 59 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
@@ -5,10 +5,11 @@ on:
pull_request:
workflow_dispatch:
inputs:
- source_llvm:
- description: Also build LLVM host tools from source
- type: boolean
- default: false
+ llvm_mode:
+ description: LLVM host tool build
+ type: choice
+ options: [system, source, static]
+ default: system
permissions:
contents: read
@@ -22,14 +23,14 @@ jobs:
cross:
runs-on: ubuntu-24.04
- timeout-minutes: ${{ inputs.source_llvm && 360 || 90 }}
+ timeout-minutes: ${{ inputs.llvm_mode && inputs.llvm_mode != 'system' && 360 || 90 }}
strategy:
fail-fast: false
matrix:
arch: [x86_64, aarch64]
env:
ARCH: ${{ matrix.arch }}
- LLVM_MODE: ${{ inputs.source_llvm && 'source' || 'system' }}
+ LLVM_MODE: ${{ inputs.llvm_mode || 'system' }}
steps:
- uses: actions/checkout@v4
- name: Install host dependencies
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
@@ -41,8 +41,7 @@ jobs:
arch: [x86_64, aarch64]
env:
ARCH: ${{ matrix.arch }}
- LLVM_MODE: source
- HOST_LDFLAGS: -static-libstdc++ -static-libgcc
+ LLVM_MODE: static
steps:
- uses: actions/checkout@v4
- name: Install host dependencies
@@ -74,6 +73,10 @@ jobs:
mkdir -p "$unpacked"
mv "build/$target" "$RUNNER_TEMP/original-$target"
tar -xJf "$archive" -C "$unpacked"
+ python3 scripts/package.py --check-host --prefix "$unpacked/musllvm-$target"
+ sudo chroot "$unpacked/musllvm-$target" /host/bin/clang --version
+ sudo chroot "$unpacked/musllvm-$target" /host/bin/ld.lld --version
+ sudo chroot "$unpacked/musllvm-$target" /host/bin/llvm-ar --version
make verify PREFIX="$unpacked/musllvm-$target" \
BUILD_DIR="$PWD/build/release-verify/$target" JOBS=2
- uses: actions/upload-artifact@v4
diff --git a/Makefile b/Makefile
@@ -1,6 +1,7 @@
include config.mk
export ARCH TARGET PREFIX BUILD_DIR SOURCES_DIR SOURCES_FILE LLVM_MODE JOBS LINK_JOBS
+export BOOTSTRAP_LLVM_MODE
export HOST_CC HOST_CXX TARGET_CFLAGS HOST_CFLAGS HOST_CXXFLAGS HOST_LDFLAGS RUNNER
all: build
@@ -37,14 +38,14 @@ clean:
help:
@printf '%s\n' \
- 'make [ARCH=x86_64|aarch64] [LLVM_MODE=system|source] [JOBS=2]' \
+ 'make [ARCH=x86_64|aarch64] [LLVM_MODE=system|source|static] [JOBS=2]' \
' build build and verify the complete cross toolchain (default)' \
' doctor check host dependencies' \
' show-config print paths and target configuration' \
' pull download and verify pinned source archives' \
' verify-sources check downloaded archives without network access' \
' verify compile, inspect, and optionally run C and C++ programs' \
- ' package archive a completed LLVM_MODE=source toolchain' \
+ ' package archive a completed source or static toolchain' \
' check run offline build-driver tests' \
' clean remove the selected toolchain and its work directory' \
' configure-llvm configure the optional LLVM source build'
diff --git a/README.md b/README.md
@@ -12,9 +12,9 @@ downloads
=========
[Releases](https://github.com/cowmonk/musllvm/releases) provide archives
-for x86_64-linux-musl and aarch64-linux-musl. Both run on x86_64 Linux
-hosts with glibc 2.39 or newer. The compiler tools are included.
-Target programs use musl.
+for x86_64-linux-musl and aarch64-linux-musl. The compiler tools link
+musl statically and run on x86_64 Linux, including musl and glibc systems.
+Target programs use musl. The wrappers need a shell and the usual POSIX tools.
Download an archive and SHA256SUMS from the same release, then check
the archive you downloaded:
@@ -23,8 +23,8 @@ the archive you downloaded:
tar -xJf musllvm-x86_64-linux-musl-host-x86_64-linux.tar.xz
eval "$(musllvm-x86_64-linux-musl/bin/x86_64-linux-musl-env)"
-Each archive includes its source pins, patches, licenses and build information under
-share/musllvm/. pkg-config is optional and uses the host installation.
+Each archive includes its source pins, patches, licenses and build information
+under share/musllvm/. pkg-config is optional and uses the host installation.
dependencies
@@ -33,7 +33,8 @@ dependencies
Build on a Linux host with:
clang/llvm Clang 21 or newer, clang++, LLD, LLVM utilities and
- matching llvm-config and LLVM CMake metadata (system mode)
+ matching llvm-config and LLVM CMake metadata (system mode
+ or a static build using the system LLVM bootstrap)
make GNU make
cmake 3.20 or newer
ninja
@@ -68,7 +69,30 @@ To also build Clang, LLD and the LLVM utilities from source:
PREFIX="$PWD/build/x86_64-source" BUILD_DIR="$PWD/build/work/x86_64-source"
Source mode installs host tools under PREFIX/host. These tools use the
-host libc. Both modes produce a cross toolchain.
+host libc.
+
+For compiler tools that link musl, libc++, libc++abi, libunwind and
+compiler-rt statically:
+
+ make LLVM_MODE=static ARCH=x86_64 JOBS=2 LINK_JOBS=1 \
+ PREFIX="$PWD/build/x86_64-static" BUILD_DIR="$PWD/build/work/x86_64-static"
+
+Static mode first builds musl and the C++ runtimes for the build machine
+under BUILD_DIR/bootstrap/. It uses that toolchain to build the final LLVM
+tools, then builds the requested target's sysroot. The compiler runs on
+the build machine's architecture; ARCH selects the target architecture.
+The build checks every installed host executable for a dynamic loader
+and shared library dependencies.
+
+To start with a working GCC C++17 toolchain, including on a musl host:
+
+ make LLVM_MODE=static BOOTSTRAP_LLVM_MODE=source \
+ HOST_CC=gcc HOST_CXX=g++ ARCH=x86_64 JOBS=2 LINK_JOBS=1 \
+ PREFIX="$PWD/build/x86_64-static" BUILD_DIR="$PWD/build/work/x86_64-static"
+
+This also builds the initial LLVM tools from source. It takes longer than
+using an installed LLVM. Static host tools cannot load compiler plugins.
+The target sysroot still includes static and shared libraries.
configuration
@@ -76,15 +100,16 @@ configuration
Edit [config.mk](config.mk) or override settings through make.
- ARCH x86_64 x86_64 or aarch64
- TARGET $(ARCH)-linux-musl target triple
- PREFIX build/$(TARGET) toolchain installation
- BUILD_DIR build/work/$(TARGET) build files and completed stages
- LLVM_MODE system system or source
- JOBS 2 compilation jobs
- LINK_JOBS 1 parallel links when building LLVM
- TARGET_CFLAGS -O2 target library flags
- RUNNER emulator executable (optional)
+ ARCH x86_64 x86_64 or aarch64
+ TARGET $(ARCH)-linux-musl target triple
+ PREFIX build/$(TARGET) toolchain installation
+ BUILD_DIR build/work/$(TARGET) build files and completed stages
+ LLVM_MODE system system, source or static
+ BOOTSTRAP_LLVM_MODE system system or source (static mode)
+ JOBS 2 compilation jobs
+ LINK_JOBS 1 parallel links when building LLVM
+ TARGET_CFLAGS -O2 target library flags
+ RUNNER emulator executable (optional)
Each target has its own prefix and work directory. Downloaded and
extracted sources are shared. Build paths must have no whitespace or
@@ -167,14 +192,14 @@ no compilation or downloads.
A completed build also runs make verify. This compiles static, static-pie
and dynamic C and C++ programs, directly and through the CMake toolchain
-file, and checks their ELF architecture and runtime dependencies. It also
+file, and checks ELF architecture and runtime dependencies. It also
compiles with -Werror. Programs run when the host architecture matches the
target or RUNNER names an emulator.
make verify ARCH=aarch64 RUNNER=qemu-aarch64
[CI](.github/workflows/ci.yml) runs offline tests and both target builds.
-A manual workflow run can build both targets with LLVM from source instead.
+A manual workflow run can select source or static LLVM builds for both targets.
publishing
@@ -186,17 +211,21 @@ or the compiler smoke tests. This covers source version updates
and new core components added to the build. README edits do not publish
a release. The workflow can also be run manually from main.
-Both targets build with LLVM_MODE=source. Each archive is unpacked into
-a new location and tested before upload. The release is published after
-both builds pass, with SHA256SUMS and sources.list attached.
+Both targets build with LLVM_MODE=static. Each archive is unpacked into
+a new location and tested before upload. CI checks the host ELF files and
+starts Clang, LLD and llvm-ar in a chroot containing only the toolchain.
+The release is published after both builds pass, with SHA256SUMS and
+sources.list attached.
Tags use musllvm-YYYY-MM-DD-COMMIT, with the first 12 commit characters.
Rerunning a published commit keeps its release assets.
-To package a completed source build yourself:
+To package a completed static build yourself:
- make package LLVM_MODE=source ARCH=x86_64
+ make package LLVM_MODE=static ARCH=x86_64 \
+ PREFIX="$PWD/build/x86_64-static" BUILD_DIR="$PWD/build/work/x86_64-static"
Archives go to build/releases/. Set DIST_DIR to change the output directory.
+LLVM_MODE=source also supports packaging, with the build host's libc requirements.
credits
diff --git a/config.mk b/config.mk
@@ -6,6 +6,7 @@ SOURCES_DIR ?= $(CURDIR)/sources
SOURCES_FILE ?= $(CURDIR)/sources.list
LLVM_MODE ?= system
+BOOTSTRAP_LLVM_MODE ?= system
JOBS ?= 2
LINK_JOBS ?= 1
HOST_CC ?= clang
diff --git a/scripts/build.sh b/scripts/build.sh
@@ -12,7 +12,9 @@ doctor()
done
need "$HOST_CC"
need "$HOST_CXX"
- if [ "$LLVM_MODE" = system ]; then
+ doctor_mode=$LLVM_MODE
+ [ "$LLVM_MODE" != static ] || doctor_mode=$BOOTSTRAP_LLVM_MODE
+ if [ "$doctor_mode" = system ]; then
"$HOST_CC" --version | head -n 1 | awk '/clang/ { found=1 } END { exit !found }' ||
die "LLVM_MODE=system requires Clang; set HOST_CC=clang"
clang_major=$("$HOST_CC" -dumpversion)
@@ -27,18 +29,53 @@ doctor()
configure_llvm()
{
+ llvm_cc=$BOOTSTRAP_CC
+ llvm_cxx=$BOOTSTRAP_CXX
+ llvm_ldflags=$HOST_LDFLAGS
+ set --
+ if [ "$LLVM_MODE" = static ]; then
+ bootstrap_prefix="$BUILD_DIR/bootstrap/prefix"
+ (
+ ARCH=$HOST_ARCH TARGET="$HOST_ARCH-linux-musl" \
+ PREFIX="$bootstrap_prefix" BUILD_DIR="$BUILD_DIR/bootstrap/work" \
+ LLVM_MODE="$BOOTSTRAP_LLVM_MODE" TARGET_CFLAGS=-O2 RUNNER= \
+ sh "$PROOT/scripts/build.sh" runtimes
+ )
+ llvm_cc="$bootstrap_prefix/bin/$HOST_ARCH-linux-musl-cc"
+ llvm_cxx="$bootstrap_prefix/bin/$HOST_ARCH-linux-musl-c++"
+ llvm_ldflags="$HOST_LDFLAGS -static"
+ set -- -DCMAKE_SYSROOT="$bootstrap_prefix/sysroot" \
+ -DCMAKE_FIND_ROOT_PATH="$bootstrap_prefix/sysroot" \
+ -DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER \
+ -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY \
+ -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY \
+ -DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=ONLY \
+ -DCMAKE_AR="$bootstrap_prefix/bin/$HOST_ARCH-linux-musl-ar" \
+ -DCMAKE_RANLIB="$bootstrap_prefix/bin/$HOST_ARCH-linux-musl-ranlib" \
+ -DCMAKE_NM="$bootstrap_prefix/bin/$HOST_ARCH-linux-musl-nm" \
+ -DCMAKE_LINKER="$bootstrap_prefix/libexec/ld.lld" \
+ -DLLVM_HOST_TRIPLE="$HOST_ARCH-linux-musl" \
+ -DLLVM_DEFAULT_TARGET_TRIPLE="$HOST_ARCH-linux-musl" \
+ -DBUILD_SHARED_LIBS=OFF -DLLVM_BUILD_LLVM_DYLIB=OFF \
+ -DLLVM_LINK_LLVM_DYLIB=OFF -DCLANG_LINK_CLANG_DYLIB=OFF \
+ -DLLVM_ENABLE_LIBCXX=ON -DLLVM_ENABLE_PLUGINS=OFF \
+ -DLLVM_EXPORT_SYMBOLS_FOR_PLUGINS=OFF -DCLANG_PLUGIN_SUPPORT=OFF \
+ -DLLVM_ENABLE_BACKTRACES=OFF -DLLVM_ENABLE_LIBPFM=OFF \
+ -DLLVM_ENABLE_CURL=OFF -DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_FFI=OFF \
+ -DDEFAULT_SYSROOT=
+ fi
cmake -S "$LLVM_SOURCE/llvm" -B "$BUILD_DIR/llvm" -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX/host" \
- -DCMAKE_C_COMPILER="$BOOTSTRAP_CC" -DCMAKE_CXX_COMPILER="$BOOTSTRAP_CXX" \
+ -DCMAKE_C_COMPILER="$llvm_cc" -DCMAKE_CXX_COMPILER="$llvm_cxx" \
-DCMAKE_C_FLAGS="$HOST_CFLAGS" -DCMAKE_CXX_FLAGS="$HOST_CXXFLAGS" \
- -DCMAKE_EXE_LINKER_FLAGS="$HOST_LDFLAGS" \
+ -DCMAKE_EXE_LINKER_FLAGS="$llvm_ldflags" \
-DLLVM_ENABLE_PROJECTS='clang;lld' -DLLVM_TARGETS_TO_BUILD='X86;AArch64' \
-DLLVM_DISTRIBUTION_COMPONENTS='clang;clang-resource-headers;lld;llvm-ar;llvm-ranlib;llvm-nm;llvm-objcopy;llvm-objdump;llvm-readelf;llvm-strip;llvm-size;llvm-strings;llvm-addr2line;llvm-cxxfilt' \
-DLLVM_PARALLEL_LINK_JOBS="$LINK_JOBS" -DLLVM_ENABLE_ASSERTIONS=OFF \
-DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF \
-DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_ENABLE_BINDINGS=OFF \
-DLLVM_ENABLE_ZLIB=OFF -DLLVM_ENABLE_ZSTD=OFF -DLLVM_ENABLE_LIBXML2=OFF \
- -DLLVM_ENABLE_LIBEDIT=OFF -DCLANG_ENABLE_ARCMT=OFF -DCLANG_ENABLE_STATIC_ANALYZER=OFF
+ -DLLVM_ENABLE_LIBEDIT=OFF -DCLANG_ENABLE_ARCMT=OFF -DCLANG_ENABLE_STATIC_ANALYZER=OFF "$@"
}
done_stage()
@@ -53,11 +90,14 @@ mark_stage()
toolchain()
{
- if [ "$LLVM_MODE" = source ]; then
+ if [ "$LLVM_MODE" != system ]; then
if ! done_stage llvm; then
configure_llvm
cmake --build "$BUILD_DIR/llvm" --parallel "$JOBS" --target distribution
cmake --build "$BUILD_DIR/llvm" --target install-distribution
+ if [ "$LLVM_MODE" = static ]; then
+ python3 "$PROOT/scripts/package.py" --check-host --prefix "$PREFIX"
+ fi
mark_stage llvm
fi
HOST_CLANG="$PREFIX/host/bin/clang"
@@ -78,7 +118,7 @@ toolchain()
RESOURCE_DIR="$PREFIX/lib/clang/$RESOURCE_VERSION"
mkdir -p "$PREFIX/libexec" "$RESOURCE_DIR/lib/linux" "$SYSROOT/usr/lib" "$BUILD_DIR/empty-gcc"
for program in $TOOLS; do
- if [ "$LLVM_MODE" = source ]; then
+ if [ "$LLVM_MODE" != system ]; then
tool_path="../host/bin/$program"
else
case "$program" in
@@ -242,6 +282,7 @@ wrappers()
sed -e "s/@TARGET@/$TARGET/g" -e "s/@RESOURCE_VERSION@/$RESOURCE_VERSION/g" \
"$PROOT/files/toolchain/clang.cfg" > "$PREFIX/share/musllvm/clang.cfg"
printf '%s\n' "$RESOURCE_VERSION" > "$PREFIX/share/musllvm/resource-version"
+ printf '%s\n' "$LLVM_MODE" > "$PREFIX/share/musllvm/llvm-mode"
if [ -d "$PROOT/patches" ]; then
cp -R "$PROOT/patches" "$PREFIX/share/musllvm/"
fi
@@ -251,8 +292,8 @@ wrappers()
stage=${1:-all}
case "$stage" in
config)
- printf 'ARCH=%s\nTARGET=%s\nLLVM_MODE=%s\nPREFIX=%s\nSYSROOT=%s\nBUILD_DIR=%s\nJOBS=%s\n' \
- "$ARCH" "$TARGET" "$LLVM_MODE" "$PREFIX" "$SYSROOT" "$BUILD_DIR" "$JOBS"
+ printf 'ARCH=%s\nTARGET=%s\nLLVM_MODE=%s\nPREFIX=%s\nSYSROOT=%s\nBUILD_DIR=%s\nJOBS=%s\nBOOTSTRAP_LLVM_MODE=%s\nHOST_ARCH=%s\n' \
+ "$ARCH" "$TARGET" "$LLVM_MODE" "$PREFIX" "$SYSROOT" "$BUILD_DIR" "$JOBS" "$BOOTSTRAP_LLVM_MODE" "$HOST_ARCH"
exit ;;
doctor) doctor; exit ;;
clean)
@@ -267,7 +308,7 @@ esac
doctor
unset CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH LIBRARY_PATH
-unset GCC_EXEC_PREFIX COMPILER_PATH CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
+unset GCC_EXEC_PREFIX COMPILER_PATH CFLAGS CXXFLAGS CPPFLAGS LDFLAGS MUSLLVM_SYSROOT
BOOTSTRAP_CC=$(absolute_path "$(command -v "$HOST_CC")")
BOOTSTRAP_CXX=$(absolute_path "$(command -v "$HOST_CXX")")
sh "$PROOT/scripts/check.sh" pull
@@ -282,7 +323,8 @@ ATOMIC_SOURCE=$source_path
config_digest=$({
printf '%s\n' "$ARCH" "$TARGET" "$LLVM_MODE" "$PREFIX" "$BUILD_DIR" \
- "$BOOTSTRAP_CC" "$BOOTSTRAP_CXX" "$TARGET_CFLAGS" "$HOST_CFLAGS" "$HOST_CXXFLAGS" "$HOST_LDFLAGS"
+ "$BOOTSTRAP_CC" "$BOOTSTRAP_CXX" "$TARGET_CFLAGS" "$HOST_CFLAGS" "$HOST_CXXFLAGS" "$HOST_LDFLAGS" \
+ "$BOOTSTRAP_LLVM_MODE" "$HOST_ARCH"
"$BOOTSTRAP_CC" --version
"$BOOTSTRAP_CXX" --version
cat "$SOURCES_FILE"
diff --git a/scripts/config.sh b/scripts/config.sh
@@ -119,9 +119,22 @@ case "$TARGET" in
esac
LLVM_MODE=${LLVM_MODE:-system}
case "$LLVM_MODE" in
+system|source|static) ;;
+*) die "LLVM_MODE must be system, source or static" ;;
+esac
+BOOTSTRAP_LLVM_MODE=${BOOTSTRAP_LLVM_MODE:-system}
+case "$BOOTSTRAP_LLVM_MODE" in
system|source) ;;
-*) die "LLVM_MODE must be system or source" ;;
+*) die "BOOTSTRAP_LLVM_MODE must be system or source" ;;
esac
+HOST_ARCH=$(uname -m)
+if [ "$LLVM_MODE" = static ]; then
+ [ "$(uname -s)" = Linux ] || die "static LLVM requires a Linux build host"
+ case "$HOST_ARCH" in
+ x86_64|aarch64) ;;
+ *) die "unsupported static LLVM host: $HOST_ARCH" ;;
+ esac
+fi
JOBS=${JOBS:-2}
LINK_JOBS=${LINK_JOBS:-1}
for jobs in "$JOBS" "$LINK_JOBS"; do
@@ -155,4 +168,5 @@ HOST_CXXFLAGS=${HOST_CXXFLAGS:-}
HOST_LDFLAGS=${HOST_LDFLAGS:-}
RUNNER=${RUNNER:-}
export PROOT ARCH TARGET PREFIX BUILD_DIR SOURCES_DIR SOURCES_FILE LLVM_MODE JOBS LINK_JOBS
+export BOOTSTRAP_LLVM_MODE HOST_ARCH
export HOST_CC HOST_CXX TARGET_CFLAGS HOST_CFLAGS HOST_CXXFLAGS HOST_LDFLAGS RUNNER
diff --git a/scripts/package.py b/scripts/package.py
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import platform
+import struct
import subprocess
import tarfile
import tempfile
@@ -13,6 +14,68 @@ import tempfile
ROOT = Path(__file__).resolve().parent.parent
+def check_static_elf(path, arch):
+ machines = {"x86_64": 62, "aarch64": 183}
+ if arch not in machines:
+ raise ValueError("unsupported host architecture: " + arch)
+ with path.open("rb") as stream:
+ size = os.fstat(stream.fileno()).st_size
+ header = stream.read(64)
+ if len(header) != 64 or header[:6] != b"\x7fELF\x02\x01" or header[6] != 1:
+ raise ValueError("host tool is not a little-endian ELF64 executable: " + str(path))
+ fields = struct.unpack("<HHIQQQIHHHHHH", header[16:])
+ kind, machine, version, entry, offset = fields[:5]
+ header_size, stride, count = fields[7:10]
+ if kind not in (2, 3) or not entry or version != 1 or machine != machines[arch]:
+ raise ValueError("wrong host ELF type or architecture: " + str(path))
+ if header_size != 64 or stride != 56 or not count or offset < 64 or offset + stride * count > size:
+ raise ValueError("invalid host ELF program headers: " + str(path))
+ loaded = False
+ for index in range(count):
+ stream.seek(offset + stride * index)
+ segment = struct.unpack("<IIQQQQQQ", stream.read(56))
+ tag, _, start, _, _, length, _, _ = segment
+ if start + length > size:
+ raise ValueError("truncated host ELF segment: " + str(path))
+ if tag == 3:
+ raise ValueError("host tool needs a dynamic loader: " + str(path))
+ loaded |= tag == 1
+ if tag == 2:
+ if not length or length % 16:
+ raise ValueError("invalid host ELF dynamic section: " + str(path))
+ stream.seek(start)
+ for _ in range(length // 16):
+ dynamic_tag, _ = struct.unpack("<qQ", stream.read(16))
+ if dynamic_tag == 0:
+ break
+ if dynamic_tag in (1, 0x7fffffff, 0x7ffffffd):
+ raise ValueError("host tool needs a shared library: " + str(path))
+ else:
+ raise ValueError("unterminated host ELF dynamic section: " + str(path))
+ if not loaded:
+ raise ValueError("host tool has no loadable segment: " + str(path))
+
+
+def check_static_host(prefix, arch=None):
+ prefix = prefix.resolve()
+ tools = prefix / "host/bin"
+ for required in ("clang", "clang++", "ld.lld", "llvm-ar", "llvm-readelf"):
+ if not (tools / required).is_file():
+ raise ValueError("missing host tool: " + required)
+ seen = set()
+ for path in sorted(tools.iterdir()):
+ if not path.is_file() or not path.stat().st_mode & 0o111:
+ raise ValueError("host tool is not executable: " + str(path))
+ try:
+ path.resolve(strict=True).relative_to(prefix)
+ except (ValueError, OSError, RuntimeError) as error:
+ raise ValueError("host tool points outside the toolchain: " + str(path)) from error
+ identity = (path.stat().st_dev, path.stat().st_ino)
+ if identity not in seen:
+ check_static_elf(path, arch or platform.machine())
+ seen.add(identity)
+
+
def source_licenses(manifest, source_root, root):
licenses = {}
for line in manifest.decode().splitlines():
@@ -33,12 +96,21 @@ def source_licenses(manifest, source_root, root):
return licenses
-def package(prefix, target, sources, output, source_root=None):
+def package(prefix, target, sources, output, source_root=None, llvm_mode="source"):
if not target or any(character not in "abcdefghijklmnopqrstuvwxyz0123456789_-" for character in target):
raise ValueError("invalid target: " + target)
if platform.system() != "Linux":
raise ValueError("packaging requires a Linux host")
prefix = prefix.resolve()
+ if llvm_mode not in ("source", "static"):
+ raise ValueError("packaging requires source or static LLVM")
+ mode = prefix / "share/musllvm/llvm-mode"
+ if mode.exists() and mode.read_text().strip() != llvm_mode:
+ raise ValueError("LLVM_MODE does not match the installed toolchain")
+ if llvm_mode == "static":
+ if not mode.is_file():
+ raise ValueError("static LLVM build marker is missing")
+ check_static_host(prefix)
for required in ("host/bin/clang", "host/bin/ld.lld", "bin/" + target + "-cc",
"sysroot/usr/lib/libc.so", "share/musllvm/resource-version"):
if not (prefix / required).is_file():
@@ -62,9 +134,13 @@ def package(prefix, target, sources, output, source_root=None):
"host": host,
"host_libc": {"name": libc_name, "version": libc_version},
"target": target,
- "llvm_mode": "source",
+ "llvm_mode": llvm_mode,
"source_manifest_sha256": hashlib.sha256(manifest).hexdigest(),
}
+ if llvm_mode == "static":
+ metadata["build_host_libc"] = metadata["host_libc"]
+ metadata["host_libc"] = {"name": "musl"}
+ metadata["host_linkage"] = "static"
root = "musllvm-" + target
generated = {
root + "/share/musllvm/sources.list": manifest,
@@ -110,12 +186,20 @@ def package(prefix, target, sources, output, source_root=None):
def main():
parser = argparse.ArgumentParser(description="Package a toolchain with bundled host tools")
parser.add_argument("--prefix", type=Path, required=True)
- parser.add_argument("--target", required=True)
- parser.add_argument("--sources", type=Path, required=True)
- parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--target")
+ parser.add_argument("--sources", type=Path)
+ parser.add_argument("--output", type=Path)
+ parser.add_argument("--llvm-mode", choices=("source", "static"), default="source")
+ parser.add_argument("--check-host", action="store_true")
args = parser.parse_args()
+ if not args.check_host and not all((args.target, args.sources, args.output)):
+ parser.error("packaging requires --target, --sources and --output")
try:
- print(package(args.prefix, args.target, args.sources, args.output))
+ if args.check_host:
+ check_static_host(args.prefix)
+ print("Verified static host tools: " + str(args.prefix))
+ else:
+ print(package(args.prefix, args.target, args.sources, args.output, llvm_mode=args.llvm_mode))
except (OSError, ValueError, subprocess.CalledProcessError) as error:
parser.exit(1, "package: " + str(error) + "\n")
diff --git a/scripts/package.sh b/scripts/package.sh
@@ -3,8 +3,11 @@ set -eu
. "$(dirname "$0")/config.sh"
-[ "$LLVM_MODE" = source ] || die "publishing requires LLVM_MODE=source"
+case "$LLVM_MODE" in
+source|static) ;;
+*) die "packaging requires LLVM_MODE=source or static" ;;
+esac
[ -f "$BUILD_DIR/stamps/runtimes" ] || die "target runtimes have not finished building"
need python3
python3 "$PROOT/scripts/package.py" --prefix "$PREFIX" --target "$TARGET" \
- --sources "$SOURCES_FILE" --output "${DIST_DIR:-$PROOT/build/releases}"
+ --sources "$SOURCES_FILE" --output "${DIST_DIR:-$PROOT/build/releases}" --llvm-mode "$LLVM_MODE"
diff --git a/scripts/publish.sh b/scripts/publish.sh
@@ -31,7 +31,7 @@ sha256sum -c SHA256SUMS
cp "$root/sources.list" sources.list
{
printf 'CI built these musllvm toolchains from commit %s.\n\n' "$GITHUB_SHA"
- printf '%s\n' 'The tools run on x86_64 Linux with glibc 2.39 or newer.' \
+ printf '%s\n' 'The compiler tools link musl statically and run on x86_64 Linux.' \
'They target x86_64-linux-musl and aarch64-linux-musl.' \
'The archives include Clang, LLD and LLVM utilities.' '' 'core sources' '------------' ''
awk 'NF && $1 !~ /^#/ { printf " %s %s\n", $1, $2 }' sources.list
diff --git a/tests/test_driver.py b/tests/test_driver.py
@@ -3,6 +3,7 @@ import io
import json
import os
from pathlib import Path
+import platform
import shutil
import subprocess
import tarfile
@@ -23,17 +24,18 @@ import sys
name = Path(sys.argv[0]).name
args = sys.argv[1:]
with open(os.environ["FAKE_LOG"], "a") as log:
- log.write(json.dumps({"tool": name, "args": args}) + "\n")
+ log.write(json.dumps({"tool": name, "args": args,
+ "sysroot": os.environ.get("MUSLLVM_SYSROOT")}) + "\n")
def write(path, value="fixture"):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value)
-if name in ("clang", "clang++"):
+if name in ("clang", "clang++", "gcc", "g++"):
version = os.environ.get("FAKE_CLANG_VERSION", "21.1.8")
if "--version" in args:
- print("clang version " + version + " (fixture)")
+ print(("clang" if name.startswith("clang") else "gcc") + " version " + version + " (fixture)")
elif "-dumpversion" in args:
print(version)
elif "-print-resource-dir" in args:
@@ -156,7 +158,7 @@ class DriverTests(unittest.TestCase):
manifest.append(f"{component} {archive.name} {digest} https://example.invalid/{archive.name}\n")
(self.root / "sources.list").write_text("".join(manifest))
self.env = os.environ.copy()
- for key in ("ARCH", "TARGET", "PREFIX", "BUILD_DIR", "SOURCES_DIR", "SOURCES_FILE", "LLVM_MODE", "JOBS", "LINK_JOBS", "HOST_CC", "HOST_CXX", "TARGET_CFLAGS", "HOST_CFLAGS", "HOST_CXXFLAGS", "HOST_LDFLAGS", "RUNNER", "MAKEFLAGS", "MFLAGS", "MUSLLVM_SYSROOT"):
+ for key in ("ARCH", "TARGET", "PREFIX", "BUILD_DIR", "SOURCES_DIR", "SOURCES_FILE", "LLVM_MODE", "BOOTSTRAP_LLVM_MODE", "JOBS", "LINK_JOBS", "HOST_CC", "HOST_CXX", "TARGET_CFLAGS", "HOST_CFLAGS", "HOST_CXXFLAGS", "HOST_LDFLAGS", "RUNNER", "MAKEFLAGS", "MFLAGS", "MUSLLVM_SYSROOT"):
self.env.pop(key, None)
self.env.update({
"PATH": str(self.tools) + os.pathsep + os.environ["PATH"],
@@ -189,6 +191,15 @@ class DriverTests(unittest.TestCase):
"\n\\ No newline at end of file\n+" + after + "\n\\ No newline at end of file\n")
return path
+ def mock_host_check(self):
+ (self.root / "scripts/package.py").write_text('''import json
+import os
+import sys
+with open(os.environ["FAKE_LOG"], "a") as stream:
+ stream.write(json.dumps({"tool": "check-host", "args": sys.argv[1:]}) + "\\n")
+sys.exit(1 if os.environ.get("FAKE_STATIC_FAIL") else 0)
+''')
+
def install_wrapper(self, name, template, prefix=None):
prefix = prefix or Path(self.temporary.name) / "relocated tools' path"
(prefix / "bin").mkdir(parents=True, exist_ok=True)
@@ -216,6 +227,64 @@ class DriverTests(unittest.TestCase):
self.run_make("show-config", *arguments, success=False)
self.assertFalse((self.root / "build").exists())
+ def test_invalid_static_bootstrap_mode_fails_before_work(self):
+ self.run_make("show-config", "LLVM_MODE=static", "BOOTSTRAP_LLVM_MODE=static", success=False)
+ self.assertFalse((self.root / "build").exists())
+
+ def test_static_host_bootstrap_uses_the_native_architecture(self):
+ self.mock_host_check()
+ native = platform.machine()
+ target = "aarch64" if native == "x86_64" else "x86_64"
+ self.run_make("runtimes", "LLVM_MODE=static", "ARCH=" + target, "TARGET_CFLAGS=-Os",
+ env={**self.env, "MUSLLVM_SYSROOT": "/wrong/target/sysroot"})
+ prefix = self.root / "build" / (target + "-linux-musl")
+ work = self.root / "build/work" / (target + "-linux-musl")
+ bootstrap = work / "bootstrap/prefix"
+ options = json.loads((work / "llvm/fixture-config.json").read_text())
+ self.assertIn("-DCMAKE_C_COMPILER=" + str(bootstrap / "bin" / (native + "-linux-musl-cc")), options)
+ self.assertIn("-DCMAKE_SYSROOT=" + str(bootstrap / "sysroot"), options)
+ self.assertIn("-DLLVM_HOST_TRIPLE=" + native + "-linux-musl", options)
+ self.assertIn("-DBUILD_SHARED_LIBS=OFF", options)
+ self.assertIn("-DLLVM_LINK_LLVM_DYLIB=OFF", options)
+ self.assertIn("-DLLVM_ENABLE_PLUGINS=OFF", options)
+ self.assertIn("-static", next(value for value in options if value.startswith("-DCMAKE_EXE_LINKER_FLAGS=")))
+ native_options = json.loads((work / "bootstrap/work/runtimes/fixture-config.json").read_text())
+ self.assertIn("-DCMAKE_C_COMPILER_TARGET=" + native + "-linux-musl", native_options)
+ self.assertNotIn("-Os", next(value for value in native_options if value.startswith("-DCMAKE_C_FLAGS=")))
+ target_options = json.loads((work / "runtimes/fixture-config.json").read_text())
+ self.assertIn("-DCMAKE_C_COMPILER_TARGET=" + target + "-linux-musl", target_options)
+ self.assertEqual((prefix / "share/musllvm/llvm-mode").read_text(), "static\n")
+ self.assertTrue(any(item["tool"] == "check-host" for item in self.commands()))
+ self.assertEqual(os.readlink(prefix / "libexec/clang"), "../host/bin/clang")
+ self.assertTrue(all(item["sysroot"] is None for item in self.commands() if item["tool"] == "cmake"))
+ count = sum(item["tool"] == "cmake" for item in self.commands())
+ self.run_make("runtimes", "LLVM_MODE=static", "ARCH=" + target, "TARGET_CFLAGS=-Os")
+ self.assertEqual(sum(item["tool"] == "cmake" for item in self.commands()), count)
+ self.run_make("runtimes", "LLVM_MODE=static", "ARCH=" + target, "TARGET_CFLAGS=-Os",
+ "BOOTSTRAP_LLVM_MODE=source", success=False)
+
+ def test_static_host_can_bootstrap_llvm_with_gcc(self):
+ self.mock_host_check()
+ for tool in ("gcc", "g++"):
+ (self.tools / tool).symlink_to(self.fake)
+ self.run_make("toolchain", "LLVM_MODE=static", "BOOTSTRAP_LLVM_MODE=source", "HOST_CC=gcc", "HOST_CXX=g++")
+ work = self.root / "build/work/x86_64-linux-musl"
+ options = json.loads((work / "bootstrap/work/llvm/fixture-config.json").read_text())
+ self.assertIn("-DCMAKE_C_COMPILER=" + str(self.tools / "gcc"), options)
+ self.assertIn("-DCMAKE_CXX_COMPILER=" + str(self.tools / "g++"), options)
+ self.assertTrue((work / "stamps/llvm").exists())
+
+ def test_failed_static_host_check_prevents_target_build(self):
+ self.mock_host_check()
+ self.run_make("runtimes", "LLVM_MODE=static", success=False,
+ env={**self.env, "FAKE_STATIC_FAIL": "1"})
+ work = self.root / "build/work/x86_64-linux-musl"
+ self.assertTrue((work / "bootstrap/work/stamps/runtimes").exists())
+ self.assertFalse((work / "stamps/llvm").exists())
+ self.assertFalse((work / "stamps/headers").exists())
+ self.run_make("runtimes", "LLVM_MODE=static")
+ self.assertTrue((work / "stamps/runtimes").exists())
+
def test_old_system_clang_is_rejected_before_fetch(self):
result = self.run_make("runtimes", success=False,
env={**self.env, "FAKE_CLANG_VERSION": "20.1.8"})
diff --git a/tests/test_release.py b/tests/test_release.py
@@ -5,6 +5,7 @@ import os
from pathlib import Path
import platform
import shutil
+import struct
import subprocess
import tarfile
import tempfile
@@ -49,6 +50,77 @@ else:
'''
+def host_elf(arch="x86_64", pie=False, interpreter=False, needed=False):
+ count = 1 + interpreter + (pie or needed)
+ start = 64 + 56 * count
+ payload = b"\x90"
+ segments = []
+ if interpreter:
+ loader = b"/lib/fixture-loader.so\0"
+ segments.append((3, start + len(payload), len(loader)))
+ payload += loader
+ if pie or needed:
+ dynamic = struct.pack("<qQ", 1 if needed else 0x6ffffffb, 1)
+ dynamic += struct.pack("<qQ", 0, 0)
+ segments.append((2, start + len(payload), len(dynamic)))
+ payload += dynamic
+ size = start + len(payload)
+ header = b"\x7fELF\x02\x01\x01" + b"\0" * 9
+ header += struct.pack("<HHIQQQIHHHHHH", 3 if pie else 2,
+ {"x86_64": 62, "aarch64": 183}[arch], 1, 0x400000 + start,
+ 64, 0, 0, 64, 56, count, 0, 0, 0)
+ program = struct.pack("<IIQQQQQQ", 1, 5, 0, 0x400000, 0x400000, size, size, 4096)
+ for kind, offset, length in segments:
+ program += struct.pack("<IIQQQQQQ", kind, 4, offset, 0x400000 + offset, 0,
+ length, length, 8)
+ return header + program + payload
+
+
+class StaticHostTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix="musllvm-static-test-")
+ self.addCleanup(self.temporary.cleanup)
+ self.path = Path(self.temporary.name) / "clang"
+
+ def test_static_executables_and_static_pie_for_both_hosts(self):
+ for arch in ("x86_64", "aarch64"):
+ for pie in (False, True):
+ with self.subTest(arch=arch, pie=pie):
+ self.path.write_bytes(host_elf(arch, pie=pie))
+ PACKAGE.check_static_elf(self.path, arch)
+
+ def test_dynamic_loader_is_rejected_without_a_needed_entry(self):
+ self.path.write_bytes(host_elf(interpreter=True))
+ with self.assertRaisesRegex(ValueError, "dynamic loader"):
+ PACKAGE.check_static_elf(self.path, "x86_64")
+
+ def test_needed_library_is_rejected_without_a_loader(self):
+ self.path.write_bytes(host_elf(pie=True, needed=True))
+ with self.assertRaisesRegex(ValueError, "shared library"):
+ PACKAGE.check_static_elf(self.path, "x86_64")
+
+ def test_wrong_host_and_malformed_elf_are_rejected(self):
+ valid = host_elf()
+ for content in (b"#!/bin/sh\n", valid[:40], valid[:80],
+ valid[:5] + b"\x02" + valid[6:],
+ valid[:16] + struct.pack("<H", 1) + valid[18:]):
+ with self.subTest(content=content[:20]):
+ self.path.write_bytes(content)
+ with self.assertRaises(ValueError):
+ PACKAGE.check_static_elf(self.path, "x86_64")
+ self.path.write_bytes(host_elf("aarch64"))
+ with self.assertRaisesRegex(ValueError, "architecture"):
+ PACKAGE.check_static_elf(self.path, "x86_64")
+
+ def test_truncated_or_unterminated_dynamic_section_is_rejected(self):
+ content = host_elf(pie=True)
+ for invalid in (content[:-1], content[:-16] + struct.pack("<qQ", 21, 0)):
+ with self.subTest(length=len(invalid)):
+ self.path.write_bytes(invalid)
+ with self.assertRaises(ValueError):
+ PACKAGE.check_static_elf(self.path, "x86_64")
+
+
class PackageTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="musllvm-package-test-")
@@ -76,8 +148,58 @@ class PackageTests(unittest.TestCase):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(relative + "\n")
- def package(self, target=None):
- return PACKAGE.package(self.prefix, target or self.target, self.sources, self.output, self.source_root)
+ def package(self, target=None, mode="source"):
+ return PACKAGE.package(self.prefix, target or self.target, self.sources, self.output,
+ self.source_root, llvm_mode=mode)
+
+ def install_static_host(self):
+ for name in ("clang", "clang++", "ld.lld", "llvm-ar", "llvm-readelf"):
+ path = self.prefix / "host/bin" / name
+ path.write_bytes(host_elf(platform.machine()))
+ path.chmod(0o755)
+ (self.prefix / "share/musllvm/llvm-mode").write_text("static\n")
+
+ def test_static_cross_package_records_the_compiler_host_runtime(self):
+ self.install_static_host()
+ target = "aarch64-linux-musl" if platform.machine() == "x86_64" else "x86_64-linux-musl"
+ (self.prefix / "bin" / (target + "-cc")).write_text("fixture\n")
+ with patch.object(PACKAGE.platform, "libc_ver", return_value=("glibc", "2.39")):
+ archive = self.package(target, mode="static")
+ with tarfile.open(archive) as stream:
+ metadata = json.load(stream.extractfile("musllvm-" + target + "/share/musllvm/build-info.json"))
+ self.assertEqual(metadata["llvm_mode"], "static")
+ self.assertEqual(metadata["host"], platform.machine() + "-linux")
+ self.assertEqual(metadata["host_libc"], {"name": "musl"})
+ self.assertEqual(metadata["host_linkage"], "static")
+ self.assertEqual(metadata["build_host_libc"], {"name": "glibc", "version": "2.39"})
+
+ def test_static_packaging_checks_every_host_executable(self):
+ self.install_static_host()
+ extra = self.prefix / "host/bin/llvm-extra"
+ extra.write_bytes(host_elf(platform.machine(), needed=True))
+ extra.chmod(0o755)
+ with self.assertRaisesRegex(ValueError, "shared library"):
+ self.package(mode="static")
+ self.assertFalse(self.output.exists())
+
+ def test_packaging_rejects_a_missing_or_wrong_build_mode(self):
+ self.install_static_host()
+ with self.assertRaisesRegex(ValueError, "does not match"):
+ self.package()
+ (self.prefix / "share/musllvm/llvm-mode").unlink()
+ with self.assertRaisesRegex(ValueError, "marker is missing"):
+ self.package(mode="static")
+
+ def test_static_host_requires_bundled_executable_tools(self):
+ self.install_static_host()
+ path = self.prefix / "host/bin/llvm-ar"
+ path.chmod(0o644)
+ with self.assertRaisesRegex(ValueError, "not executable"):
+ self.package(mode="static")
+ path.unlink()
+ path.symlink_to("/bin/sh")
+ with self.assertRaisesRegex(ValueError, "outside"):
+ self.package(mode="static")
def test_archive_preserves_links_modes_and_source_metadata(self):
archive = self.package()