工具链

报告问题 查看源代码

本页面介绍了工具链框架,规则作者可通过该框架将其规则逻辑与基于平台的选择工具分离开来。建议先阅读规则平台页面,然后再继续操作。本页面介绍了为什么需要工具链、如何定义和使用它们,以及 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 用户来说,这个问题非常繁琐,而且有点麻烦。如果在整个工作区中未以一致的方式使用此样式,会导致构建在单个平台上运行良好,但在扩展到多平台场景时失败。此外,如果不修改现有规则或目标,它也无法解决添加对新平台和编译器的支持的问题。

工具链框架可以通过添加额外的间接层来解决此问题。从本质上讲,您需要声明您的规则对目标系列(工具链类型)的某个成员有抽象依赖项,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,因为“目标”是默认值)的工具链依赖项都是针对与父项相同的目标平台构建的。这样,工具链规则就可以为需要库(上面的 system_lib 属性)和工具(compiler 属性)提供它们。系统库链接到最终工件,因此需要针对同一平台进行构建,而编译器是在构建期间调用的工具,并且需要能够在执行平台上运行。

注册并使用工具链进行构建

此时,所有构建块已组合完毕,您只需要将工具链提供给 Bazel 的解析过程。为此,您可以使用 register_toolchains()MODULE.bazel 文件中注册工具链,也可以使用 --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",
    # or even
    # "//bar_tools/...",
)

使用目标模式注册工具链时,各个工具链的注册顺序由以下规则确定:

  • 软件包子软件包中定义的工具链先于软件包本身中定义的工具链注册。
  • 在软件包中,工具链按名称的字典顺序注册。

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

# 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 的工具链解析过程会确定目标的具体工具链依赖项。该过程将一组必需的工具链类型、目标平台、可用执行平台的列表以及可用工具链的列表作为输入。其输出是针对每种工具链类型选择的工具链,以及为当前目标选定的执行平台。

可用的执行平台和工具链是通过 MODULE.bazel 文件中的 register_execution_platformsregister_toolchains 调用从外部依赖关系图收集的。您也可以通过 --extra_execution_platforms--extra_toolchains 在命令行中指定其他执行平台和工具链。主机平台会自动添加为可用的执行平台。系统以有序列表的形式跟踪可用平台和工具链,以确保确定性,并优先考虑列表中的前一项。

一组按优先级顺序的可用工具链集根据 --extra_toolchainsregister_toolchains 创建:

  1. 首先添加使用 --extra_toolchains 注册的工具链。(其中,最后一个工具链的优先级最高。)
  2. 按以下顺序在传递外部依赖项图中使用 register_toolchains 注册的工具链:(在这些中,第一个提到的工具链的优先级最高。)
    1. 由根模块注册的工具链(如工作区根目录下的 MODULE.bazel);
    2. 在用户的 WORKSPACE 文件中注册的工具链,包括从该文件调用的所有宏中;
    3. 由非根模块注册的工具链(例如,由根模块指定的依赖项及其依赖项,等等);
    4. 在“WORKSPACE 后缀”中注册的工具链;只有与 Bazel 安装捆绑的特定原生规则才会使用此工具链。

注意:all:*/... 等伪目标按 Bazel 的软件包加载机制进行排序,该机制采用字典顺序。

解决步骤如下。

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

    如果平台有来自 constraint_settingconstraint_value 未被子句引用,则不会影响匹配。

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

  3. 系统会过滤可用工具链列表,以移除所有指定 target_settings 与当前配置不匹配的工具链。

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

  5. 任何执行平台均无法为其其中一个工具链类型找到兼容的强制性工具链时,才会被排除。在其余平台上,第一个平台将成为当前目标的执行平台,其关联的工具链(如果有)会成为目标的依赖项。

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

如果可以在同一 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