Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions swift/internal/feature_names.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,13 @@ SWIFT_FEATURE_LLD_GC_WORKAROUND = "swift.lld_gc_workaround"
# objects if you know that isn't required.
SWIFT_FEATURE_OBJC_LINK_FLAGS = "swift.objc_link_flag"

# If enabled, binaries linked with a Linux Swift toolchain will
# statically link the Swift standard library and runtime by resolving them from
# the toolchain's `lib/swift_static/{os}` directory instead of the shared
# `lib/swift/{os}` directory, and will omit the runtime rpath entry that points
# at the shared library directory.
SWIFT_FEATURE_STATIC_STDLIB = "swift.static_stdlib"

# If enabled, requests the `-enforce-exclusivity=checked` swiftc flag which
# enables runtime checking of exclusive memory access on mutation.
SWIFT_FEATURE_CHECKED_EXCLUSIVITY = "swift.checked_exclusivity"
Expand Down
20 changes: 15 additions & 5 deletions swift/toolchains/swift_toolchain.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ load("//swift/internal:autolinking.bzl", "autolink_extract_action_configs")
load(
"//swift/internal:feature_names.bzl",
"SWIFT_FEATURE_MODULE_MAP_HOME_IS_CWD",
"SWIFT_FEATURE_STATIC_STDLIB",
"SWIFT_FEATURE_USE_AUTOLINK_EXTRACT",
"SWIFT_FEATURE_USE_GLOBAL_INDEX_STORE",
"SWIFT_FEATURE_USE_MODULE_WRAP",
Expand Down Expand Up @@ -362,7 +363,8 @@ def _swift_unix_linkopts_cc_info(
toolchain_label,
toolchain_root,
additional_inputs,
additional_rpaths):
additional_rpaths,
static_stdlib):
"""Returns a `CcInfo` containing flags that should be passed to the linker.

The provider returned by this function will be used as an implicit
Expand All @@ -378,15 +380,19 @@ def _swift_unix_linkopts_cc_info(
toolchain_root: The toolchain's root directory.
additional_inputs: depset of File objects to add to link actions.
additional_rpaths: list of additional RPATH to add at link time.
static_stdlib: If `True`, link the Swift standard library and runtime
statically by sourcing them from `lib/swift_static/{os}` instead of
`lib/swift/{os}` and omitting the runtime rpath entry.

Returns:
A `CcInfo` provider that will provide linker flags to binaries that
depend on Swift targets.
"""

# TODO(#8): Support statically linking the Swift runtime.
platform_lib_dir = "{toolchain_root}/lib/swift/{os}".format(
stdlib_subdir = "swift_static" if static_stdlib else "swift"
platform_lib_dir = "{toolchain_root}/lib/{stdlib_subdir}/{os}".format(
os = os,
stdlib_subdir = stdlib_subdir,
toolchain_root = toolchain_root,
)

Expand All @@ -398,7 +404,10 @@ def _swift_unix_linkopts_cc_info(
linkopts = [
"-pie",
"-L{}".format(platform_lib_dir),
"-Wl,-rpath,{}".format(platform_lib_dir),
]
if not static_stdlib:
linkopts.append("-Wl,-rpath,{}".format(platform_lib_dir))
linkopts.extend([
"-lm",
"-lstdc++",
"-lrt",
Expand All @@ -408,7 +417,7 @@ def _swift_unix_linkopts_cc_info(
] + [
"-Wl,-rpath,{}".format(rpath)
for rpath in additional_rpaths
]
])

return CcInfo(
linking_context = cc_common.create_linking_context(
Expand Down Expand Up @@ -495,6 +504,7 @@ def _swift_toolchain_impl(ctx):
toolchain_root,
ctx.attr.swift_tools[SwiftToolsInfo].additional_inputs if ctx.attr.swift_tools else [],
additional_rpaths,
SWIFT_FEATURE_STATIC_STDLIB in ctx.features,
)

# TODO: Remove once we drop bazel 7.x support
Expand Down
3 changes: 3 additions & 0 deletions test/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ load(":private_deps_tests.bzl", "private_deps_test_suite")
load(":private_swiftinterface_tests.bzl", "private_swiftinterface_test_suite")
load(":runtime_deps_tests.bzl", "runtime_deps_test_suite")
load(":split_derived_files_tests.bzl", "split_derived_files_test_suite")
load(":static_stdlib_tests.bzl", "static_stdlib_test_suite")
load(":swift_binary_linking_tests.bzl", "swift_binary_linking_test_suite")
load(":swift_through_non_swift_tests.bzl", "swift_through_non_swift_test_suite")
load(":swift_toolchain_tests.bzl", "swift_toolchain_test_suite")
Expand Down Expand Up @@ -70,6 +71,8 @@ private_deps_test_suite(name = "private_deps")

split_derived_files_test_suite(name = "split_derived_files")

static_stdlib_test_suite(name = "static_stdlib")

swift_binary_linking_test_suite(name = "swift_binary_rules")

swift_through_non_swift_test_suite(name = "swift_through_non_swift")
Expand Down
14 changes: 14 additions & 0 deletions test/fixtures/static_stdlib/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
load("//swift:swift_binary.bzl", "swift_binary")
load("//test/fixtures:common.bzl", "FIXTURE_TAGS")

package(
default_visibility = ["//test:__subpackages__"],
)

licenses(["notice"])

swift_binary(
name = "bin",
srcs = ["main.swift"],
tags = FIXTURE_TAGS,
)
1 change: 1 addition & 0 deletions test/fixtures/static_stdlib/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("hello, static stdlib")
5 changes: 4 additions & 1 deletion test/rules/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ bzl_library(
],
)

exports_files(["swift_shell_runner.sh.template"])
exports_files([
"swift_shell_runner.sh.template",
"verify_static_stdlib.sh",
])
48 changes: 48 additions & 0 deletions test/rules/static_stdlib_link_test.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright 2026 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0

"""Transition rule that forwards a `swift_binary` built with `swift.static_stdlib`.

Used to wrap a `swift_binary` target so that it can be consumed as `data` by an
`sh_test` that inspects the linked ELF for dynamic Swift runtime references.
"""

def _enable_static_stdlib_impl(settings, _attr):
existing = list(settings["//command_line_option:features"])
if "swift.static_stdlib" not in existing:
existing.append("swift.static_stdlib")
return {"//command_line_option:features": existing}

_enable_static_stdlib_transition = transition(
implementation = _enable_static_stdlib_impl,
inputs = ["//command_line_option:features"],
outputs = ["//command_line_option:features"],
)

def _with_static_stdlib_impl(ctx):
target = ctx.attr.target[0]
return [
DefaultInfo(
files = target[DefaultInfo].files,
runfiles = target[DefaultInfo].default_runfiles,
),
]

with_static_stdlib = rule(
attrs = {
"target": attr.label(
cfg = _enable_static_stdlib_transition,
mandatory = True,
),
},
doc = """\
Rebuilds `target` with `--features=swift.static_stdlib` added and forwards its
files. Intended to be referenced via `data` on an `sh_test`.
""",
implementation = _with_static_stdlib_impl,
)
38 changes: 38 additions & 0 deletions test/rules/verify_static_stdlib.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Copyright 2026 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0

set -euo pipefail

binary="${1:?usage: verify_static_stdlib.sh <binary>}"

if [[ ! -x "$binary" ]]; then
echo "verify_static_stdlib: binary '$binary' not found or not executable" >&2
exit 1
fi

if ! command -v readelf >/dev/null 2>&1; then
echo "verify_static_stdlib: readelf not available; cannot verify" >&2
exit 1
fi

needed=$(readelf -d "$binary" | awk '/\(NEEDED\)/ {print $NF}' | tr -d '[]')

swift_dyn=$(printf '%s\n' "$needed" | grep -E '^libswift(Core|_Concurrency|_StringProcessing|_RegexParser|Glibc|Dispatch|Foundation)' || true)

if [[ -n "$swift_dyn" ]]; then
echo "verify_static_stdlib: Swift runtime was dynamically linked — expected static." >&2
echo "Dynamic swift NEEDED entries:" >&2
printf ' %s\n' $swift_dyn >&2
echo >&2
echo "Full NEEDED list:" >&2
printf ' %s\n' $needed >&2
exit 1
fi

echo "verify_static_stdlib: OK — no dynamic Swift runtime NEEDED entries in $binary"
45 changes: 45 additions & 0 deletions test/static_stdlib_tests.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Copyright 2026 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0

"""Tests that `--features=swift.static_stdlib` actually links the Swift runtime statically."""

load("@rules_shell//shell:sh_test.bzl", "sh_test")
load("//test/rules:static_stdlib_link_test.bzl", "with_static_stdlib")

def static_stdlib_test_suite(name, tags = []):
"""Verifies that binaries built with `swift.static_stdlib` are statically linked.

Produces one `sh_test` (Linux-only) that inspects the linked ELF with
`readelf -d` and asserts no Swift runtime libraries (`libswiftCore`,
`libswift_Concurrency`, etc.) appear as `NEEDED` entries.

Args:
name: The base name for targets created by this macro.
tags: Additional tags to apply to each target.
"""
all_tags = [name] + tags

with_static_stdlib(
name = "{}_bin".format(name),
tags = all_tags + ["manual"],
target = "//test/fixtures/static_stdlib:bin",
)

sh_test(
name = "{}_not_dynamically_linked".format(name),
srcs = ["//test/rules:verify_static_stdlib.sh"],
args = ["$(rootpath :{}_bin)".format(name)],
data = [":{}_bin".format(name)],
tags = all_tags,
target_compatible_with = ["@platforms//os:linux"],
)

native.test_suite(
name = name,
tags = all_tags,
)