相约 2023 年 BazelCon 将于 10 月 24 日至 25 日在 Google 慕尼黑举办!了解详情

工具链

报告问题 查看源代码

本页介绍了工具链框架,工具链作者可以借助该框架将规则逻辑与基于平台的工具选择分离开来。建议您先阅读规则平台页面,然后再继续。本页面介绍了需要工具链的原因、定义和使用工具链的方法,以及 Bazel 如何根据平台限制选择适当的工具链。

动机

我们先来看一下工具链旨在解决的问题。假设您正在编写规则来支持“bar”编程语言。您的 bar_binary 规则将使用 barc 编译器编译 *.bar 文件,编译器本身会构建为您的工作区中的另一个目标。由于编写 bar_binary 目标的用户不应要求指定对编译器的依赖项,因此请将其作为隐式属性添加到规则定义中,使其成为隐式依赖项。

bar_binary = rule(
    implementation = _bar_binary_impl,
    attrs = {
        "srcs": attr.label_list(allow_files = True),
        ...
        "_compiler": attr.label(
            default = "//bar_tools:barc_linux",  # the compiler running on linux
            providers = [BarcInfo],
        ),
    },
)

//bar_tools:barc_linux 现在是每个 bar_binary 目标的依赖项,因此应在任何 bar_binary 目标之前进行构建。就像其他任何属性一样,可以通过规则的实现函数访问该模式:

BarcInfo = provider(
    doc = "Information about how to invoke the barc compiler.",
    # In the real world, compiler_path and system_lib might hold File objects,
    # but for simplicity they are strings for this example. arch_flags is a list
    # of strings.
    fields = ["compiler_path", "system_lib", "arch_flags"],
)

def _bar_binary_impl(ctx):
    ...
    info = ctx.attr._compiler[BarcInfo]
    command = "%s -l %s %s" % (
        info.compiler_path,
        info.system_lib,
        " ".join(info.arch_flags),
    )
    ...

这里的问题在于,编译器的标签被硬编码为 bar_binary,但不同的目标可能需要不同的编译器,具体取决于它们针对什么平台构建,以及它们在什么平台上构建 - 分别称为目标平台执行平台。此外,规则作者不一定知道所有可用的工具和平台,因此在规则的定义中对其进行硬编码是不可行的。

一种不太理想的解决方案是将 _compiler 特性设为非私有性,从而将负担转移到用户身上。然后,可以将各个目标硬编码到一个平台或另一个平台上。

bar_binary(
    name = "myprog_on_linux",
    srcs = ["mysrc.bar"],
    compiler = "//bar_tools:barc_linux",
)

bar_binary(
    name = "myprog_on_windows",
    srcs = ["mysrc.bar"],
    compiler = "//bar_tools:barc_windows",
)

如需改进此解决方案,您可以使用 select 根据平台选择 compiler

config_setting(
    name = "on_linux",
    constraint_values = [
        "@platforms//os:linux",
    ],
)

config_setting(
    name = "on_windows",
    constraint_values = [
        "@platforms//os:windows",
    ],
)

bar_binary(
    name = "myprog",
    srcs = ["mysrc.bar"],
    compiler = select({
        ":on_linux": "//bar_tools:barc_linux",
        ":on_windows": "//bar_tools:barc_windows",
    }),
)

但是,对每个 bar_binary 用户而言,这非常繁琐而复杂。如果此样式未在整个工作区中一致地使用,则会导致 build 能够在单一平台上正常运行,但在扩展到多平台场景时则会失败。此外,它也不会解决无需修改现有规则或目标即可为新平台和编译器添加支持的问题。

工具链框架通过添加额外的间接性解决了这个问题。从本质上讲,声明您的规则依赖于一个目标系列(工具链类型)的成员,Bazel 会根据适用的平台限制自动将其解析为特定目标(工具链)。规则作者和目标作者都不需要知道完整的可用平台和工具链集。

编写使用工具链的规则

在工具链框架下,规则需要依赖于工具,而不是直接依赖于工具。工具链类型是一个简单的目标,表示一系列针对不同平台提供相同角色的工具。例如,您可以声明一个表示条形编译器的类型:

# By convention, toolchain_type targets are named "toolchain_type" and
# distinguished by their package path. So the full path for this would be
# //bar_tools:toolchain_type.
toolchain_type(name = "toolchain_type")

