diff --git a/pkgs/build-support/rust/hooks/cargo-setup-hook.sh b/pkgs/build-support/rust/hooks/cargo-setup-hook.sh index b85796e2a41b..aeddeef29d92 100644 --- a/pkgs/build-support/rust/hooks/cargo-setup-hook.sh +++ b/pkgs/build-support/rust/hooks/cargo-setup-hook.sh @@ -27,7 +27,7 @@ cargoSetupPostUnpackHook() { cat ${tmp_config} >> .cargo/config cat >> .cargo/config <<'EOF' - @rustTarget@ + @cargoConfig@ EOF echo "Finished cargoSetupPostUnpackHook" diff --git a/pkgs/build-support/rust/hooks/default.nix b/pkgs/build-support/rust/hooks/default.nix index 652b074c3020..9d3fc9b126ef 100644 --- a/pkgs/build-support/rust/hooks/default.nix +++ b/pkgs/build-support/rust/hooks/default.nix @@ -68,15 +68,37 @@ in { # The `.nativeDrv` stanza works like nativeBuildInputs and ensures cross-compiling has the right version available. diff = "${diffutils.nativeDrv or diffutils}/bin/diff"; - # Target platform - rustTarget = '' - [target."${rust.toRustTarget stdenv.buildPlatform}"] + # We want to specify the correct crt-static flag for both + # the build and host platforms. This is important when the wanted + # value for crt-static does not match the defaults in the rustc target, + # like for pkgsMusl or pkgsCross.musl64; Upstream rustc still assumes + # that musl = static[1]. + # + # By default, Cargo doesn't apply RUSTFLAGS when building build.rs + # if --target is passed, so the only good way to set crt-static for + # build.rs files is to use the unstable -Zhost-config Cargo feature. + # This allows us to specify flags that should be passed to rustc + # when building for the build platform. We also need to use + # -Ztarget-applies-to-host, because using -Zhost-config requires it. + # + # When doing this, we also have to specify the linker, or cargo + # won't pass a -C linker= argument to rustc. This will make rustc + # try to use its default value of "cc", which won't be available + # when cross-compiling. + # + # [1]: https://github.com/rust-lang/compiler-team/issues/422 + cargoConfig = '' + [host] "linker" = "${ccForBuild}" - ${lib.optionalString (stdenv.buildPlatform.config != stdenv.hostPlatform.config) '' - [target."${shortTarget}"] - "linker" = "${ccForHost}" - ''} + "rustflags" = [ "-C", "target-feature=${if stdenv.buildPlatform.isStatic then "+" else "-"}crt-static" ] + + [target."${shortTarget}"] + "linker" = "${ccForHost}" "rustflags" = [ "-C", "target-feature=${if stdenv.hostPlatform.isStatic then "+" else "-"}crt-static" ] + + [unstable] + host-config = true + target-applies-to-host = true ''; }; } ./cargo-setup-hook.sh) {};