TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Toolchain Resolution

Toolchain Resolution

A rule shouldn't hard-code which compiler it uses. cc_binary asks for "a C++ toolchain", go_binary for "a Go toolchain", and Bazel resolves a concrete toolchain for each target from what's registered, using the target and execution platforms. That's how one BUILD file builds with GCC on Linux, Clang on macOS and MSVC on Windows, or for ARM from x86.

The pieces:

Piece What it is
toolchain_type(name = "…") an interface, e.g. @bazel_tools//tools/cpp:toolchain_type
a toolchain rule (e.g. cc_toolchain, go_toolchain, your own) a target that returns platform_common.ToolchainInfo(...) with the tool's details
toolchain(...) glue: which toolchain_type it implements, the implementing target, and exec_compatible_with / target_compatible_with constraints
register_toolchains(...) in MODULE.bazel makes toolchain targets candidates (also --extra_toolchains on the command line)
toolchains = ["//x:type"] on a rule + ctx.toolchains["//x:type"] how a rule asks for and uses the resolved toolchain

Resolution goes, for each target: for each required toolchain type, take the registered toolchains in order; skip those whose target_compatible_with doesn't match the target platform; pick the first one that also has a compatible execution platform. The first match wins.

Build your own toolchain

A "formatter" toolchain type with two implementations: plain text for the host platform, and a decorated variant for a platform with a custom style constraint. One rule uses whichever toolchain resolution selects:

bash · try it yourself
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
module(name = "tc_demo")
bazel_dep(name = "platforms", version = "1.0.0")
register_toolchains("//toolchains:all")
EOF
mkdir -p toolchains plat banner
cat > plat/BUILD.bazel <<'EOF'
constraint_setting(name = "style")
constraint_value(name = "fancy", constraint_setting = ":style", visibility = ["//visibility:public"])
platform(name = "fancy_linux", parents = ["@platforms//host"], constraint_values = [":fancy"])
EOF
cat > toolchains/defs.bzl <<'EOF'
def _formatter_toolchain_impl(ctx):
    return [platform_common.ToolchainInfo(prefix = ctx.attr.prefix, suffix = ctx.attr.suffix)]

formatter_toolchain = rule(
    implementation = _formatter_toolchain_impl,
    attrs = {"prefix": attr.string(), "suffix": attr.string()},
)

def _banner_impl(ctx):
    tc = ctx.toolchains["//toolchains:formatter_type"]
    out = ctx.actions.declare_file(ctx.label.name + ".txt")
    ctx.actions.write(out, tc.prefix + ctx.attr.text + tc.suffix + "\n")
    return [DefaultInfo(files = depset([out]))]

banner = rule(
    implementation = _banner_impl,
    attrs = {"text": attr.string()},
    toolchains = ["//toolchains:formatter_type"],
)
EOF
cat > toolchains/BUILD.bazel <<'EOF'
load(":defs.bzl", "formatter_toolchain")

toolchain_type(name = "formatter_type", visibility = ["//visibility:public"])

formatter_toolchain(name = "fancy_impl", prefix = "*** ", suffix = " ***")
formatter_toolchain(name = "plain_impl", prefix = "", suffix = "")

# Order matters: the first compatible toolchain wins.
toolchain(
    name = "fancy",
    toolchain = ":fancy_impl",
    toolchain_type = ":formatter_type",
    target_compatible_with = ["//plat:fancy"],
)
toolchain(
    name = "plain",
    toolchain = ":plain_impl",
    toolchain_type = ":formatter_type",
)
EOF
cat > banner/BUILD.bazel <<'EOF'
load("//toolchains:defs.bzl", "banner")
banner(name = "welcome", text = "Welcome to the shop")
EOF
bazel build //banner:welcome 2>/dev/null && cat bazel-bin/banner/welcome.txt
bazel build --platforms=//plat:fancy_linux //banner:welcome 2>/dev/null && cat bazel-bin/banner/welcome.txt
echo "== --toolchain_resolution_debug"
bazel build --toolchain_resolution_debug=//toolchains:formatter_type //banner:welcome 2>&1 \
  | grep -E 'ToolchainResolution: +(Rejected|Toolchain|Selected)' | sed 's/^ *ToolchainResolution: *//' | cut -c1-150