上一部分中的规则定义已修改,因此声明不会使用编译器作为属性,而是声明其使用 //bar_tools:toolchain_type 工具链。

bar_binary = rule(
    implementation = _bar_binary_impl,
    attrs = {
        "srcs": attr.label_list(allow_files = True),
        ...
        # No `_compiler` attribute anymore.
    },
    toolchains = ["//bar_tools:toolchain_type"],
)

实现函数现在使用工具链类型作为键,在 ctx.toolchains(而非 ctx.attr)下访问此依赖项。

def _bar_binary_impl(ctx):
    ...
    info = ctx.toolchains["//bar_tools:toolchain_type"].barcinfo
    # The rest is unchanged.
    command = "%s -l %s %s" % (
        info.compiler_path,
        info.system_lib,
        " ".join(info.arch_flags),
    )
    ...

ctx.toolchains["//bar_tools:toolchain_type"] 会返回任何 Bazel 将工具链依赖项解析为目标的 ToolchainInfo 提供程序ToolchainInfo 对象的字段由底层工具的规则设置;在下一部分中,该规则进行了定义,使得 barcinfo 字段封装了 BarcInfo 对象。

下文介绍了 Bazel 将工具链解析为目标的过程。实际上,只有经过解析的工具链目标才是 bar_binary 目标的依赖项,而不是整个候选工具链。

必需和可选工具链

默认情况下,当规则使用裸标签表示工具链类型依赖项时(如上所示),工具链类型被视为“强制”。如果 Bazel 找不到某个强制工具链类型的匹配工具链(请参阅下方的工具链解析),则会导致错误和分析停止。

您可以改为声明可选的工具链类型依赖项,如下所示:

bar_binary = rule(
    ...
    toolchains = [
        config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False),
    ],
)

当无法解析可选工具链类型时,系统会继续进行分析,并且 ctx.toolchains["//bar_tools:toolchain_type"] 的结果为 None

config_common.toolchain_type 函数默认为必需函数。

可以使用以下表单:

  • 强制工具链类型:
    • toolchains = ["//bar_tools:toolchain_type"]
    • toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type")]
    • toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = True)]
  • 可选的工具链类型:
    • toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False)]
bar_binary = rule(
    ...
    toolchains = [
        "//foo_tools:toolchain_type",
        config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False),
    ],
)

您也可以在同一规则中混搭表单。但是,如果多次列出同一工具链类型,则它会采用最严格的版本,其中必须比强制模式更严格。

编写使用工具链的方面

方面可以访问与规则相同的工具链 API:您可以定义所需的工具链类型,通过上下文访问工具链,并使用这些工具链使用工具链生成新操作。

bar_aspect = aspect(
    implementation = _bar_aspect_impl,
    attrs = {},
    toolchains = ['//bar_tools:toolchain_type'],
)

def _bar_aspect_impl(target, ctx):
  toolchain = ctx.toolchains['//bar_tools:toolchain_type']
  # Use the toolchain provider like in a rule.
  return []

定义工具链

如需为给定的工具链类型定义一些工具链,您需要具备三项条件:

  1. 表示特定语言规则或工具套件的规则。按照惯例,此规则的名称以“_toolchain”为后缀。

    1. 注意\_toolchain 规则无法创建任何构建操作。而是从其他规则收集工件并将其转发到使用工具链的规则。该规则负责创建所有构建操作。
  2. 此规则类型的多个目标,表示适用于不同平台的工具或工具版本。

  3. 对于每个此类目标,这是通用 toolchain 规则的关联目标,以提供工具链框架使用的元数据。此 toolchain 目标也指的是与此工具链关联的 toolchain_type。这意味着,给定的 _toolchain 规则可以与任何 toolchain_type 关联,并且只能在使用此 _toolchain 规则的 toolchain 实例中将该规则与 toolchain_type 相关联。

我们运行中的示例是 bar_toolchain 规则的定义。我们的示例中只有一个编译器,但链接器等其他工具也可以分组在该工具下。

def _bar_toolchain_impl(ctx):
    toolchain_info = platform_common.ToolchainInfo(
        barcinfo = BarcInfo(
            compiler_path = ctx.attr.compiler_path,
            system_lib = ctx.attr.system_lib,
            arch_flags = ctx.attr.arch_flags,
        ),
    )
    return [toolchain_info]

