cargo_build_script incompatible with rust_toolchain using target_json

Open
#4,268 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 3 days

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
65/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust

Research direction

The issue is in cargo_build_script.bzl and cargo_build_script_runner/bin.rs. Start by examining the cargo_build_script rule implementation around line 468 and the runner's get_target_env_vars function. The fix involves checking if target_json is set and passing the JSON file path instead of the target triple, and adding -Zunstable-options when the target ends with .json. Run the provided reproduction steps to verify the fix works with a custom JSON target.

Written by the indexing model from the issue text.

Description

needs-triage

Description

I am trying to use a tier-3 language, and defining the platform as a platform JSON.
It seems cargo_build_script cannot be used with a rust_toolchain that has target_json due to a type mismatch between literal and filename.

  • Current: analysis fails with Error in run: got dict<string, File> for 'env', want dict<string, string>.
  • Expected: build works with JSON targets.

Reproduction steps

MODULE.bazel:

module(name = "repro")
bazel_dep(name = "rules_rust", version = "0.74.0")
bazel_dep(name = "platforms", version = "1.1.0")
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
rust.toolchain(edition = "2021", versions = ["nightly/2026-09-21"])
use_repo(rust, "rust_toolchains", "rust_linux_x86_64__x86_64-unknown-linux-gnu__nightly_tools")
register_toolchains("//:json_toolchain", "@rust_toolchains//:all")

BUILD.bazel:

load("@rules_rust//cargo:defs.bzl", "cargo_build_script")
load("@rules_rust//rust:defs.bzl", "rust_binary")
load("@rules_rust//rust:toolchain.bzl", "rust_toolchain")
load(":target.bzl", "TARGET_JSON")

constraint_setting(name = "spec")
constraint_value(name = "json_spec", constraint_setting = ":spec")
platform(name = "json_platform", constraint_values = ["@platforms//cpu:x86_64", "@platforms//os:linux", ":json_spec"])

TOOLS = "@rust_linux_x86_64__x86_64-unknown-linux-gnu__nightly_tools"
rust_toolchain(
    name = "json_rust_toolchain",
    binary_ext = "", dylib_ext = ".so", staticlib_ext = ".a",
    exec_triple = "x86_64-unknown-linux-gnu",
    extra_rustc_flags = ["-Zunstable-options"],
    rust_doc = TOOLS + "//:rustdoc",
    rust_std = TOOLS + "//:rust_std-x86_64-unknown-linux-gnu",
    rustc = TOOLS + "//:rustc",
    rustc_lib = TOOLS + "//:rustc_lib",
    stdlib_linkflags = ["-ldl", "-lpthread"],
    target_json = TARGET_JSON,
)
toolchain(
    name = "json_toolchain",
    exec_compatible_with = ["@platforms//cpu:x86_64", "@platforms//os:linux"],
    target_compatible_with = ["@platforms//cpu:x86_64", "@platforms//os:linux", ":json_spec"],
    toolchain = ":json_rust_toolchain",
    toolchain_type = "@rules_rust//rust:toolchain_type",
)
cargo_build_script(name = "bs", srcs = ["build.rs"], edition = "2021")
rust_binary(name = "bin", srcs = ["main.rs"], edition = "2021", deps = [":bs"])

build.rs:

fn main() { println!("cargo:rustc-cfg=from_build_script"); }

main.rs:

fn main() { }

Trigger:

(echo 'TARGET_JSON = """'; rustc -Zunstable-options --print target-spec-json --target x86_64-unknown-linux-gnu; echo '"""') > target.bzl
bazel build //:bs --platforms=//:json_platform --@rules_rust//rust/toolchain/channel=nightly

Additional context

ERROR: /home/bluecmd/work/rust-repro/BUILD.bazel:30:19: in cargo_build_script rule //:bs: 
Traceback (most recent call last):
        File "/home/bluecmd/.cache/bazel/_bazel_bluecmd/ea14b543b17791a382a3d5f7ed953007/external/rules_rust+/cargo/private/cargo_build_script.bzl", line 703, column 20, in _cargo_build_script_impl
                ctx.actions.run(
Error in run: got dict<string, File> for 'env', want dict<string, string>
ERROR: /home/bluecmd/work/rust-repro/BUILD.bazel:30:19: Analysis of target '//:bs' (config: 63aac55) failed
ERROR: Analysis of target '//:bin' failed; build aborted: Analysis failed
INFO: Elapsed time: 33.434s, Critical Path: 0.06s
INFO: 1 process: 1 internal.
ERROR: Build did NOT complete successfully

Something like this might work?
Adding -Zunstable-options since the error without seems to want it; error loading target specification: custom targets are unstable and require -Zunstable-options".

--- a/cargo/private/cargo_build_script.bzl
+++ b/cargo/private/cargo_build_script.bzl
@@ -468,7 +468,7 @@
         "RUSTDOC": toolchain.rust_doc.path,
-        "TARGET": toolchain.target_flag_value,
+        "TARGET": toolchain.target_json.path if toolchain.target_json else toolchain.target_flag_value,
--- a/cargo/private/cargo_build_script_runner/bin.rs
+++ b/cargo/private/cargo_build_script_runner/bin.rs
@@ -505,12 +505,14 @@
 fn get_target_env_vars<P: AsRef<Path>>(rustc: &P) -> Result<BTreeMap<String, String>, String> {
-    let output = Command::new(rustc.as_ref())
-        .arg("--print=cfg")
-        .arg(format!(
-            "--target={}",
-            env::var("TARGET").expect("missing TARGET")
-        ))
+    let target = env::var("TARGET").expect("missing TARGET");
+    let mut command = Command::new(rustc.as_ref());
+    command.arg("--print=cfg").arg(format!("--target={target}"));
+    if target.ends_with(".json") {
+        command.arg("-Zunstable-options");
+    }
+    let output = command
         .output()

Impact

Blocks every crate with a build.rs on custom JSON targets.

Bazel and rules_rust version

Bazel 9.2.0, rules_rust 0.74.0

Dominant language
Starlark
Stars
857
Forks
701
Avg merge
4d 7h
Merged PRs (30d)
46

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bazelbuild/rules_rust

All issues in bazelbuild/rules_rust

Similar issues

More Build System issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.