Welcome to the shop
*** Welcome to the shop ***
== --toolchain_resolution_debug
Rejected toolchain //toolchains:fancy (resolves to //toolchains:fancy_impl) ; mismatching values: fancy
Toolchain //toolchains:plain (resolves to //toolchains:plain_impl) is compatible with target platform, searching for execution platforms:
Selected //toolchains:plain_impl to run on execution platform @@platforms//host:host

The banner rule never names a toolchain; it asks for the type and uses whatever ToolchainInfo it gets. The debug output (for the host platform) shows the reasoning per candidate: fancy is rejected for mismatching values: fancy, plain has no constraints, so it is compatible and selected. With --platforms=//plat:fancy_linux the first candidate matches and wins. That message is the first thing to read when Bazel says "No matching toolchains found".

The C++ toolchain in this image

rules_cc auto-configures a C++ toolchain from the system compiler (cc_configure) and registers it. Its resolution, trimmed:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir app
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "app", srcs = ["main.cc"])\n' > app/BUILD.bazel
echo 'int main() { return 0; }' > app/main.cc
bazel build --toolchain_resolution_debug='@bazel_tools//tools/cpp:toolchain_type' //app 2>&1 \
  | grep -E 'ToolchainResolution: +(Rejected|Toolchain .* is compatible|Selected)' \
  | sed 's/^ *ToolchainResolution: *//; s/@@rules_cc++cc_configure_extension+//g' | cut -c1-110
Rejected toolchain local_config_cc_toolchains//:cc-toolchain-armeabi-v7a (resolves to local_config_cc//:cc-com
Toolchain local_config_cc_toolchains//:cc-toolchain-k8 (resolves to local_config_cc//:cc-compiler-k8) is compa
Selected local_config_cc//:cc-compiler-k8 to run on execution platform @@platforms//host:host

The generated local_config_cc_toolchains repository declares two toolchains: one for the host (k8, i.e. x86-64 Linux) and an armeabi-v7a entry that's rejected because its constraints say ARM/Android. Real projects that need reproducible C++ builds register a hermetic toolchain instead, one that downloads a pinned compiler and sysroot:

python
# Zig-based cross-compiling toolchain (MODULE.bazel), not run here
bazel_dep(name = "hermetic_cc_toolchain", version = "4.0.1")
toolchains = use_extension("@hermetic_cc_toolchain//toolchain:ext.bzl", "toolchains")
use_repo(toolchains, "zig_sdk")
register_toolchains("@zig_sdk//toolchain:linux_amd64_gnu.2.31", "@zig_sdk//toolchain:linux_arm64_gnu.2.31")

toolchains_llvm does the same with a pinned LLVM release. Registered first, they win over the auto-configured one.

Execution platforms and exec_compatible_with

A toolchain can also say where it can run (exec_compatible_with). A remote-execution setup registers the workers as execution platforms (register_execution_platforms or --extra_execution_platforms) so that Bazel only picks toolchains whose binaries can run on those workers. The host platform is always an execution platform, which is why everything in this course resolves locally.

Test yourself

What does a rule declare to use a toolchain?

  1. The compiler's path
  2. toolchains = ["//x:type"], then reads ctx.toolchains["//x:type"]
  3. A deps entry on the compiler
  4. An environment variable

Two registered toolchains are both compatible with the target platform. Which one is selected?

  1. The newest
  2. The first one in registration order
  3. Both
  4. Bazel fails as ambiguous

Which flag shows why a toolchain was rejected or selected?

  1. --explain
  2. --toolchain_resolution_debug=<regex of types>
  3. --verbose_failures
  4. --announce_rc