diff --git a/cargo/private/cargo_build_script.bzl b/cargo/private/cargo_build_script.bzl --- a/cargo/private/cargo_build_script.bzl +++ b/cargo/private/cargo_build_script.bzl @@ -120,6 +120,44 @@ executable = True, ) +def _rewrite_windows_exec_msvc_cc_args(toolchain, args): + """Translate GNU-flavored cc args when exec-side build scripts target Windows MSVC.""" + if toolchain.target_flag_value != toolchain.exec_triple.str or not toolchain.exec_triple.str.endswith("-pc-windows-msvc"): + return args + + rewritten = [] + skip_next = False + for arg in args: + if skip_next: + skip_next = False + continue + + if arg == "-target": + skip_next = True + continue + + if arg.startswith("-target=") or arg.startswith("--target="): + continue + + if arg == "-nostdlibinc" or arg.startswith("--sysroot"): + continue + + if "mingw-w64-" in arg or "mingw_import_libraries_directory" in arg or "mingw_crt_library_search_directory" in arg: + continue + + if arg.startswith("-fstack-protector"): + continue + + if arg.startswith("-D_FORTIFY_SOURCE="): + continue + + rewritten.append(arg) + + return [ + "-target", + toolchain.target_flag_value, + ] + rewritten + def get_cc_compile_args_and_env(cc_toolchain, feature_configuration): """Gather cc environment variables from the given `cc_toolchain` @@ -503,6 +541,8 @@ if not env["AR"]: env["AR"] = cc_toolchain.ar_executable + cc_c_args = _rewrite_windows_exec_msvc_cc_args(toolchain, cc_c_args) + cc_cxx_args = _rewrite_windows_exec_msvc_cc_args(toolchain, cc_cxx_args) # 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).