bar_toolchain = rule(
    implementation = _bar_toolchain_impl,
    attrs = {
        "compiler_path": attr.string(),
        "system_lib": attr.string(),
        "arch_flags": attr.string_list(),
    },
)

规则必须返回一个 ToolchainInfo 提供程序,该提供程序将成为使用方规则使用 ctx.toolchains 和工具链类型的标签检索的对象。与 struct 一样,ToolchainInfo 可以存储任意字段-值对。在工具链类型上应明确记录关于哪些字段会添加到 ToolchainInfo。在此示例中,这些值会封装在 BarcInfo 对象中,以便重复使用上面定义的架构;此样式可能对验证和代码重用很有用。

现在,您可以定义特定 barc 编译器的目标。

bar_toolchain(
    name = "barc_linux",
    arch_flags = [
        "--arch=Linux",
        "--debug_everything",
    ],
    compiler_path = "/path/to/barc/on/linux",
    system_lib = "/usr/lib/libbarc.so",
)

bar_toolchain(
    name = "barc_windows",
    arch_flags = [
        "--arch=Windows",
        # Different flags, no debug support on windows.
    ],
    compiler_path = "C:\\path\\on\\windows\\barc.exe",
    system_lib = "C:\\path\\on\\windows\\barclib.dll",
)

最后,为两个 bar_toolchain 目标创建 toolchain 定义。这些定义将特定于语言的目标与工具链类型相关联,并提供限制条件信息来告知 Bazel 何时适合给定平台。

toolchain(
    name = "barc_linux_toolchain",
    exec_compatible_with = [
        "@platforms//os:linux",
        "@platforms//cpu:x86_64",
    ],
    target_compatible_with = [
        "@platforms//os:linux",
        "@platforms//cpu:x86_64",
    ],
    toolchain = ":barc_linux",
    toolchain_type = ":toolchain_type",
)

toolchain(
    name = "barc_windows_toolchain",
    exec_compatible_with = [
        "@platforms//os:windows",
        "@platforms//cpu:x86_64",
    ],
    target_compatible_with = [
        "@platforms//os:windows",
        "@platforms//cpu:x86_64",
    ],
    toolchain = ":barc_windows",
    toolchain_type = ":toolchain_type",
)

使用上述相对路径语法表明,这些定义都位于同一软件包中,但工具链类型、特定语言的工具链目标和 toolchain 定义目标不能全部位于不同的软件包中。

如需查看实际示例,请参阅 go_toolchain

工具链和配置

规则作者需要考虑的一个重要问题是,分析 bar_toolchain 目标后,它会看到哪些配置,以及应将哪些转换用于依赖项?上面的示例使用的是字符串属性,但如果依赖于 Bazel 代码库中其他目标的更复杂的工具链,会发生什么情况?

下面我们来看一个更复杂的 bar_toolchain 版本:

def _bar_toolchain_impl(ctx):
    # The implementation is mostly the same as above, so skipping.
    pass

bar_toolchain = rule(
    implementation = _bar_toolchain_impl,
    attrs = {
        "compiler": attr.label(
            executable = True,
            mandatory = True,
            cfg = "exec",
        ),
        "system_lib": attr.label(
            mandatory = True,
            cfg = "target",
        ),
        "arch_flags": attr.string_list(),
    },
)

attr.label 的用法与标准规则相同,但 cfg 参数的含义略有不同。

从目标(称为“父级”)到通过工具链解析到工具链的依赖关系使用一种称为“工具链转换”的特殊配置转换。工具链转换会使配置保持不变,只不过它会强制对工具链使用与父级相同的执行平台(否则,工具链的工具链解析可能会选择任何执行平台,并且不一定与父级的执行平台相同)。这样一来,工具链的任何 exec 依赖项也可以由父项的构建操作执行。任何使用 cfg = "target"(或者未指定 cfg,因为“target”是默认选项)的工具链的依赖项都是与父级相同的目标平台构建的。这样,工具链规则就可以将库(所需的 system_lib 属性)和工具(compiler 属性)贡献给需要它们的构建规则。系统库关联到最终工件,因此需要针对同一平台进行构建,而编译器是在构建期间调用的工具,需要能够在执行平台上运行。

使用工具链注册和构建

此时,所有组件都已组装完成,您只需将工具链提供给 Bazel 的解析过程即可。为此,您可以使用 register_toolchains()WORKSPACE 文件中注册该工具链,也可以使用 --extra_toolchains 标志在命令行中传递工具链的标签。

