From fdfd065f99539df1de054abd046a48b5dfa43df0 Mon Sep 17 00:00:00 2001 From: Martin Kuntz Jacobsen Date: Wed, 18 Nov 2026 12:42:31 +0100 Subject: [PATCH] cargo_build_script: set the Apple deployment target for cc-rs cc-rs reads MACOSX_DEPLOYMENT_TARGET and its per-OS siblings, not CFLAGS. Derive them from the C compile args, as rustc actions already do from the link args. As for rustc, a value set through --action_env is kept, and the toolchain's env and build_script_env still override the derived one. Assisted-by: Claude --- cargo/private/cargo_build_script.bzl | 15 ++- cargo/settings/settings.bzl | 3 +- .../cc_args_and_env/BUILD.bazel | 3 + .../cc_args_and_env/cc_args_and_env_test.bzl | 96 +++++++++++++++++-- rust/private/rustc.bzl | 31 +++--- 5 files changed, 124 insertions(+), 24 deletions(-) diff --git a/cargo/private/cargo_build_script.bzl b/cargo/private/cargo_build_script.bzl index 73dcf808e4..58bc86e850 100644 --- a/cargo/private/cargo_build_script.bzl +++ b/cargo/private/cargo_build_script.bzl @@ -13,6 +13,7 @@ load("//rust:rust_common.bzl", "BuildInfo", "DepInfo") # buildifier: disable=bzl-visibility load( "//rust/private:rustc.bzl", + "apple_deployment_target_env", "get_compilation_mode_opts", "get_linker_and_args", ) @@ -559,11 +560,19 @@ def _cargo_build_script_impl(ctx): if not env["AR"]: env["AR"] = cc_toolchain.ar_executable - # Populate CFLAGS and CXXFLAGS that cc-rs relies on when building from source, in particular - # to determine the deployment target when building for apple platforms (`macosx-version-min` - # for example, itself derived from the `macos_minimum_os` Bazel argument). + # Populate CFLAGS and CXXFLAGS that cc-rs relies on when building from source. env["CFLAGS"] = " ".join(_pwd_flags(cc_c_args)) env["CXXFLAGS"] = " ".join(_pwd_flags(cc_cxx_args)) + + # cc-rs reads the Apple deployment target from `MACOSX_DEPLOYMENT_TARGET` + # and its per-OS siblings, not from `CFLAGS`, so mirror the one the + # cc_toolchain encodes in its compile args. A value from `--action_env` + # is kept; the toolchain's `env` and `build_script_env` are applied below + # and override this one. An inherited `--action_env=VAR` is overridden. + for key, value in apple_deployment_target_env(cc_c_args).items(): + if not (use_default_shell_env and key in ctx.configuration.default_shell_env): + env[key] = value + # It may be tempting to forward ARFLAGS, but cc-rs is opinionated enough # that doing so is more likely to hurt than help. If you need to change # ARFLAGS, make changes to cc-rs. diff --git a/cargo/settings/settings.bzl b/cargo/settings/settings.bzl index 951addad55..5ab49a16bb 100644 --- a/cargo/settings/settings.bzl +++ b/cargo/settings/settings.bzl @@ -49,7 +49,8 @@ def use_cc_toolchain(): When enabled (the default), each `cargo_build_script` action gets the resolved `cc_toolchain`'s `all_files` added to its inputs and picks up the - `CC`, `CXX`, `AR`, `CFLAGS`, `CXXFLAGS`, `LDFLAGS`, and `INCLUDE` + `CC`, `CXX`, `AR`, `CFLAGS`, `CXXFLAGS`, `LDFLAGS`, `INCLUDE`, and, for + Apple targets, `*_DEPLOYMENT_TARGET` (e.g. `MACOSX_DEPLOYMENT_TARGET`) environment variables derived from that toolchain. This matches Cargo's behavior and is required for build scripts that shell out to a C/C++ compiler (e.g. those using `cc-rs` or `cmake-rs`). diff --git a/cargo/tests/cargo_build_script/cc_args_and_env/BUILD.bazel b/cargo/tests/cargo_build_script/cc_args_and_env/BUILD.bazel index 8966f22194..fec90d81a0 100644 --- a/cargo/tests/cargo_build_script/cc_args_and_env/BUILD.bazel +++ b/cargo/tests/cargo_build_script/cc_args_and_env/BUILD.bazel @@ -1,5 +1,6 @@ load( "cc_args_and_env_test.bzl", + "apple_deployment_target_test", "bindir_absolute_test", "bindir_malformed_missing_value_test", "bindir_relative_test", @@ -94,3 +95,5 @@ direct_libs_absolute_test(name = "direct_libs_absolute_test") direct_libs_as_flag_operand_test(name = "direct_libs_as_flag_operand_test") forwarded_header_paths_test(name = "forwarded_header_paths_test") + +apple_deployment_target_test(name = "apple_deployment_target_test") diff --git a/cargo/tests/cargo_build_script/cc_args_and_env/cc_args_and_env_test.bzl b/cargo/tests/cargo_build_script/cc_args_and_env/cc_args_and_env_test.bzl index 130d1a858d..b7be0ce408 100644 --- a/cargo/tests/cargo_build_script/cc_args_and_env/cc_args_and_env_test.bzl +++ b/cargo/tests/cargo_build_script/cc_args_and_env/cc_args_and_env_test.bzl @@ -253,6 +253,21 @@ def _cc_args_and_env_analysis_test_impl(ctx): "set up by most Bazel C/C++ toolchains is extremely error-prone.", ) + for env_var, expected_value in ctx.attr.expected_env.items(): + asserts.equals( + env, + expected_value, + cargo_action.env.get(env_var), + "error: expected env '{}' to be '{}'".format(env_var, expected_value), + ) + + for env_var in ctx.attr.unexpected_env: + asserts.false( + env, + env_var in cargo_action.env, + "error: expected env '{}' to be unset".format(env_var), + ) + if ctx.attr.expected_include: actual_include = cargo_action.env.get("INCLUDE") asserts.equals( @@ -264,14 +279,32 @@ def _cc_args_and_env_analysis_test_impl(ctx): return analysistest.end(env) +_CC_ARGS_AND_ENV_ANALYSIS_TEST_ATTRS = { + "expected_cflags": attr.string_list(default = ["-Wall"]), + "expected_cxxflags": attr.string_list(default = ["-fno-rtti"]), + "expected_env": attr.string_dict(), + "expected_include": attr.string(default = ""), + "legacy_cc_toolchain": attr.bool(default = False), + "unexpected_env": attr.string_list(), +} + cc_args_and_env_analysis_test = analysistest.make( impl = _cc_args_and_env_analysis_test_impl, doc = """An analysistest to examine the custom cargo flags of an cargo_build_script target.""", - attrs = { - "expected_cflags": attr.string_list(default = ["-Wall"]), - "expected_cxxflags": attr.string_list(default = ["-fno-rtti"]), - "expected_include": attr.string(default = ""), - "legacy_cc_toolchain": attr.bool(default = False), + attrs = _CC_ARGS_AND_ENV_ANALYSIS_TEST_ATTRS, +) + +# `--action_env` deployment target the analysistest below injects. +_ACTION_ENV_DEPLOYMENT_TARGET = "15.0" + +cc_args_and_env_with_action_env_analysis_test = analysistest.make( + impl = _cc_args_and_env_analysis_test_impl, + doc = """Like cc_args_and_env_analysis_test, with `MACOSX_DEPLOYMENT_TARGET` set through `--action_env`.""", + attrs = _CC_ARGS_AND_ENV_ANALYSIS_TEST_ATTRS, + config_settings = { + "//command_line_option:action_env": [ + "MACOSX_DEPLOYMENT_TARGET=" + _ACTION_ENV_DEPLOYMENT_TARGET, + ], }, ) @@ -282,7 +315,9 @@ def cargo_build_script_with_extra_cc_compile_flags( extra_cxx_compile_flags = ["-fno-rtti"], extra_ar_flags = ["-x"], extra_include_paths = "", - legacy_cc_toolchain = False): + legacy_cc_toolchain = False, + build_script_env = {}, + use_default_shell_env = None): """Produces a test cargo_build_script target that's set up to use a custom cc_toolchain with the extra_cc_compile_flags. This is achieved by creating a cascade of targets: @@ -299,6 +334,8 @@ def cargo_build_script_with_extra_cc_compile_flags( extra_include_paths: INCLUDE environment variable value for the cc_toolchain. legacy_cc_toolchain: Enables legacy tool_path configuration of the cc cc toolchain. + build_script_env: Forwarded to the cargo_build_script. + use_default_shell_env: Forwarded to the cargo_build_script. """ test_cc_config( @@ -330,6 +367,8 @@ def cargo_build_script_with_extra_cc_compile_flags( name = "%s/cargo_build_script_impl" % name, edition = "2018", srcs = ["build.rs"], + build_script_env = build_script_env, + use_default_shell_env = use_default_shell_env, tags = ["manual", "nobuild"], ) with_extra_toolchains( @@ -794,3 +833,48 @@ def forwarded_header_paths_test(name): target_under_test = case + "/cargo_build_script", expected_cflags = [forwarding, category, forwarding, expected, "-DKEEP=1"], ) + +_APPLE_DEPLOYMENT_TARGET_VARS = [ + "IPHONEOS_DEPLOYMENT_TARGET", + "MACOSX_DEPLOYMENT_TARGET", + "TVOS_DEPLOYMENT_TARGET", + "WATCHOS_DEPLOYMENT_TARGET", + "XROS_DEPLOYMENT_TARGET", +] + +def apple_deployment_target_test(name): + """Tests that the Apple deployment target in the cc args is exported for cc-rs. + + Args: + name: Prefix for the generated analysis tests. + """ + macos_target = ["-target", "arm64-apple-macosx26.0"] + for suffix, flags, expected_env, unexpected_env, analysis_test, script_attrs in [ + ("macos_target", macos_target, {"MACOSX_DEPLOYMENT_TARGET": "26.0"}, [], cc_args_and_env_analysis_test, {}), + ("ios_version_min", ["-mios-version-min=17.0"], {"IPHONEOS_DEPLOYMENT_TARGET": "17.0"}, [], cc_args_and_env_analysis_test, {}), + # The version in the `-target` triple wins over `-m-version-min=`, + # whichever comes first. + ("target_after_version_min", ["-mmacosx-version-min=13.0"] + macos_target, {"MACOSX_DEPLOYMENT_TARGET": "26.0"}, [], cc_args_and_env_analysis_test, {}), + ("target_before_version_min", macos_target + ["-mmacosx-version-min=13.0"], {"MACOSX_DEPLOYMENT_TARGET": "26.0"}, [], cc_args_and_env_analysis_test, {}), + ("non_apple_target", ["-target", "x86_64-unknown-linux-gnu"], {}, _APPLE_DEPLOYMENT_TARGET_VARS, cc_args_and_env_analysis_test, {}), + # A deployment target from `--action_env` is not overridden. + ("action_env_wins", macos_target, {"MACOSX_DEPLOYMENT_TARGET": _ACTION_ENV_DEPLOYMENT_TARGET}, [], cc_args_and_env_with_action_env_analysis_test, {}), + # Without the default shell env, `--action_env` never reaches the build + # script, so the derived deployment target is still needed. + ("action_env_without_default_shell_env", macos_target, {"MACOSX_DEPLOYMENT_TARGET": "26.0"}, [], cc_args_and_env_with_action_env_analysis_test, {"use_default_shell_env": False}), + # `build_script_env` overrides the derived deployment target. + ("build_script_env_wins", macos_target, {"MACOSX_DEPLOYMENT_TARGET": "14.0"}, [], cc_args_and_env_analysis_test, {"build_script_env": {"MACOSX_DEPLOYMENT_TARGET": "14.0"}}), + ]: + case = "%s_%s" % (name, suffix) + cargo_build_script_with_extra_cc_compile_flags( + name = case + "/cargo_build_script", + extra_cc_compile_flags = flags, + **script_attrs + ) + analysis_test( + name = case, + target_under_test = case + "/cargo_build_script", + expected_cflags = flags, + expected_env = expected_env, + unexpected_env = unexpected_env, + ) diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl index b4992f04b1..17b04b4d50 100644 --- a/rust/private/rustc.bzl +++ b/rust/private/rustc.bzl @@ -531,7 +531,7 @@ def get_linker_and_args(ctx, crate_type, toolchain, cc_toolchain, feature_config return ld, ld_is_direct_driver, link_args, link_env -# The environment variables rustc reads the Apple deployment target from, +# The environment variables rustc and cc-rs read the Apple deployment target from, # keyed by the OS names clang accepts in a `-target` triple and in # `-m-version-min=`. _APPLE_DEPLOYMENT_TARGET_ENV = { @@ -552,31 +552,34 @@ def _split_os_version(os_version): return os_version[:i], os_version[i:] return os_version, "" -def apple_deployment_target_env(link_args): - """Derives the Apple deployment target variable rustc expects from linker arguments. +def apple_deployment_target_env(args): + """Derives the Apple deployment target variable from clang arguments. An Apple cc_toolchain tells clang its deployment target through the `-target` triple (e.g. `arm64-apple-macosx26.0`) or `-m-version-min=`. - rustc does not read the link args it forwards: it takes the deployment + Neither rustc nor cc-rs reads those arguments: both take the deployment target from `MACOSX_DEPLOYMENT_TARGET` and its per-OS siblings and, when - those are unset, from its own default, which it passes to the linker as - `-m-version-min=`. clang then warns about the conflicting options on - every link (bazelbuild/rules_rust#4149). + those are unset, from their own default. rustc passes its default to the + linker as `-m-version-min=`, so clang warns about the conflicting + options on every link (bazelbuild/rules_rust#4149); cc-rs adds its + own deployment target to the C compiler command line, where it can + disagree with the one in the toolchain's `CFLAGS`. - As in clang, a version carried by the last `-target` triple wins over - `-m-version-min=`. + The arguments may be the linker arguments forwarded to rustc or the C + compile arguments handed to a cargo build script. As in clang, a version + carried by the last `-target` triple wins over `-m-version-min=`. Args: - link_args (list): The linker arguments forwarded to rustc. + args (list): The linker or C compile arguments of the cc_toolchain. Returns: - dict: The deployment target variable to set for rustc, if any. + dict: The deployment target variable to set, if any. """ triple = None version_min = None - for i, arg in enumerate(link_args): - if arg == "-target" and i + 1 < len(link_args): - triple = link_args[i + 1] + for i, arg in enumerate(args): + if arg == "-target" and i + 1 < len(args): + triple = args[i + 1] elif arg.startswith("--target="): triple = arg[len("--target="):] elif arg.startswith("-m") and "-version-min=" in arg: