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,63 @@ executable = True, ) +def _strip_stack_protector_for_windows_llvm_mingw(toolchain, args): + """Drop stack protector flags unsupported by llvm-mingw build-script probes.""" + if "windows-gnullvm" not in toolchain.target_flag_value: + return args + + uses_llvm_mingw = False + for arg in args: + if "mingw-w64-" in arg: + uses_llvm_mingw = True + break + + if not uses_llvm_mingw: + return args + + # llvm-mingw does not ship libssp_nonshared, so forwarding stack-protector + # flags through CFLAGS/CXXFLAGS breaks build.rs probe binaries compiled via + # cc-rs. + return [arg for arg in args if not arg.startswith("-fstack-protector")] + +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 +560,10 @@ if not env["AR"]: env["AR"] = cc_toolchain.ar_executable + cc_c_args = _strip_stack_protector_for_windows_llvm_mingw(toolchain, cc_c_args) + cc_cxx_args = _strip_stack_protector_for_windows_llvm_mingw(toolchain, cc_cxx_args) + 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).