register_toolchains(
    "//bar_tools:barc_linux_toolchain",
    "//bar_tools:barc_windows_toolchain",
    # Target patterns are also permitted, so you could have also written:
    # "//bar_tools:all",
)

现在,当您构建依赖于工具链类型的目标时,系统会根据目标和执行平台选择适当的工具链。

# my_pkg/BUILD

platform(
    name = "my_target_platform",
    constraint_values = [
        "@platforms//os:linux",
    ],
)

bar_binary(
    name = "my_bar_binary",
    ...
)
bazel build //my_pkg:my_bar_binary --platforms=//my_pkg:my_target_platform

Bazel 会发现 //my_pkg:my_bar_binary 是使用具有 @platforms//os:linux 的平台构建的,因此会解析对 //bar_tools:barc_linux_toolchain//bar_tools:toolchain_type 引用。这将最终构建 //bar_tools:barc_linux,但不会构建 //bar_tools:barc_windows

工具链解决方法

对于使用工具链的每个目标,Bazel 的工具链解析过程决定了目标的具体工具链依赖项。该过程将一组必需的工具链类型、目标平台、可用执行平台列表和可用工具链列表作为输入。其输出是为每种工具链类型选择的工具链,以及为当前目标选择的执行平台。

通过 register_execution_platformsregister_toolchainsWORKSPACE 文件收集可用的执行平台和工具链。您还可以通过 --extra_execution_platforms--extra_toolchains 在命令行中指定其他执行平台和工具链。主机平台会自动添加为可用的执行平台。 可用的平台和工具链将作为有序列表进行跟踪以确定性,同时优先考虑列表中的早期项。

解决步骤如下。

  1. 如果平台对于列表中的每个 constraint_value 也具有该 constraint_value(明确或默认),则 target_compatible_withexec_compatible_with 子句会与该平台匹配

    如果平台有未由子句引用的 constraint_setting 中的 constraint_value,它们不会影响匹配。

  2. 如果正在构建的目标指定了 exec_compatible_with 属性(或其规则定义指定了 exec_compatible_with 参数),系统会过滤可用执行平台列表,以移除与执行约束不匹配的任何平台。

  3. 对于每个可用的执行平台,您可以将每种工具链类型与与该执行平台和目标平台兼容的第一个可用工具链(如果有)相关联。

  4. 如有任何执行平台未能为其某个工具链类型找到兼容的强制工具链,则此规则将被排除。在其余平台中,第一个平台成为当前目标的执行平台,其关联的工具链(如果有)将成为目标的依赖项。

所选的执行平台用于运行目标生成的所有操作。

如果可以在同一 build 内的多个配置(例如,针对不同的 CPU)中构建同一目标,则系统会分别对每个目标版本应用解析过程。

如果规则使用执行组,则每个执行组会分别执行工具链解析,并且每个执行组都有自己的执行平台和工具链。

调试工具链

如果要为现有规则添加工具链支持,请使用 --toolchain_resolution_debug=regex 标志。在工具链解析期间,该标志会为与正则表达式变量匹配的工具链类型或目标名称提供详细输出。您可以使用 .* 输出所有信息。Bazel 将输出在解析过程中检查和跳过的工具链的名称。

如果您想查看哪些 cquery 依赖项来自工具链解析,请使用 cquery--transitions 标志:

# Find all direct dependencies of //cc:my_cc_lib. This includes explicitly
# declared dependencies, implicit dependencies, and toolchain dependencies.
$ bazel cquery 'deps(//cc:my_cc_lib, 1)'
//cc:my_cc_lib (96d6638)
@bazel_tools//tools/cpp:toolchain (96d6638)
@bazel_tools//tools/def_parser:def_parser (HOST)
//cc:my_cc_dep (96d6638)
@local_config_platform//:host (96d6638)
@bazel_tools//tools/cpp:toolchain_type (96d6638)
//:default_host_platform (96d6638)
@local_config_cc//:cc-compiler-k8 (HOST)
//cc:my_cc_lib.cc (null)
@bazel_tools//tools/cpp:grep-includes (HOST)

# Which of these are from toolchain resolution?
$ bazel cquery 'deps(//cc:my_cc_lib, 1)' --transitions=lite | grep "toolchain dependency"
  [toolchain dependency]#@local_config_cc//:cc-compiler-k8#HostTransition -> b6df211