From 98c3e5d327b42d8d2e634827ae20aae103689f11 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:14:33 -0700 Subject: [PATCH 01/19] Add bidirectional C++ and Rust interop with rules_rust cdylib support Add bidirectional FFI interop between C++ and Rust, including C++ calling Rust and Rust calling C++. Features: - Rust calling C++: //rs:cpp_calculator links //cc:calculator via link_deps and invokes cc_calculator_* C-ABI functions hermetically using rust-lld. - C++ calling Rust: //cc:rust_calculator links //rs:rust_calculator (rust_shared_library / cdylib) and invokes rs_calculator_* C-ABI functions via GNU import library. - cc/: native C++ expression calculator engine, C-ABI export, CLI supporting info, calc, and calc-rs, and unit tests (calculator_test, rust_calculator_test). - rs/: extended with cpp_calculator wrapper, rust_calculator cdylib export, cpp_calculator_test, and CLI calc-cpp command. - patches/rules_rust_cdylib_windows.patch: fixes rules_rust cdylib support on Windows GNU targets: - Adds --entry=DllMainCRTStartup for direct linker drivers (rust-lld) linking shared libraries on Windows GNU. - Declares correct import library filename by target ABI (.dll.lib on MSVC, lib.dll.a on GNU/LLVM-GNU). - Omits transitive stdlib_linkflags from CcInfo on cdylib since cdylib is already linked against Rust stdlib. - README.md: updated with usage instructions for both CLI tools. --- MODULE.bazel | 6 +- README.md | 15 ++ cc/BUILD.bazel | 60 ++++++ cc/calculator.cc | 269 ++++++++++++++++++++++++ cc/calculator.hh | 53 +++++ cc/calculator_test.cc | 75 +++++++ cc/main.cc | 68 ++++++ cc/rust_calculator.cc | 52 +++++ cc/rust_calculator.hh | 24 +++ cc/rust_calculator_test.cc | 67 ++++++ patches/BUILD.bazel | 5 +- patches/rules_rust_cdylib_windows.patch | 89 ++++++++ patches/rules_rust_windows_gnu.patch | 1 + rs/BUILD.bazel | 30 ++- rs/cpp_calculator.rs | 65 ++++++ rs/cpp_calculator_test.rs | 56 +++++ rs/main.rs | 23 +- rs/rust_calculator.rs | 91 ++++++++ 18 files changed, 1043 insertions(+), 6 deletions(-) create mode 100644 cc/BUILD.bazel create mode 100644 cc/calculator.cc create mode 100644 cc/calculator.hh create mode 100644 cc/calculator_test.cc create mode 100644 cc/main.cc create mode 100644 cc/rust_calculator.cc create mode 100644 cc/rust_calculator.hh create mode 100644 cc/rust_calculator_test.cc create mode 100644 patches/rules_rust_cdylib_windows.patch create mode 100644 rs/cpp_calculator.rs create mode 100644 rs/cpp_calculator_test.rs create mode 100644 rs/rust_calculator.rs diff --git a/MODULE.bazel b/MODULE.bazel index e722e80..b006c14 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -13,6 +13,7 @@ bazel_dep(name = "rules_python_gazelle_plugin", version = "0.37.0") bazel_dep(name = "hermetic_cc_toolchain", version = "4.1.0") bazel_dep(name = "platforms", version = "1.1.0") bazel_dep(name = "rules_rust", version = "0.75.0") +bazel_dep(name = "rules_cc", version = "0.2.17") python = use_extension("@rules_python//python/extensions:python.bzl", "python") python.toolchain( @@ -78,5 +79,8 @@ register_toolchains("@rust_toolchains//:all") single_version_override( module_name = "rules_rust", patch_strip = 1, - patches = ["//patches:rules_rust_windows_gnu.patch"], + patches = [ + "//patches:rules_rust_windows_gnu.patch", + "//patches:rules_rust_cdylib_windows.patch", + ], ) diff --git a/README.md b/README.md index 7eed27a..46cdaf8 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,21 @@ To run the Rust calculator example: bazel run //rs:main -- calc "2 + 3 * 4" ``` +To run the C++ calculator example: +```shell +bazel run //cc:main -- calc "2 + 3 * 4" +``` + +To run the Rust calling C++ FFI interop example: +```shell +bazel run //rs:main -- calc-cpp "2 * (3 + 4) ^ 2" +``` + +To run the C++ calling Rust FFI interop example: +```shell +bazel run //cc:main -- calc-rs "2 * (3 + 4) ^ 2" +``` + To format Bazel files: ```shell buildifier BUILD.bazel diff --git a/cc/BUILD.bazel b/cc/BUILD.bazel new file mode 100644 index 0000000..64549ff --- /dev/null +++ b/cc/BUILD.bazel @@ -0,0 +1,60 @@ +load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") + +cc_library( + name = "calculator", + srcs = ["calculator.cc"], + hdrs = ["calculator.hh"], + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + visibility = ["//visibility:public"], +) + +cc_library( + name = "rust_calculator", + srcs = ["rust_calculator.cc"], + hdrs = ["rust_calculator.hh"], + visibility = ["//visibility:public"], + deps = ["//rs:rust_calculator"], +) + +cc_binary( + name = "main", + srcs = ["main.cc"], + data = ["//rs:rust_calculator"], + env = select({ + "@platforms//os:windows": { + "PATH": "rs;.", + }, + "//conditions:default": {}, + }), + visibility = ["//visibility:public"], + deps = [ + ":calculator", + ":rust_calculator", + "//rs:rust_calculator", + ], +) + +cc_test( + name = "calculator_test", + srcs = ["calculator_test.cc"], + deps = [":calculator"], +) + +cc_test( + name = "rust_calculator_test", + srcs = ["rust_calculator_test.cc"], + data = ["//rs:rust_calculator"], + env = select({ + "@platforms//os:windows": { + "PATH": "rs;.", + }, + "//conditions:default": {}, + }), + deps = [ + ":rust_calculator", + "//rs:rust_calculator", + ], +) diff --git a/cc/calculator.cc b/cc/calculator.cc new file mode 100644 index 0000000..bd8956a --- /dev/null +++ b/cc/calculator.cc @@ -0,0 +1,269 @@ +#include "cc/calculator.hh" + +#include +#include +#include +#include +#include +#include +#include + +namespace calculator { +namespace { + +enum class TokenType { + Number, + Plus, + Minus, + Star, + Slash, + Power, + LParen, + RParen, + Invalid, + End +}; + +struct Token { + TokenType type; + double value{0.0}; +}; + +class Lexer { +public: + explicit Lexer(std::string_view input) : input_(input), pos_(0) {} + + Token next_token() { + skip_whitespace(); + if (pos_ >= input_.size()) { + return {TokenType::End, 0.0}; + } + + char c = input_[pos_]; + if (std::isdigit(static_cast(c)) || c == '.') { + const char* start_ptr = input_.data() + pos_; + char* end_ptr = nullptr; + double val = std::strtod(start_ptr, &end_ptr); + if (end_ptr == start_ptr) { + pos_++; + return {TokenType::Invalid, 0.0}; + } + pos_ += static_cast(end_ptr - start_ptr); + return {TokenType::Number, val}; + } + + pos_++; + switch (c) { + case '+': return {TokenType::Plus, 0.0}; + case '-': return {TokenType::Minus, 0.0}; + case '*': + if (pos_ < input_.size() && input_[pos_] == '*') { + pos_++; + return {TokenType::Power, 0.0}; + } + return {TokenType::Star, 0.0}; + case '/': return {TokenType::Slash, 0.0}; + case '^': return {TokenType::Power, 0.0}; + case '(': return {TokenType::LParen, 0.0}; + case ')': return {TokenType::RParen, 0.0}; + default: return {TokenType::Invalid, 0.0}; + } + } + +private: + void skip_whitespace() { + while (pos_ < input_.size() && std::isspace(static_cast(input_[pos_]))) { + pos_++; + } + } + + std::string_view input_; + size_t pos_; +}; + +class Parser { +public: + explicit Parser(std::string_view input) : lexer_(input), error_code_(0), error_msg_(nullptr) { + advance(); + } + + bool parse(double* out_result) { + if (current_token_.type == TokenType::End) { + set_error(3, "empty expression"); + return false; + } + double res = expression(); + if (error_code_ != 0) { + return false; + } + if (current_token_.type != TokenType::End) { + set_error(4, "trailing unparsed tokens"); + return false; + } + if (out_result) { + *out_result = res; + } + return true; + } + + int32_t error_code() const { return error_code_; } + const char* error_msg() const { return error_msg_ ? error_msg_ : ""; } + +private: + void set_error(int32_t code, const char* msg) { + if (error_code_ == 0) { + error_code_ = code; + error_msg_ = msg; + } + } + + void advance() { + current_token_ = lexer_.next_token(); + } + + double expression() { + double result = term(); + if (error_code_ != 0) return 0.0; + while (current_token_.type == TokenType::Plus || current_token_.type == TokenType::Minus) { + bool is_plus = (current_token_.type == TokenType::Plus); + advance(); + double rhs = term(); + if (error_code_ != 0) return 0.0; + if (is_plus) { + result += rhs; + } else { + result -= rhs; + } + } + return result; + } + + double term() { + double result = unary(); + if (error_code_ != 0) return 0.0; + while (current_token_.type == TokenType::Star || current_token_.type == TokenType::Slash) { + bool is_mul = (current_token_.type == TokenType::Star); + advance(); + double rhs = unary(); + if (error_code_ != 0) return 0.0; + if (is_mul) { + result *= rhs; + } else { + if (rhs == 0.0) { + set_error(1, "division by zero"); + return 0.0; + } + result /= rhs; + } + } + return result; + } + + double unary() { + if (current_token_.type == TokenType::Plus) { + advance(); + return unary(); + } + if (current_token_.type == TokenType::Minus) { + advance(); + return -unary(); + } + return power(); + } + + double power() { + double base = primary(); + if (error_code_ != 0) return 0.0; + if (current_token_.type == TokenType::Power) { + advance(); + double exponent = unary(); + if (error_code_ != 0) return 0.0; + return std::pow(base, exponent); + } + return base; + } + + double primary() { + if (current_token_.type == TokenType::Number) { + double val = current_token_.value; + advance(); + return val; + } + if (current_token_.type == TokenType::LParen) { + advance(); + double result = expression(); + if (error_code_ != 0) return 0.0; + if (current_token_.type != TokenType::RParen) { + set_error(2, "invalid syntax"); + return 0.0; + } + advance(); + return result; + } + set_error(2, "invalid syntax"); + return 0.0; + } + + Lexer lexer_; + Token current_token_; + int32_t error_code_; + const char* error_msg_; +}; + +} // namespace + +double evaluate_expression(std::string_view expr) { + Parser parser(expr); + double result = 0.0; + if (!parser.parse(&result)) { + return 0.0; + } + return result; +} + +} // namespace calculator + +extern "C" { + +int32_t cc_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +) { + if (!expr || !out_result) { + if (err_buf && err_buf_len > 0) { + std::strncpy(err_buf, "null pointer argument", err_buf_len - 1); + err_buf[err_buf_len - 1] = '\0'; + } + return -1; + } + + calculator::Parser parser(expr); + if (!parser.parse(out_result)) { + if (err_buf && err_buf_len > 0) { + std::strncpy(err_buf, parser.error_msg(), err_buf_len - 1); + err_buf[err_buf_len - 1] = '\0'; + } + return parser.error_code(); + } + + if (err_buf && err_buf_len > 0) { + err_buf[0] = '\0'; + } + return 0; +} + +int32_t cc_calculator_add(int32_t a, int32_t b) { + return a + b; +} + +double cc_calculator_pow(double base, double exp) { + return std::pow(base, exp); +} + +const char* cc_calculator_version(void) { + return "1.0.0-cpp"; +} + +} // extern "C" diff --git a/cc/calculator.hh b/cc/calculator.hh new file mode 100644 index 0000000..38ba8dc --- /dev/null +++ b/cc/calculator.hh @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +#include +#include + +namespace calculator { + +/// Evaluates a mathematical string expression in C++. +/// Supported operators: +, -, *, /, ^ and ** (power), and parentheses. +/// Throws std::runtime_error on invalid syntax, empty expression, or division by zero. +double evaluate_expression(std::string_view expr); + +} // namespace calculator +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/// C-compatible FFI interface for evaluating expressions. +/// +/// Returns 0 on success, or a non-zero error code: +/// 1: Division by zero +/// 2: Invalid syntax +/// 3: Empty expression +/// 4: Trailing tokens +/// -1: Unexpected internal error or null pointer +/// +/// On success, *out_result contains the evaluated double. +/// If err_buf is non-null and err_buf_len > 0, an error description is written. +int32_t cc_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +); + +/// Adds two 32-bit integers via C++ implementation. +int32_t cc_calculator_add(int32_t a, int32_t b); + +/// Computes base raised to exp via C++ implementation. +double cc_calculator_pow(double base, double exp); + +/// Returns the C++ calculator engine version string. +const char* cc_calculator_version(void); + +#ifdef __cplusplus +} +#endif diff --git a/cc/calculator_test.cc b/cc/calculator_test.cc new file mode 100644 index 0000000..1ffc3ac --- /dev/null +++ b/cc/calculator_test.cc @@ -0,0 +1,75 @@ +#include "cc/calculator.hh" + +#include +#include +#include +#include + +void test_basic_operations() { + assert(calculator::evaluate_expression("2 + 2") == 4.0); + assert(calculator::evaluate_expression("5 - 3") == 2.0); + assert(calculator::evaluate_expression("4 * 3") == 12.0); + assert(calculator::evaluate_expression("10 / 2") == 5.0); +} + +void test_operator_precedence() { + assert(calculator::evaluate_expression("2 + 3 * 4") == 14.0); + assert(calculator::evaluate_expression("(2 + 3) * 4") == 20.0); +} + +void test_power_operations() { + assert(calculator::evaluate_expression("2 ** 3") == 8.0); + assert(calculator::evaluate_expression("2 ^ 3") == 8.0); +} + +void test_unary_operations() { + assert(calculator::evaluate_expression("-5 + 3") == -2.0); + assert(calculator::evaluate_expression("-(3 * 2)") == -6.0); +} + +void test_float_parsing() { + assert(calculator::evaluate_expression("2.5 * 4") == 10.0); +} + +void test_ffi_functions() { + double result = 0.0; + char err[64] = {0}; + + // Successful evaluation + int32_t status = cc_calculator_eval("3 * (4 + 5)", &result, err, sizeof(err)); + assert(status == 0); + assert(result == 27.0); + assert(err[0] == '\0'); + + // Division by zero + status = cc_calculator_eval("8 / 0", &result, err, sizeof(err)); + assert(status == 1); + assert(std::strcmp(err, "division by zero") == 0); + + // Invalid syntax + status = cc_calculator_eval("1 ++ 2 *", &result, err, sizeof(err)); + assert(status == 2); + assert(std::strcmp(err, "invalid syntax") == 0); + + // Empty expression + status = cc_calculator_eval(" ", &result, err, sizeof(err)); + assert(status == 3); + assert(std::strcmp(err, "empty expression") == 0); + + // Direct helper functions + assert(cc_calculator_add(10, 32) == 42); + assert(cc_calculator_pow(3.0, 3.0) == 27.0); + assert(std::strcmp(cc_calculator_version(), "1.0.0-cpp") == 0); +} + +int main() { + test_basic_operations(); + test_operator_precedence(); + test_power_operations(); + test_unary_operations(); + test_float_parsing(); + test_ffi_functions(); + + std::cout << "All C++ calculator tests passed successfully!" << std::endl; + return 0; +} diff --git a/cc/main.cc b/cc/main.cc new file mode 100644 index 0000000..f440ca3 --- /dev/null +++ b/cc/main.cc @@ -0,0 +1,68 @@ +#include "cc/calculator.hh" +#include "cc/rust_calculator.hh" + +#include +#include +#include + +void print_usage() { + std::cout << "Usage: main [arguments]\n" + << "Commands:\n" + << " info Display information about the C++ environment.\n" + << " calc Evaluate a mathematical expression using C++ engine.\n" + << " calc-rs Evaluate a mathematical expression using Rust FFI engine.\n"; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + print_usage(); + return 1; + } + + std::string_view command = argv[1]; + if (command == "info") { + std::cout << "C++ Standard: " << __cplusplus << "\n" + << "Engine Version: " << cc_calculator_version() << "\n" + << "Rust Interop Engine Version: " << rust_interop::version() << "\n" + << "Bazel hermetic C++ toolchain is working!\n"; + return 0; + } + + if (command == "calc") { + if (argc < 3) { + std::cerr << "Error: calc command requires a mathematical expression.\n"; + return 1; + } + std::string expression = argv[2]; + double result = 0.0; + char err_buf[256] = {0}; + int32_t status = cc_calculator_eval(expression.c_str(), &result, err_buf, sizeof(err_buf)); + if (status == 0) { + std::cout << expression << " = " << result << "\n"; + return 0; + } else { + std::cerr << "Error: " << (err_buf[0] != '\0' ? err_buf : "evaluation failed") << "\n"; + return 1; + } + } + + if (command == "calc-rs") { + if (argc < 3) { + std::cerr << "Error: calc-rs command requires a mathematical expression.\n"; + return 1; + } + std::string expression = argv[2]; + try { + double result = rust_interop::evaluate_expression(expression); + std::cout << expression << " = " << result << " (via Rust engine)\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << "Error: " << e.what() << "\n"; + return 1; + } + } + + std::cerr << "Error: Unknown command '" << command << "'\n"; + print_usage(); + return 1; +} diff --git a/cc/rust_calculator.cc b/cc/rust_calculator.cc new file mode 100644 index 0000000..57214ac --- /dev/null +++ b/cc/rust_calculator.cc @@ -0,0 +1,52 @@ +#include "cc/rust_calculator.hh" + +#include +#include + +extern "C" { +int32_t rs_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +); +int32_t rs_calculator_add(int32_t a, int32_t b); +double rs_calculator_pow(double base, double exp); +const char* rs_calculator_version(void); +} + +namespace rust_interop { + +double evaluate_expression(std::string_view expr) { + std::string null_term_expr(expr); + double result = 0.0; + char err_buf[256] = {0}; + + int32_t status = rs_calculator_eval( + null_term_expr.c_str(), + &result, + err_buf, + sizeof(err_buf) + ); + + if (status != 0) { + throw std::runtime_error(err_buf[0] != '\0' ? err_buf : "Rust evaluation failed"); + } + + return result; +} + +int32_t add(int32_t a, int32_t b) { + return rs_calculator_add(a, b); +} + +double pow(double base, double exp) { + return rs_calculator_pow(base, exp); +} + +std::string_view version() { + const char* v = rs_calculator_version(); + return v ? std::string_view(v) : "unknown"; +} + +} // namespace rust_interop diff --git a/cc/rust_calculator.hh b/cc/rust_calculator.hh new file mode 100644 index 0000000..589fb56 --- /dev/null +++ b/cc/rust_calculator.hh @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include + +namespace rust_interop { + +/// Evaluates a mathematical string expression using the hermetic Rust engine. +/// Supported operators: +, -, *, /, ^, ** and parentheses. +/// Throws std::runtime_error on failure (syntax error, division by zero, etc.). +double evaluate_expression(std::string_view expr); + +/// Adds two 32-bit integers via the Rust implementation. +int32_t add(int32_t a, int32_t b); + +/// Computes base raised to exponent via the Rust implementation. +double pow(double base, double exp); + +/// Returns the version string of the Rust calculator engine. +std::string_view version(); + +} // namespace rust_interop diff --git a/cc/rust_calculator_test.cc b/cc/rust_calculator_test.cc new file mode 100644 index 0000000..edb12fa --- /dev/null +++ b/cc/rust_calculator_test.cc @@ -0,0 +1,67 @@ +#include "cc/rust_calculator.hh" + +#include +#include +#include + +void test_basic_operations() { + assert(rust_interop::evaluate_expression("2 + 2") == 4.0); + assert(rust_interop::evaluate_expression("5 - 3") == 2.0); + assert(rust_interop::evaluate_expression("4 * 3") == 12.0); + assert(rust_interop::evaluate_expression("10 / 2") == 5.0); +} + +void test_operator_precedence() { + assert(rust_interop::evaluate_expression("2 + 3 * 4") == 14.0); + assert(rust_interop::evaluate_expression("(2 + 3) * 4") == 20.0); +} + +void test_power_operations() { + assert(rust_interop::evaluate_expression("2 ** 3") == 8.0); + assert(rust_interop::evaluate_expression("2 ^ 3") == 8.0); +} + +void test_unary_operations() { + assert(rust_interop::evaluate_expression("-5 + 3") == -2.0); + assert(rust_interop::evaluate_expression("-(3 * 2)") == -6.0); +} + +void test_division_by_zero() { + bool caught = false; + try { + rust_interop::evaluate_expression("10 / 0"); + } catch (const std::runtime_error& e) { + caught = true; + assert(std::string_view(e.what()) == "division by zero"); + } + assert(caught); +} + +void test_invalid_syntax() { + bool caught = false; + try { + rust_interop::evaluate_expression("2 + * 3"); + } catch (const std::runtime_error&) { + caught = true; + } + assert(caught); +} + +void test_direct_helpers() { + assert(rust_interop::add(15, 27) == 42); + assert(rust_interop::pow(2.0, 10.0) == 1024.0); + assert(rust_interop::version() == "1.0.0-rust"); +} + +int main() { + test_basic_operations(); + test_operator_precedence(); + test_power_operations(); + test_unary_operations(); + test_division_by_zero(); + test_invalid_syntax(); + test_direct_helpers(); + + std::cout << "All C++ calling Rust interop tests passed successfully!" << std::endl; + return 0; +} diff --git a/patches/BUILD.bazel b/patches/BUILD.bazel index 6a4b63c..eedaab5 100644 --- a/patches/BUILD.bazel +++ b/patches/BUILD.bazel @@ -1 +1,4 @@ -exports_files(["rules_rust_windows_gnu.patch"]) +exports_files([ + "rules_rust_cdylib_windows.patch", + "rules_rust_windows_gnu.patch", +]) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch new file mode 100644 index 0000000..db4b24e --- /dev/null +++ b/patches/rules_rust_cdylib_windows.patch @@ -0,0 +1,89 @@ +diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl +--- a/rust/private/rustc.bzl ++++ b/rust/private/rustc.bzl +@@ -1478,6 +1478,24 @@ + if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: + rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) + ++ # On Windows GNU targets, the C runtime startup object (dllcrt2.o) provides ++ # the DLL entry point (DllMainCRTStartup on 64-bit x86_64/aarch64, or ++ # _DllMainCRTStartup@12 with stdcall name decoration on 32-bit x86), which ++ # gcc/clang drivers pass via `-e`. When invoking a direct linker driver such ++ # as `rust-lld` without gcc/clang, `ld.lld -flavor gnu` defaults to looking ++ # for `_DllMainCRTStartup` (without @12 or without matching 64-bit symbols), ++ # causing an undefined symbol error. Pass the entry point explicitly. ++ if ( ++ crate_info.type in ("cdylib", "dylib", "proc-macro") and ++ toolchain.target_os == "windows" and ++ toolchain.target_abi != "msvc" and ++ ld_is_direct_driver ++ ): ++ if toolchain.target_arch in ("i686", "i586", "i386"): ++ rustc_flags.add("--codegen=link-arg=--entry=_DllMainCRTStartup@12") ++ else: ++ rustc_flags.add("--codegen=link-arg=--entry=DllMainCRTStartup") ++ + use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects) + + # These always need to be added, even if not linking this crate. +@@ -2010,9 +2028,14 @@ + # interface library that rustc generates in the output files. + interface_library = None + if toolchain.target_os == "windows" and crate_info.type == "cdylib": +- # Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc +- # expects (see https://github.com/rust-lang/rust/pull/29520 for more context). +- interface_library = ctx.actions.declare_file(crate_info.output.basename + ".lib", sibling = crate_info.output) ++ if toolchain.target_abi == "msvc": ++ # Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc ++ # expects (see https://github.com/rust-lang/rust/pull/29520 for more context). ++ interface_library_name = crate_info.output.basename + ".lib" ++ else: ++ # On non-MSVC Windows targets (e.g. gnu, gnullvm), rustc generates `lib.dll.a`. ++ interface_library_name = "lib" + crate_info.output.basename + ".a" ++ interface_library = ctx.actions.declare_file(interface_library_name, sibling = crate_info.output) + outputs.append(interface_library) + + # The action might generate extra output that we don't want to include in the `DefaultInfo` files. +@@ -2572,8 +2595,12 @@ + linking_context = linking_context, + debug_context = debug_context, + ), +- toolchain.stdlib_linkflags, + ] ++ ++ # A cdylib is already linked against the Rust standard library, so its ++ # stdlib link flags do not need to propagate to downstream link actions. ++ if crate_info.type != "cdylib": ++ cc_infos.append(toolchain.stdlib_linkflags) + + # Flattening is okay since crate_info.deps only records direct deps. + for dep in crate_info.deps.to_list(): +diff --git a/test/unit/cc_info/cc_info_test.bzl b/test/unit/cc_info/cc_info_test.bzl +--- a/test/unit/cc_info/cc_info_test.bzl ++++ b/test/unit/cc_info/cc_info_test.bzl +@@ -98,7 +98,7 @@ + def _cdylib_provides_cc_info_test_impl(ctx): + env = analysistest.begin(ctx) + tut = analysistest.target_under_test(env) +- _assert_cc_info_has_library_to_link(env, tut, "cdylib", 2) ++ _assert_cc_info_has_library_to_link(env, tut, "cdylib", 1) + return analysistest.end(env) + + def _staticlib_provides_cc_info_test_impl(ctx): +diff --git a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +--- a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl ++++ b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +@@ -12,10 +12,11 @@ + files = target[DefaultInfo].files.to_list() + cc_library = target[CcInfo].linking_context.linker_inputs.to_list()[0].libraries[0] + +- # Make sure that we have both the `.dll` and the `.dll.lib` file in the default info's files ++ # Make sure that we have both the `.dll` and the import library (`.dll.lib` on MSVC, ++ # `.dll.a` on GNU/LLVM-GNU) in the default info's files. + asserts.equals(env, len(files), 2) + asserts.true(env, files[0].basename.endswith(".dll")) +- asserts.true(env, files[1].basename.endswith(".dll.lib")) ++ asserts.true(env, files[1].basename.endswith((".dll.lib", ".dll.a"))) + + # Make sure that the cc_library has both a dynamic and interface library + asserts.true(env, cc_library.dynamic_library != None) diff --git a/patches/rules_rust_windows_gnu.patch b/patches/rules_rust_windows_gnu.patch index bf78bfe..adbe7aa 100644 --- a/patches/rules_rust_windows_gnu.patch +++ b/patches/rules_rust_windows_gnu.patch @@ -1,3 +1,4 @@ +diff --git a/rust/private/repository_utils.bzl b/rust/private/repository_utils.bzl --- a/rust/private/repository_utils.bzl +++ b/rust/private/repository_utils.bzl @@ -56,6 +56,7 @@ filegroup( diff --git a/rs/BUILD.bazel b/rs/BUILD.bazel index 57ecf70..e8070e2 100644 --- a/rs/BUILD.bazel +++ b/rs/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_test") +load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_shared_library", "rust_test") rust_library( name = "calculator", @@ -7,12 +7,31 @@ rust_library( visibility = ["//:__subpackages__"], ) +rust_shared_library( + name = "rust_calculator", + srcs = ["rust_calculator.rs"], + edition = "2021", + visibility = ["//visibility:public"], + deps = [":calculator"], +) + +rust_library( + name = "cpp_calculator", + srcs = ["cpp_calculator.rs"], + edition = "2021", + link_deps = ["//cc:calculator"], + visibility = ["//:__subpackages__"], +) + rust_binary( name = "main", srcs = ["main.rs"], edition = "2021", visibility = ["//:__subpackages__"], - deps = [":calculator"], + deps = [ + ":calculator", + ":cpp_calculator", + ], ) rust_test( @@ -21,3 +40,10 @@ rust_test( edition = "2021", deps = [":calculator"], ) + +rust_test( + name = "cpp_calculator_test", + srcs = ["cpp_calculator_test.rs"], + edition = "2021", + deps = [":cpp_calculator"], +) diff --git a/rs/cpp_calculator.rs b/rs/cpp_calculator.rs new file mode 100644 index 0000000..825e097 --- /dev/null +++ b/rs/cpp_calculator.rs @@ -0,0 +1,65 @@ +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int}; + +extern "C" { + fn cc_calculator_eval( + expr: *const c_char, + out_result: *mut f64, + err_buf: *mut c_char, + err_buf_len: usize, + ) -> c_int; + + fn cc_calculator_add(a: i32, b: i32) -> i32; + fn cc_calculator_pow(base: f64, exp: f64) -> f64; + fn cc_calculator_version() -> *const c_char; +} + +/// Safely evaluates a mathematical string expression using the hermetic C++ engine. +/// +/// Supported operators: +, -, *, /, ^, ** and parentheses. +/// Returns Ok(f64) on success, or Err(String) describing the parsing or runtime error. +pub fn evaluate_expression_cpp(expr: &str) -> Result { + let c_expr = CString::new(expr).map_err(|e| format!("invalid C string: {e}"))?; + let mut result = 0.0f64; + let mut err_buf = [0u8; 256]; + + let status = unsafe { + cc_calculator_eval( + c_expr.as_ptr(), + &mut result, + err_buf.as_mut_ptr() as *mut c_char, + err_buf.len(), + ) + }; + + if status == 0 { + Ok(result) + } else { + let err_msg = unsafe { CStr::from_ptr(err_buf.as_ptr() as *const c_char) } + .to_str() + .unwrap_or("unknown error"); + Err(err_msg.to_string()) + } +} + +/// Invokes the C++ integer addition function via FFI. +pub fn add_cpp(a: i32, b: i32) -> i32 { + unsafe { cc_calculator_add(a, b) } +} + +/// Invokes the C++ power function via FFI. +pub fn pow_cpp(base: f64, exp: f64) -> f64 { + unsafe { cc_calculator_pow(base, exp) } +} + +/// Returns the C++ calculator engine version string via FFI. +pub fn version_cpp() -> &'static str { + unsafe { + let ptr = cc_calculator_version(); + if ptr.is_null() { + "unknown" + } else { + CStr::from_ptr(ptr).to_str().unwrap_or("unknown") + } + } +} diff --git a/rs/cpp_calculator_test.rs b/rs/cpp_calculator_test.rs new file mode 100644 index 0000000..dc91566 --- /dev/null +++ b/rs/cpp_calculator_test.rs @@ -0,0 +1,56 @@ +use cpp_calculator::{add_cpp, evaluate_expression_cpp, pow_cpp, version_cpp}; + +#[test] +fn test_cpp_basic_operations() { + assert_eq!(evaluate_expression_cpp("2 + 2"), Ok(4.0)); + assert_eq!(evaluate_expression_cpp("5 - 3"), Ok(2.0)); + assert_eq!(evaluate_expression_cpp("4 * 3"), Ok(12.0)); + assert_eq!(evaluate_expression_cpp("10 / 2"), Ok(5.0)); +} + +#[test] +fn test_cpp_operator_precedence() { + assert_eq!(evaluate_expression_cpp("2 + 3 * 4"), Ok(14.0)); + assert_eq!(evaluate_expression_cpp("(2 + 3) * 4"), Ok(20.0)); +} + +#[test] +fn test_cpp_power_operations() { + assert_eq!(evaluate_expression_cpp("2 ** 3"), Ok(8.0)); + assert_eq!(evaluate_expression_cpp("2 ^ 3"), Ok(8.0)); +} + +#[test] +fn test_cpp_unary_operations() { + assert_eq!(evaluate_expression_cpp("-5 + 3"), Ok(-2.0)); + assert_eq!(evaluate_expression_cpp("-(3 * 2)"), Ok(-6.0)); +} + +#[test] +fn test_cpp_division_by_zero() { + let result = evaluate_expression_cpp("10 / 0"); + assert!(result.is_err()); + assert_eq!(result.unwrap_err(), "division by zero"); +} + +#[test] +fn test_cpp_invalid_syntax() { + assert!(evaluate_expression_cpp("2 + * 3").is_err()); +} + +#[test] +fn test_cpp_unsupported_operations() { + assert!(evaluate_expression_cpp("import os").is_err()); +} + +#[test] +fn test_cpp_float_parsing() { + assert_eq!(evaluate_expression_cpp("2.5 * 4"), Ok(10.0)); +} + +#[test] +fn test_cpp_direct_helpers() { + assert_eq!(add_cpp(15, 27), 42); + assert_eq!(pow_cpp(2.0, 10.0), 1024.0); + assert_eq!(version_cpp(), "1.0.0-cpp"); +} diff --git a/rs/main.rs b/rs/main.rs index c6b004d..9d04bae 100644 --- a/rs/main.rs +++ b/rs/main.rs @@ -4,8 +4,9 @@ use std::process; fn print_usage() { println!("Usage: main [arguments]"); println!("Commands:"); - println!(" info Display information about the Rust environment."); - println!(" calc Evaluate a mathematical expression securely."); + println!(" info Display information about the Rust environment."); + println!(" calc Evaluate a mathematical expression using Rust engine."); + println!(" calc-cpp Evaluate a mathematical expression using C++ FFI engine."); } fn main() { @@ -19,6 +20,10 @@ fn main() { "info" => { println!("OS: {}, Arch: {}", env::consts::OS, env::consts::ARCH); println!("Bazel hermetic Rust template is working!"); + println!( + "C++ Interop Engine Version: {}", + cpp_calculator::version_cpp() + ); } "calc" => { if args.len() < 3 { @@ -34,6 +39,20 @@ fn main() { } } } + "calc-cpp" => { + if args.len() < 3 { + eprintln!("Error: calc-cpp command requires a mathematical expression."); + process::exit(1); + } + let expression = &args[2]; + match cpp_calculator::evaluate_expression_cpp(expression) { + Ok(result) => println!("{expression} = {result} (via C++ engine)"), + Err(err) => { + eprintln!("Error: {err}"); + process::exit(1); + } + } + } unknown => { eprintln!("Error: Unknown command '{unknown}'"); print_usage(); diff --git a/rs/rust_calculator.rs b/rs/rust_calculator.rs new file mode 100644 index 0000000..1fab149 --- /dev/null +++ b/rs/rust_calculator.rs @@ -0,0 +1,91 @@ +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int}; + +/// Evaluates a mathematical string expression using the Rust calculator engine. +/// +/// Returns 0 on success, or a non-zero error code: +/// 1: Division by zero +/// 2: Invalid syntax +/// 3: Empty expression +/// 4: Trailing unparsed tokens +/// -1: Null pointer or unexpected error +/// +/// # Safety +/// Caller must ensure that `expr` is a valid null-terminated C string and +/// that `out_result` and `err_buf` point to valid memory if non-null. +#[no_mangle] +pub unsafe extern "C" fn rs_calculator_eval( + expr: *const c_char, + out_result: *mut f64, + err_buf: *mut c_char, + err_buf_len: usize, +) -> c_int { + if expr.is_null() || out_result.is_null() { + if !err_buf.is_null() && err_buf_len > 0 { + let msg = b"null pointer argument\0"; + let copy_len = msg.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(msg.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + return -1; + } + + let c_str = CStr::from_ptr(expr); + let expr_str = match c_str.to_str() { + Ok(s) => s, + Err(_) => { + if !err_buf.is_null() && err_buf_len > 0 { + let msg = b"invalid utf-8 string\0"; + let copy_len = msg.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(msg.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + return 2; + } + }; + + match calculator::evaluate_expression(expr_str) { + Ok(val) => { + *out_result = val; + if !err_buf.is_null() && err_buf_len > 0 { + *err_buf = 0; + } + 0 + } + Err(err) => { + let code = match err.as_str() { + "division by zero" => 1, + "empty expression" => 3, + "trailing unparsed tokens" => 4, + _ => 2, + }; + if !err_buf.is_null() && err_buf_len > 0 { + let c_err = CString::new(err).unwrap_or_default(); + let bytes = c_err.as_bytes_with_nul(); + let copy_len = bytes.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + code + } + } +} + +/// Evaluates integer addition in Rust. +#[no_mangle] +pub extern "C" fn rs_calculator_add(a: i32, b: i32) -> i32 { + a + b +} + +/// Evaluates floating point exponentiation in Rust. +#[no_mangle] +pub extern "C" fn rs_calculator_pow(base: f64, exp: f64) -> f64 { + base.powf(exp) +} + +/// Returns the Rust calculator engine version string. +#[no_mangle] +pub extern "C" fn rs_calculator_version() -> *const c_char { + static VERSION: &[u8] = b"1.0.0-rust\0"; + VERSION.as_ptr() as *const c_char +} From 403e079bc9f47e42a354289e2065f37ff1324335 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:39:10 -0700 Subject: [PATCH 02/19] fix(rules_rust): switch to -Bstatic for trailing static libraries on Linux/ELF --- patches/rules_rust_cdylib_windows.patch | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch index db4b24e..f11d082 100644 --- a/patches/rules_rust_cdylib_windows.patch +++ b/patches/rules_rust_cdylib_windows.patch @@ -58,6 +58,35 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl # Flattening is okay since crate_info.deps only records direct deps. for dep in crate_info.deps.to_list(): +@@ -3019,6 +3046,7 @@ + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + ret.extend([ +@@ -3027,7 +3055,19 @@ + ("-Clink-arg=%s--no-whole-archive" % prefix), + ]) + elif include_link_flags: +- ret.extend(portable_link_flags(lib, use_pic, ambiguous_libs, get_lib_name_default)) ++ flags = portable_link_flags(lib, use_pic, ambiguous_libs, get_lib_name_default) ++ if (lib.static_library or lib.pic_static_library) and not _is_dylib(lib): ++ # On Linux/ELF platforms, rustc emits `-Wl,-Bdynamic` before trailing link-args. ++ # When linking against static libraries in Section C, switch the linker to static ++ # mode so that `-l` searches for `lib.a` rather than requiring `lib.so`. ++ ret.extend([f for f in flags if not f.startswith("-Clink-arg=")]) ++ ret.append("-Clink-arg=%s-Bstatic" % prefix) ++ ret.extend([f for f in flags if f.startswith("-Clink-arg=")]) ++ has_static_trailing_libs = True ++ else: ++ ret.extend(flags) ++ if has_static_trailing_libs: ++ ret.append("-Clink-arg=%s-Bdynamic" % prefix) + _add_user_link_flags(ret, linker_input) + return ret + diff --git a/test/unit/cc_info/cc_info_test.bzl b/test/unit/cc_info/cc_info_test.bzl --- a/test/unit/cc_info/cc_info_test.bzl +++ b/test/unit/cc_info/cc_info_test.bzl From 978046dfec354d25770ddbdb04148cd56c854b01 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:50:25 -0700 Subject: [PATCH 03/19] fix(cc): link C++ libraries statically and configure runtime library paths for Linux --- cc/BUILD.bazel | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/cc/BUILD.bazel b/cc/BUILD.bazel index 64549ff..fec59df 100644 --- a/cc/BUILD.bazel +++ b/cc/BUILD.bazel @@ -8,6 +8,7 @@ cc_library( "-fno-exceptions", "-fno-rtti", ], + linkstatic = True, visibility = ["//visibility:public"], ) @@ -15,6 +16,7 @@ cc_library( name = "rust_calculator", srcs = ["rust_calculator.cc"], hdrs = ["rust_calculator.hh"], + linkstatic = True, visibility = ["//visibility:public"], deps = ["//rs:rust_calculator"], ) @@ -27,8 +29,20 @@ cc_binary( "@platforms//os:windows": { "PATH": "rs;.", }, + "@platforms//os:linux": { + "LD_LIBRARY_PATH": "rs:.", + }, "//conditions:default": {}, }), + linkopts = select({ + "@platforms//os:linux": [ + "-Wl,-rpath,$$ORIGIN/../rs", + "-Wl,-rpath,$$ORIGIN/rs", + "-Wl,-rpath,$$ORIGIN", + ], + "//conditions:default": [], + }), + linkstatic = True, visibility = ["//visibility:public"], deps = [ ":calculator", @@ -40,6 +54,7 @@ cc_binary( cc_test( name = "calculator_test", srcs = ["calculator_test.cc"], + linkstatic = True, deps = [":calculator"], ) @@ -51,8 +66,20 @@ cc_test( "@platforms//os:windows": { "PATH": "rs;.", }, + "@platforms//os:linux": { + "LD_LIBRARY_PATH": "rs:.", + }, "//conditions:default": {}, }), + linkopts = select({ + "@platforms//os:linux": [ + "-Wl,-rpath,$$ORIGIN/../rs", + "-Wl,-rpath,$$ORIGIN/rs", + "-Wl,-rpath,$$ORIGIN", + ], + "//conditions:default": [], + }), + linkstatic = True, deps = [ ":rust_calculator", "//rs:rust_calculator", From fa37036f1c5656b19ad3cca874fdcb5cb180b7c0 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:57:31 -0700 Subject: [PATCH 04/19] fix(rules_rust): add DT_SONAME support for ELF dynamic libraries in patch --- patches/rules_rust_cdylib_windows.patch | 26 +++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch index f11d082..39d4c8c 100644 --- a/patches/rules_rust_cdylib_windows.patch +++ b/patches/rules_rust_cdylib_windows.patch @@ -1,10 +1,24 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl --- a/rust/private/rustc.bzl +++ b/rust/private/rustc.bzl -@@ -1478,6 +1478,24 @@ - if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: +@@ -1476,8 +1476,35 @@ +- # On macOS, set the dylib install name to @rpath/ so that +- # consumers find it via RPATH rather than the exec-root build path. +- if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: ++ # On macOS, set the dylib/cdylib install name to @rpath/ so that ++ # consumers find it via RPATH rather than the exec-root build path. ++ if crate_info.type in ("cdylib", "dylib") and toolchain.target_os in ["macos", "darwin"]: rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) ++ # On ELF platforms, set the DT_SONAME so that downstream linkers ++ # record the soname rather than the exec-root solib path. ++ if ( ++ crate_info.type in ("cdylib", "dylib") and ++ toolchain.target_os in ["linux", "android", "freebsd", "openbsd", "netbsd"] ++ ): ++ prefix = "" if ld_is_direct_driver else "-Wl," ++ rustc_flags.add("--codegen=link-arg=%s-soname=%s" % (prefix, crate_info.output.basename)) ++ + # On Windows GNU targets, the C runtime startup object (dllcrt2.o) provides + # the DLL entry point (DllMainCRTStartup on 64-bit x86_64/aarch64, or + # _DllMainCRTStartup@12 with stdcall name decoration on 32-bit x86), which @@ -26,7 +40,7 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects) # These always need to be added, even if not linking this crate. -@@ -2010,9 +2028,14 @@ +@@ -2010,9 +2037,14 @@ # interface library that rustc generates in the output files. interface_library = None if toolchain.target_os == "windows" and crate_info.type == "cdylib": @@ -44,7 +58,7 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl outputs.append(interface_library) # The action might generate extra output that we don't want to include in the `DefaultInfo` files. -@@ -2572,8 +2595,12 @@ +@@ -2572,8 +2604,12 @@ linking_context = linking_context, debug_context = debug_context, ), @@ -58,7 +72,7 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl # Flattening is okay since crate_info.deps only records direct deps. for dep in crate_info.deps.to_list(): -@@ -3019,6 +3046,7 @@ +@@ -3019,6 +3055,7 @@ linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args ret = [] prefix = "" if use_direct_driver else "-Wl," @@ -66,7 +80,7 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl for lib in linker_input.libraries: if lib.alwayslink: ret.extend([ -@@ -3027,7 +3055,19 @@ +@@ -3027,7 +3064,19 @@ ("-Clink-arg=%s--no-whole-archive" % prefix), ]) elif include_link_flags: From 0535389908ba8f3cb159a9844d1aeba4d8a74852 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:25:15 -0700 Subject: [PATCH 05/19] ci: add macos-latest runner to CI matrix and configure macos rpath --- .github/workflows/ci.yml | 8 ++++++-- cc/BUILD.bazel | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a97104..ae7d908 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,8 +5,12 @@ on: jobs: ci: - name: Continuous Testing - runs-on: ubuntu-latest + name: Continuous Testing (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] steps: - name: Checkout repository diff --git a/cc/BUILD.bazel b/cc/BUILD.bazel index fec59df..f6d2e22 100644 --- a/cc/BUILD.bazel +++ b/cc/BUILD.bazel @@ -32,6 +32,9 @@ cc_binary( "@platforms//os:linux": { "LD_LIBRARY_PATH": "rs:.", }, + "@platforms//os:macos": { + "DYLD_LIBRARY_PATH": "rs:.", + }, "//conditions:default": {}, }), linkopts = select({ @@ -40,6 +43,11 @@ cc_binary( "-Wl,-rpath,$$ORIGIN/rs", "-Wl,-rpath,$$ORIGIN", ], + "@platforms//os:macos": [ + "-Wl,-rpath,@loader_path/../rs", + "-Wl,-rpath,@loader_path/rs", + "-Wl,-rpath,@loader_path", + ], "//conditions:default": [], }), linkstatic = True, @@ -69,6 +77,9 @@ cc_test( "@platforms//os:linux": { "LD_LIBRARY_PATH": "rs:.", }, + "@platforms//os:macos": { + "DYLD_LIBRARY_PATH": "rs:.", + }, "//conditions:default": {}, }), linkopts = select({ @@ -77,6 +88,11 @@ cc_test( "-Wl,-rpath,$$ORIGIN/rs", "-Wl,-rpath,$$ORIGIN", ], + "@platforms//os:macos": [ + "-Wl,-rpath,@loader_path/../rs", + "-Wl,-rpath,@loader_path/rs", + "-Wl,-rpath,@loader_path", + ], "//conditions:default": [], }), linkstatic = True, From f6bc009c10949a1540683bf6fe5e4fb196a9698e Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:29:08 -0700 Subject: [PATCH 06/19] build(macos): set toolchain_linker_preference=rust on macOS to support Apple ld64 flags --- .bazelrc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.bazelrc b/.bazelrc index 0175683..4e4e399 100644 --- a/.bazelrc +++ b/.bazelrc @@ -24,6 +24,10 @@ build:windows --nolegacy_external_runfiles # hermetic x86_64-pc-windows-gnu toolchain instead of the C++ toolchain wrapper. build:windows --@rules_rust//rust/settings:toolchain_linker_preference=rust +# On macOS, let rustc invoke its own linker driver instead of hermetic_cc_toolchain +# (which uses zig c++ and does not support Apple ld64 flags like -oso_prefix). +build:macos --@rules_rust//rust/settings:toolchain_linker_preference=rust + # Linting settings # To run linting: bazel build --config=lint //... build:lint --aspects=//tools:lint.bzl%ruff,@rules_rust//rust:defs.bzl%rust_clippy_aspect,@rules_rust//rust:defs.bzl%rustfmt_aspect From b137218d8603abca5edcbec9ad00aa36b7d19e72 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:35:10 -0700 Subject: [PATCH 07/19] fix(toolchain): bypass Zig CC on macOS to use native Apple Clang toolchain --- MODULE.bazel | 8 ++++++++ patches/hermetic_cc_toolchain_darwin.patch | 11 +++++++++++ 2 files changed, 19 insertions(+) create mode 100644 patches/hermetic_cc_toolchain_darwin.patch diff --git a/MODULE.bazel b/MODULE.bazel index b006c14..b9d5320 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -76,6 +76,14 @@ use_repo(rust, "rust_toolchains") register_toolchains("@rust_toolchains//:all") +single_version_override( + module_name = "hermetic_cc_toolchain", + patch_strip = 1, + patches = [ + "//patches:hermetic_cc_toolchain_darwin.patch", + ], +) + single_version_override( module_name = "rules_rust", patch_strip = 1, diff --git a/patches/hermetic_cc_toolchain_darwin.patch b/patches/hermetic_cc_toolchain_darwin.patch new file mode 100644 index 0000000..9956781 --- /dev/null +++ b/patches/hermetic_cc_toolchain_darwin.patch @@ -0,0 +1,11 @@ +diff --git a/toolchain/toolchain/defs.bzl b/toolchain/toolchain/defs.bzl +--- a/toolchain/toolchain/defs.bzl ++++ b/toolchain/toolchain/defs.bzl +@@ -4,3 +4,7 @@ def declare_toolchains(configs = "", extra_target_settings = []): + for target_config in target_structs(): ++ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain ++ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. ++ if target_config.libc == "darwin": ++ continue + gotarget = target_config.gotarget + zigtarget = target_config.zigtarget From e27bdeae959809497ef0ca35250f8562d99102cd Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:42:12 -0700 Subject: [PATCH 08/19] build(macos): use default cc linker preference with native Apple Clang --- .bazelrc | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.bazelrc b/.bazelrc index 4e4e399..0175683 100644 --- a/.bazelrc +++ b/.bazelrc @@ -24,10 +24,6 @@ build:windows --nolegacy_external_runfiles # hermetic x86_64-pc-windows-gnu toolchain instead of the C++ toolchain wrapper. build:windows --@rules_rust//rust/settings:toolchain_linker_preference=rust -# On macOS, let rustc invoke its own linker driver instead of hermetic_cc_toolchain -# (which uses zig c++ and does not support Apple ld64 flags like -oso_prefix). -build:macos --@rules_rust//rust/settings:toolchain_linker_preference=rust - # Linting settings # To run linting: bazel build --config=lint //... build:lint --aspects=//tools:lint.bzl%ruff,@rules_rust//rust:defs.bzl%rust_clippy_aspect,@rules_rust//rust:defs.bzl%rustfmt_aspect From 5d36a5e3f0bb17def4982a864de28caebc01cb55 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:51:41 -0700 Subject: [PATCH 09/19] fix(rules_rust): support direct linker drivers on macOS for cdylib install_name --- patches/rules_rust_cdylib_windows.patch | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch index 39d4c8c..e3b0462 100644 --- a/patches/rules_rust_cdylib_windows.patch +++ b/patches/rules_rust_cdylib_windows.patch @@ -1,14 +1,19 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl --- a/rust/private/rustc.bzl +++ b/rust/private/rustc.bzl -@@ -1476,8 +1476,35 @@ +@@ -1476,8 +1476,40 @@ - # On macOS, set the dylib install name to @rpath/ so that - # consumers find it via RPATH rather than the exec-root build path. - if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: +- rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) + # On macOS, set the dylib/cdylib install name to @rpath/ so that + # consumers find it via RPATH rather than the exec-root build path. + if crate_info.type in ("cdylib", "dylib") and toolchain.target_os in ["macos", "darwin"]: - rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) ++ if ld_is_direct_driver: ++ rustc_flags.add("--codegen=link-arg=-install_name") ++ rustc_flags.add("--codegen=link-arg=@rpath/" + crate_info.output.basename) ++ else: ++ rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) + # On ELF platforms, set the DT_SONAME so that downstream linkers + # record the soname rather than the exec-root solib path. From 2fa4dcde4b78f26ab652fdd4874eae83bf8ea6cb Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:15:14 -0700 Subject: [PATCH 10/19] fix(go): resolve nested bazel invocation and working directory in staticcheck --- bin/go.py | 15 +++++++++++++++ tools/BUILD.bazel | 5 ++--- tools/staticcheck.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 tools/staticcheck.py diff --git a/bin/go.py b/bin/go.py index c04aa76..2e64a60 100644 --- a/bin/go.py +++ b/bin/go.py @@ -8,6 +8,7 @@ from __future__ import annotations import os +import subprocess import sys from pathlib import Path @@ -19,6 +20,20 @@ def main() -> None: + # When invoked as a subtool from another running Bazel process (e.g. staticcheck or goimports), + # avoid re-invoking Bazel (which causes output-base lock deadlocks). + # Instead, locate the hermetic Go binary directly in BUILD_EXECROOT. + execroot = os.environ.get("BUILD_EXECROOT") + if execroot: + exe_name = "go.exe" if sys.platform == "win32" else "go" + external_dir = Path(execroot) / "external" + if external_dir.is_dir(): + for entry in external_dir.iterdir(): + if "rules_go" in entry.name and "go_sdk" in entry.name: + go_bin = entry / "bin" / exe_name + if go_bin.is_file(): + sys.exit(subprocess.run([str(go_bin), *sys.argv[1:]], check=False).returncode) + # Run @rules_go//go target with all arguments run_bazel_target("@rules_go//go", extra_args=sys.argv[1:]) diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel index cedb81a..fc9b3c8 100644 --- a/tools/BUILD.bazel +++ b/tools/BUILD.bazel @@ -53,10 +53,9 @@ py_binary( py_binary( name = "staticcheck", - srcs = ["run_in_cwd.py"], - args = ["$(rlocationpath @co_honnef_go_tools//cmd/staticcheck:staticcheck)"], + srcs = ["staticcheck.py"], data = ["@co_honnef_go_tools//cmd/staticcheck"], - main = "run_in_cwd.py", + main = "staticcheck.py", visibility = ["//visibility:public"], ) diff --git a/tools/staticcheck.py b/tools/staticcheck.py new file mode 100644 index 0000000..b55a62a --- /dev/null +++ b/tools/staticcheck.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Launcher for staticcheck that restores the workspace working directory.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + + +def main() -> None: + workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") + if workspace_dir: + os.chdir(workspace_dir) + + exe_name = "staticcheck.exe" if sys.platform == "win32" else "staticcheck" + runfiles_dir = os.environ.get("RUNFILES_DIR") + found_bin = None + + if runfiles_dir: + for root, _dirs, files in os.walk(runfiles_dir): + if exe_name in files: + found_bin = Path(root) / exe_name + break + + if not found_bin: + # Fallback to searching relative to this script + for root, _dirs, files in os.walk(Path(__file__).parent.parent): + if exe_name in files and "staticcheck_" in root: + found_bin = Path(root) / exe_name + break + + if not found_bin: + sys.stderr.write("Error: Could not locate staticcheck binary in runfiles.\n") + sys.exit(1) + + res = subprocess.run([str(found_bin), *sys.argv[1:]], check=False) + sys.exit(res.returncode) + + +if __name__ == "__main__": + main() From 87175a6fb7596e2b946cd3708e925aa13d763368 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:23:38 -0700 Subject: [PATCH 11/19] fix(tools): robustly locate staticcheck binary in python runfiles across platforms --- tools/staticcheck.py | 48 ++++++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/tools/staticcheck.py b/tools/staticcheck.py index b55a62a..9038119 100644 --- a/tools/staticcheck.py +++ b/tools/staticcheck.py @@ -9,27 +9,45 @@ from pathlib import Path +def _find_runfiles_dir() -> Path | None: + runfiles_env = os.environ.get("PYTHON_RUNFILES") or os.environ.get("RUNFILES_DIR") + if runfiles_env and Path(runfiles_env).is_dir(): + return Path(runfiles_env) + + for parent in [Path(__file__).resolve(), *Path(__file__).resolve().parents]: + if parent.name.endswith(".runfiles") and parent.is_dir(): + return parent + return None + + +def _find_binary(exe_name: str) -> Path | None: + search_dirs: list[Path] = [] + runfiles_dir = _find_runfiles_dir() + if runfiles_dir: + search_dirs.append(runfiles_dir) + search_dirs.extend( + [ + Path(__file__).resolve().parent.parent, + Path(__file__).resolve().parent.parent.parent, + ] + ) + + for base in search_dirs: + if not base.is_dir(): + continue + for root, _dirs, files in os.walk(base): + if exe_name in files and "staticcheck_" in root: + return Path(root) / exe_name + return None + + def main() -> None: workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") if workspace_dir: os.chdir(workspace_dir) exe_name = "staticcheck.exe" if sys.platform == "win32" else "staticcheck" - runfiles_dir = os.environ.get("RUNFILES_DIR") - found_bin = None - - if runfiles_dir: - for root, _dirs, files in os.walk(runfiles_dir): - if exe_name in files: - found_bin = Path(root) / exe_name - break - - if not found_bin: - # Fallback to searching relative to this script - for root, _dirs, files in os.walk(Path(__file__).parent.parent): - if exe_name in files and "staticcheck_" in root: - found_bin = Path(root) / exe_name - break + found_bin = _find_binary(exe_name) if not found_bin: sys.stderr.write("Error: Could not locate staticcheck binary in runfiles.\n") From 95cfc72eb985bb096bc595cd037cd7510cb66694 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:31:51 -0700 Subject: [PATCH 12/19] fix(tools): locate staticcheck binary before chdir to workspace --- tools/staticcheck.py | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/tools/staticcheck.py b/tools/staticcheck.py index 9038119..dca92af 100644 --- a/tools/staticcheck.py +++ b/tools/staticcheck.py @@ -8,29 +8,47 @@ import sys from pathlib import Path +SCRIPT_PATH = Path(__file__).resolve() + + +def _find_binary_from_manifest(exe_name: str) -> Path | None: + manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE") + if manifest_file: + manifest_path = Path(manifest_file) + if manifest_path.is_file(): + with manifest_path.open(encoding="utf-8") as f: + for line in f: + match line.strip().split(" ", 1): + case [rpath, target] if rpath.endswith(f"/{exe_name}"): + candidate = Path(target) + if candidate.is_file(): + return candidate + case _: + continue + return None + def _find_runfiles_dir() -> Path | None: runfiles_env = os.environ.get("PYTHON_RUNFILES") or os.environ.get("RUNFILES_DIR") if runfiles_env and Path(runfiles_env).is_dir(): return Path(runfiles_env) - for parent in [Path(__file__).resolve(), *Path(__file__).resolve().parents]: + for parent in [SCRIPT_PATH, *SCRIPT_PATH.parents]: if parent.name.endswith(".runfiles") and parent.is_dir(): return parent return None def _find_binary(exe_name: str) -> Path | None: + from_manifest = _find_binary_from_manifest(exe_name) + if from_manifest: + return from_manifest + search_dirs: list[Path] = [] runfiles_dir = _find_runfiles_dir() if runfiles_dir: search_dirs.append(runfiles_dir) - search_dirs.extend( - [ - Path(__file__).resolve().parent.parent, - Path(__file__).resolve().parent.parent.parent, - ] - ) + search_dirs.extend([SCRIPT_PATH.parent.parent, SCRIPT_PATH.parent.parent.parent]) for base in search_dirs: if not base.is_dir(): @@ -42,10 +60,6 @@ def _find_binary(exe_name: str) -> Path | None: def main() -> None: - workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") - if workspace_dir: - os.chdir(workspace_dir) - exe_name = "staticcheck.exe" if sys.platform == "win32" else "staticcheck" found_bin = _find_binary(exe_name) @@ -53,7 +67,11 @@ def main() -> None: sys.stderr.write("Error: Could not locate staticcheck binary in runfiles.\n") sys.exit(1) - res = subprocess.run([str(found_bin), *sys.argv[1:]], check=False) + workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") + if workspace_dir: + os.chdir(workspace_dir) + + res = subprocess.run([str(found_bin.resolve()), *sys.argv[1:]], check=False) sys.exit(res.returncode) From 33cfd2a66fb715df4ed51c1e666fab424a382531 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:51:59 -0700 Subject: [PATCH 13/19] fix(go): provision hermetic go in staticcheck runfiles to prevent bazel deadlock --- bin/go.py | 15 --------------- tools/BUILD.bazel | 5 ++++- tools/staticcheck.py | 41 +++++++++++++++++++++++++---------------- 3 files changed, 29 insertions(+), 32 deletions(-) diff --git a/bin/go.py b/bin/go.py index 2e64a60..c04aa76 100644 --- a/bin/go.py +++ b/bin/go.py @@ -8,7 +8,6 @@ from __future__ import annotations import os -import subprocess import sys from pathlib import Path @@ -20,20 +19,6 @@ def main() -> None: - # When invoked as a subtool from another running Bazel process (e.g. staticcheck or goimports), - # avoid re-invoking Bazel (which causes output-base lock deadlocks). - # Instead, locate the hermetic Go binary directly in BUILD_EXECROOT. - execroot = os.environ.get("BUILD_EXECROOT") - if execroot: - exe_name = "go.exe" if sys.platform == "win32" else "go" - external_dir = Path(execroot) / "external" - if external_dir.is_dir(): - for entry in external_dir.iterdir(): - if "rules_go" in entry.name and "go_sdk" in entry.name: - go_bin = entry / "bin" / exe_name - if go_bin.is_file(): - sys.exit(subprocess.run([str(go_bin), *sys.argv[1:]], check=False).returncode) - # Run @rules_go//go target with all arguments run_bazel_target("@rules_go//go", extra_args=sys.argv[1:]) diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel index fc9b3c8..a6f43b6 100644 --- a/tools/BUILD.bazel +++ b/tools/BUILD.bazel @@ -54,7 +54,10 @@ py_binary( py_binary( name = "staticcheck", srcs = ["staticcheck.py"], - data = ["@co_honnef_go_tools//cmd/staticcheck"], + data = [ + "@co_honnef_go_tools//cmd/staticcheck", + "@rules_go//go", + ], main = "staticcheck.py", visibility = ["//visibility:public"], ) diff --git a/tools/staticcheck.py b/tools/staticcheck.py index dca92af..be0d7a4 100644 --- a/tools/staticcheck.py +++ b/tools/staticcheck.py @@ -1,17 +1,18 @@ #!/usr/bin/env python3 -"""Launcher for staticcheck that restores the workspace working directory.""" +"""Launcher for staticcheck that restores the workspace working directory and provisions hermetic Go.""" from __future__ import annotations import os import subprocess import sys +from collections.abc import Callable from pathlib import Path SCRIPT_PATH = Path(__file__).resolve() -def _find_binary_from_manifest(exe_name: str) -> Path | None: +def _find_file_from_manifest(predicate: Callable[[str], bool]) -> Path | None: manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE") if manifest_file: manifest_path = Path(manifest_file) @@ -19,7 +20,7 @@ def _find_binary_from_manifest(exe_name: str) -> Path | None: with manifest_path.open(encoding="utf-8") as f: for line in f: match line.strip().split(" ", 1): - case [rpath, target] if rpath.endswith(f"/{exe_name}"): + case [rpath, target] if predicate(rpath): candidate = Path(target) if candidate.is_file(): return candidate @@ -39,34 +40,42 @@ def _find_runfiles_dir() -> Path | None: return None -def _find_binary(exe_name: str) -> Path | None: - from_manifest = _find_binary_from_manifest(exe_name) +def _find_binary(rel_suffix: str, exe_name: str) -> Path | None: + from_manifest = _find_file_from_manifest(lambda rpath: rpath.endswith(f"{rel_suffix}/{exe_name}")) if from_manifest: return from_manifest - search_dirs: list[Path] = [] runfiles_dir = _find_runfiles_dir() if runfiles_dir: - search_dirs.append(runfiles_dir) - search_dirs.extend([SCRIPT_PATH.parent.parent, SCRIPT_PATH.parent.parent.parent]) - - for base in search_dirs: - if not base.is_dir(): - continue - for root, _dirs, files in os.walk(base): - if exe_name in files and "staticcheck_" in root: - return Path(root) / exe_name + for repo_dir in runfiles_dir.iterdir(): + if not repo_dir.is_dir(): + continue + candidate = repo_dir / rel_suffix / exe_name + if candidate.is_file(): + return candidate + return None def main() -> None: exe_name = "staticcheck.exe" if sys.platform == "win32" else "staticcheck" - found_bin = _find_binary(exe_name) + go_exe = "go.exe" if sys.platform == "win32" else "go" + + found_bin = _find_binary("cmd/staticcheck/staticcheck_", exe_name) + if not found_bin: + found_bin = _find_binary("cmd/staticcheck", exe_name) if not found_bin: sys.stderr.write("Error: Could not locate staticcheck binary in runfiles.\n") sys.exit(1) + hermetic_go = _find_binary("go/tools/go_bin_runner/bin", go_exe) + if not hermetic_go: + hermetic_go = _find_binary("bin", go_exe) + + if hermetic_go: + os.environ["PATH"] = str(hermetic_go.parent.resolve()) + os.pathsep + os.environ.get("PATH", "") + workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") if workspace_dir: os.chdir(workspace_dir) From 1ebd6b274b73093860cabf5947c40d4dcc6e14b0 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:23:38 -0700 Subject: [PATCH 14/19] fix(toolchain): support dynamic linking in hermetic_cc_toolchain and rules_rust - Add patches/hermetic_cc_toolchain_dynamic_linking.patch to inject runtime_library_search_directories, soname (ELF), and set_install_name (macOS) into hermetic_cc_toolchain, allowing dynamically linked binaries and tests to find shared libraries at runtime without workarounds. - Update patches/rules_rust_cdylib_windows.patch to include cdylib artifacts in runfiles so dependent binaries receive transitive dynamic libraries in their runfiles tree. - Remove workarounds from cc/BUILD.bazel: strip linkstatic=True, data overrides, LD_LIBRARY_PATH/DYLD_LIBRARY_PATH, and manual -Wl,-rpath flags. --- MODULE.bazel | 2 +- cc/BUILD.bazel | 47 ---------- patches/BUILD.bazel | 1 + patches/hermetic_cc_toolchain_darwin.patch | 11 --- ...ermetic_cc_toolchain_dynamic_linking.patch | 85 +++++++++++++++++++ patches/rules_rust_cdylib_windows.patch | 60 +++++++++---- 6 files changed, 132 insertions(+), 74 deletions(-) delete mode 100644 patches/hermetic_cc_toolchain_darwin.patch create mode 100644 patches/hermetic_cc_toolchain_dynamic_linking.patch diff --git a/MODULE.bazel b/MODULE.bazel index b9d5320..77a1935 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -80,7 +80,7 @@ single_version_override( module_name = "hermetic_cc_toolchain", patch_strip = 1, patches = [ - "//patches:hermetic_cc_toolchain_darwin.patch", + "//patches:hermetic_cc_toolchain_dynamic_linking.patch", ], ) diff --git a/cc/BUILD.bazel b/cc/BUILD.bazel index f6d2e22..32e9ac0 100644 --- a/cc/BUILD.bazel +++ b/cc/BUILD.bazel @@ -8,7 +8,6 @@ cc_library( "-fno-exceptions", "-fno-rtti", ], - linkstatic = True, visibility = ["//visibility:public"], ) @@ -16,7 +15,6 @@ cc_library( name = "rust_calculator", srcs = ["rust_calculator.cc"], hdrs = ["rust_calculator.hh"], - linkstatic = True, visibility = ["//visibility:public"], deps = ["//rs:rust_calculator"], ) @@ -24,80 +22,35 @@ cc_library( cc_binary( name = "main", srcs = ["main.cc"], - data = ["//rs:rust_calculator"], env = select({ "@platforms//os:windows": { "PATH": "rs;.", }, - "@platforms//os:linux": { - "LD_LIBRARY_PATH": "rs:.", - }, - "@platforms//os:macos": { - "DYLD_LIBRARY_PATH": "rs:.", - }, "//conditions:default": {}, }), - linkopts = select({ - "@platforms//os:linux": [ - "-Wl,-rpath,$$ORIGIN/../rs", - "-Wl,-rpath,$$ORIGIN/rs", - "-Wl,-rpath,$$ORIGIN", - ], - "@platforms//os:macos": [ - "-Wl,-rpath,@loader_path/../rs", - "-Wl,-rpath,@loader_path/rs", - "-Wl,-rpath,@loader_path", - ], - "//conditions:default": [], - }), - linkstatic = True, visibility = ["//visibility:public"], deps = [ ":calculator", ":rust_calculator", - "//rs:rust_calculator", ], ) cc_test( name = "calculator_test", srcs = ["calculator_test.cc"], - linkstatic = True, deps = [":calculator"], ) cc_test( name = "rust_calculator_test", srcs = ["rust_calculator_test.cc"], - data = ["//rs:rust_calculator"], env = select({ "@platforms//os:windows": { "PATH": "rs;.", }, - "@platforms//os:linux": { - "LD_LIBRARY_PATH": "rs:.", - }, - "@platforms//os:macos": { - "DYLD_LIBRARY_PATH": "rs:.", - }, "//conditions:default": {}, }), - linkopts = select({ - "@platforms//os:linux": [ - "-Wl,-rpath,$$ORIGIN/../rs", - "-Wl,-rpath,$$ORIGIN/rs", - "-Wl,-rpath,$$ORIGIN", - ], - "@platforms//os:macos": [ - "-Wl,-rpath,@loader_path/../rs", - "-Wl,-rpath,@loader_path/rs", - "-Wl,-rpath,@loader_path", - ], - "//conditions:default": [], - }), - linkstatic = True, deps = [ ":rust_calculator", - "//rs:rust_calculator", ], ) diff --git a/patches/BUILD.bazel b/patches/BUILD.bazel index eedaab5..2b9ea9f 100644 --- a/patches/BUILD.bazel +++ b/patches/BUILD.bazel @@ -1,4 +1,5 @@ exports_files([ + "hermetic_cc_toolchain_dynamic_linking.patch", "rules_rust_cdylib_windows.patch", "rules_rust_windows_gnu.patch", ]) diff --git a/patches/hermetic_cc_toolchain_darwin.patch b/patches/hermetic_cc_toolchain_darwin.patch deleted file mode 100644 index 9956781..0000000 --- a/patches/hermetic_cc_toolchain_darwin.patch +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/toolchain/toolchain/defs.bzl b/toolchain/toolchain/defs.bzl ---- a/toolchain/toolchain/defs.bzl -+++ b/toolchain/toolchain/defs.bzl -@@ -4,3 +4,7 @@ def declare_toolchains(configs = "", extra_target_settings = []): - for target_config in target_structs(): -+ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain -+ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. -+ if target_config.libc == "darwin": -+ continue - gotarget = target_config.gotarget - zigtarget = target_config.zigtarget diff --git a/patches/hermetic_cc_toolchain_dynamic_linking.patch b/patches/hermetic_cc_toolchain_dynamic_linking.patch new file mode 100644 index 0000000..194ee9a --- /dev/null +++ b/patches/hermetic_cc_toolchain_dynamic_linking.patch @@ -0,0 +1,85 @@ +diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl +index 72fa0c2..b010b08 100644 +--- a/toolchain/zig_cc_toolchain.bzl ++++ b/toolchain/zig_cc_toolchain.bzl +@@ -161,12 +161,79 @@ def _zig_cc_toolchain_config_impl(ctx): + ], + ) + ++ dynamic_linking_features = [] ++ if ctx.attr.supports_dynamic_linker: ++ is_macos = "macos" in ctx.attr.target ++ rpath_prefix = "@loader_path" if is_macos else "$ORIGIN" ++ dynamic_linking_features.append( ++ feature( ++ name = "runtime_library_search_directories", ++ flag_sets = [ ++ flag_set( ++ actions = all_link_actions, ++ flag_groups = [ ++ flag_group( ++ iterate_over = "runtime_library_search_directories", ++ flag_groups = [ ++ flag_group( ++ flags = [ ++ "-Xlinker", ++ "-rpath", ++ "-Xlinker", ++ rpath_prefix + "/%{runtime_library_search_directories}", ++ ], ++ ), ++ ], ++ expand_if_available = "runtime_library_search_directories", ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ if is_macos: ++ dynamic_linking_features.append( ++ feature( ++ name = "set_install_name", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = dynamic_library_link_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "runtime_solib_name", ++ flags = ["-Wl,-install_name,@rpath/%{runtime_solib_name}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ else: ++ dynamic_linking_features.append( ++ feature( ++ name = "soname", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = dynamic_library_link_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "runtime_solib_name", ++ flags = ["-Wl,-soname,%{runtime_solib_name}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ + features = [ + compile_and_link_flags, + default_linker_flags, + supports_dynamic_linker, + strip_debug_symbols_feature, +- ] + _compilation_mode_features(ctx) ++ ] + dynamic_linking_features + _compilation_mode_features(ctx) + + artifact_name_patterns = [ + artifact_name_pattern(**json.decode(p)) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch index e3b0462..b31bd20 100644 --- a/patches/rules_rust_cdylib_windows.patch +++ b/patches/rules_rust_cdylib_windows.patch @@ -1,20 +1,23 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl +index 72d776f..344b4e1 100644 --- a/rust/private/rustc.bzl +++ b/rust/private/rustc.bzl -@@ -1476,8 +1476,40 @@ +@@ -1473,10 +1473,41 @@ def construct_arguments( + include_link_flags = include_link_flags, + ) + - # On macOS, set the dylib install name to @rpath/ so that -- # consumers find it via RPATH rather than the exec-root build path. ++ # On macOS, set the dylib/cdylib install name to @rpath/ so that + # consumers find it via RPATH rather than the exec-root build path. - if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: - rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) -+ # On macOS, set the dylib/cdylib install name to @rpath/ so that -+ # consumers find it via RPATH rather than the exec-root build path. + if crate_info.type in ("cdylib", "dylib") and toolchain.target_os in ["macos", "darwin"]: + if ld_is_direct_driver: + rustc_flags.add("--codegen=link-arg=-install_name") + rustc_flags.add("--codegen=link-arg=@rpath/" + crate_info.output.basename) + else: + rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) - ++ + # On ELF platforms, set the DT_SONAME so that downstream linkers + # record the soname rather than the exec-root solib path. + if ( @@ -41,11 +44,10 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl + rustc_flags.add("--codegen=link-arg=--entry=_DllMainCRTStartup@12") + else: + rustc_flags.add("--codegen=link-arg=--entry=DllMainCRTStartup") -+ + use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects) - # These always need to be added, even if not linking this crate. -@@ -2010,9 +2037,14 @@ +@@ -2010,9 +2041,14 @@ def rustc_compile_action( # interface library that rustc generates in the output files. interface_library = None if toolchain.target_os == "windows" and crate_info.type == "cdylib": @@ -63,21 +65,47 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl outputs.append(interface_library) # The action might generate extra output that we don't want to include in the `DefaultInfo` files. -@@ -2572,8 +2604,12 @@ +@@ -2206,7 +2242,7 @@ def rustc_compile_action( + files = getattr(ctx.files, "data", []) + + ([] if experimental_use_coverage_metadata_files else coverage_runfiles) + + # Include any generated Rust ABI dylibs as required runfiles. +- ([crate_info.output] if crate_info.type == "dylib" else []) + ++ ([crate_info.output] if crate_info.type in ("dylib", "cdylib") else []) + + # Include the stdlib dylib when dynamically linking the standard library. + ([toolchain.rust_std_dylib] if link_std_dylib and toolchain.rust_std_dylib else []), + ) +@@ -2572,9 +2608,13 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co linking_context = linking_context, debug_context = debug_context, ), - toolchain.stdlib_linkflags, ] -+ + + # A cdylib is already linked against the Rust standard library, so its + # stdlib link flags do not need to propagate to downstream link actions. + if crate_info.type != "cdylib": + cc_infos.append(toolchain.stdlib_linkflags) - ++ # Flattening is okay since crate_info.deps only records direct deps. for dep in crate_info.deps.to_list(): -@@ -3019,6 +3055,7 @@ + if dep.cc_info: +@@ -2972,6 +3012,7 @@ def _make_link_flags_windows(make_link_flags_args, flavor_msvc, use_direct_drive + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + if flavor_msvc: +@@ -3004,6 +3045,7 @@ def _make_link_flags_darwin(make_link_flags_args, use_direct_driver): + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + ret.extend([ +@@ -3019,6 +3061,7 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args ret = [] prefix = "" if use_direct_driver else "-Wl," @@ -85,7 +113,7 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl for lib in linker_input.libraries: if lib.alwayslink: ret.extend([ -@@ -3027,7 +3064,19 @@ +@@ -3027,7 +3070,19 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): ("-Clink-arg=%s--no-whole-archive" % prefix), ]) elif include_link_flags: @@ -107,9 +135,10 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl return ret diff --git a/test/unit/cc_info/cc_info_test.bzl b/test/unit/cc_info/cc_info_test.bzl +index 3530a48..aebedbf 100644 --- a/test/unit/cc_info/cc_info_test.bzl +++ b/test/unit/cc_info/cc_info_test.bzl -@@ -98,7 +98,7 @@ +@@ -98,7 +98,7 @@ def _proc_macro_does_not_provide_cc_info_test_impl(ctx): def _cdylib_provides_cc_info_test_impl(ctx): env = analysistest.begin(ctx) tut = analysistest.target_under_test(env) @@ -119,9 +148,10 @@ diff --git a/test/unit/cc_info/cc_info_test.bzl b/test/unit/cc_info/cc_info_test def _staticlib_provides_cc_info_test_impl(ctx): diff --git a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +index 016d4d2..aaff9df 100644 --- a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +++ b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl -@@ -12,10 +12,11 @@ +@@ -12,10 +12,11 @@ def _win_interface_library_test_impl(ctx): files = target[DefaultInfo].files.to_list() cc_library = target[CcInfo].linking_context.linker_inputs.to_list()[0].libraries[0] From 4e9dae36af5044ca2050430d2de2318f285782fb Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:35:14 -0700 Subject: [PATCH 15/19] fix(toolchain): align solib symlink with soname for cdylib and restore macos clang bypass - Set dynamic_library_symlink_path to crate_info.output.basename in rules_rust cdylib create_library_to_link, ensuring the solib symlink in _solib_ matches the DT_SONAME embedded by rustc so dynamic linkers can locate the shared library at runtime. - Combine hermetic_cc_toolchain patches into patches/hermetic_cc_toolchain.patch: includes runtime_library_search_directories, soname, and restores the macOS Darwin libc bypass so native Apple Clang is used on macOS runners. --- MODULE.bazel | 2 +- patches/BUILD.bazel | 2 +- ...king.patch => hermetic_cc_toolchain.patch} | 26 +++++++++++++++++++ patches/rules_rust_cdylib_windows.patch | 20 +++++++++----- 4 files changed, 42 insertions(+), 8 deletions(-) rename patches/{hermetic_cc_toolchain_dynamic_linking.patch => hermetic_cc_toolchain.patch} (73%) diff --git a/MODULE.bazel b/MODULE.bazel index 77a1935..50896ef 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -80,7 +80,7 @@ single_version_override( module_name = "hermetic_cc_toolchain", patch_strip = 1, patches = [ - "//patches:hermetic_cc_toolchain_dynamic_linking.patch", + "//patches:hermetic_cc_toolchain.patch", ], ) diff --git a/patches/BUILD.bazel b/patches/BUILD.bazel index 2b9ea9f..6cc0f8c 100644 --- a/patches/BUILD.bazel +++ b/patches/BUILD.bazel @@ -1,5 +1,5 @@ exports_files([ - "hermetic_cc_toolchain_dynamic_linking.patch", + "hermetic_cc_toolchain.patch", "rules_rust_cdylib_windows.patch", "rules_rust_windows_gnu.patch", ]) diff --git a/patches/hermetic_cc_toolchain_dynamic_linking.patch b/patches/hermetic_cc_toolchain.patch similarity index 73% rename from patches/hermetic_cc_toolchain_dynamic_linking.patch rename to patches/hermetic_cc_toolchain.patch index 194ee9a..713306c 100644 --- a/patches/hermetic_cc_toolchain_dynamic_linking.patch +++ b/patches/hermetic_cc_toolchain.patch @@ -1,3 +1,29 @@ +diff --git a/toolchain/toolchain/defs.bzl b/toolchain/toolchain/defs.bzl +index 73cf613..9fee7da 100644 +--- a/toolchain/toolchain/defs.bzl ++++ b/toolchain/toolchain/defs.bzl +@@ -2,6 +2,10 @@ load("@hermetic_cc_toolchain//toolchain/private:defs.bzl", "target_structs") + + def declare_toolchains(configs = "", extra_target_settings = []): + for target_config in target_structs(): ++ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain ++ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. ++ if target_config.libc == "darwin": ++ continue + gotarget = target_config.gotarget + zigtarget = target_config.zigtarget + +@@ -18,6 +22,10 @@ def declare_toolchains(configs = "", extra_target_settings = []): + + def declare_libc_aware_toolchains(configs = "", extra_target_settings = []): + for target_config in target_structs(): ++ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain ++ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. ++ if target_config.libc == "darwin": ++ continue + gotarget = target_config.gotarget + zigtarget = target_config.zigtarget + diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl index 72fa0c2..b010b08 100644 --- a/toolchain/zig_cc_toolchain.bzl diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch index b31bd20..a88ced8 100644 --- a/patches/rules_rust_cdylib_windows.patch +++ b/patches/rules_rust_cdylib_windows.patch @@ -1,5 +1,5 @@ diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl -index 72d776f..344b4e1 100644 +index 72d776f..0dc0323 100644 --- a/rust/private/rustc.bzl +++ b/rust/private/rustc.bzl @@ -1473,10 +1473,41 @@ def construct_arguments( @@ -74,7 +74,15 @@ index 72d776f..344b4e1 100644 # Include the stdlib dylib when dynamically linking the standard library. ([toolchain.rust_std_dylib] if link_std_dylib and toolchain.rust_std_dylib else []), ) -@@ -2572,9 +2608,13 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co +@@ -2544,6 +2580,7 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co + feature_configuration = feature_configuration, + cc_toolchain = cc_toolchain, + dynamic_library = crate_info.output, ++ dynamic_library_symlink_path = crate_info.output.basename, + interface_library = interface_library, + ) + elif crate_info.type == "dylib": +@@ -2572,9 +2609,13 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co linking_context = linking_context, debug_context = debug_context, ), @@ -89,7 +97,7 @@ index 72d776f..344b4e1 100644 # Flattening is okay since crate_info.deps only records direct deps. for dep in crate_info.deps.to_list(): if dep.cc_info: -@@ -2972,6 +3012,7 @@ def _make_link_flags_windows(make_link_flags_args, flavor_msvc, use_direct_drive +@@ -2972,6 +3013,7 @@ def _make_link_flags_windows(make_link_flags_args, flavor_msvc, use_direct_drive linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args ret = [] prefix = "" if use_direct_driver else "-Wl," @@ -97,7 +105,7 @@ index 72d776f..344b4e1 100644 for lib in linker_input.libraries: if lib.alwayslink: if flavor_msvc: -@@ -3004,6 +3045,7 @@ def _make_link_flags_darwin(make_link_flags_args, use_direct_driver): +@@ -3004,6 +3046,7 @@ def _make_link_flags_darwin(make_link_flags_args, use_direct_driver): linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args ret = [] prefix = "" if use_direct_driver else "-Wl," @@ -105,7 +113,7 @@ index 72d776f..344b4e1 100644 for lib in linker_input.libraries: if lib.alwayslink: ret.extend([ -@@ -3019,6 +3061,7 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): +@@ -3019,6 +3062,7 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args ret = [] prefix = "" if use_direct_driver else "-Wl," @@ -113,7 +121,7 @@ index 72d776f..344b4e1 100644 for lib in linker_input.libraries: if lib.alwayslink: ret.extend([ -@@ -3027,7 +3070,19 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): +@@ -3027,7 +3071,19 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): ("-Clink-arg=%s--no-whole-archive" % prefix), ]) elif include_link_flags: From bded37c2cd9d29cecd95dde3f47e78ba6ad000dd Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:42:52 -0700 Subject: [PATCH 16/19] fix(toolchain): pass -Wl,-no-as-needed on Linux in hermetic_cc_toolchain --- patches/hermetic_cc_toolchain.patch | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/patches/hermetic_cc_toolchain.patch b/patches/hermetic_cc_toolchain.patch index 713306c..8c46de0 100644 --- a/patches/hermetic_cc_toolchain.patch +++ b/patches/hermetic_cc_toolchain.patch @@ -25,10 +25,10 @@ index 73cf613..9fee7da 100644 zigtarget = target_config.zigtarget diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl -index 72fa0c2..b010b08 100644 +index 72fa0c2..4f30389 100644 --- a/toolchain/zig_cc_toolchain.bzl +++ b/toolchain/zig_cc_toolchain.bzl -@@ -161,12 +161,79 @@ def _zig_cc_toolchain_config_impl(ctx): +@@ -161,12 +161,95 @@ def _zig_cc_toolchain_config_impl(ctx): ], ) @@ -98,6 +98,22 @@ index 72fa0c2..b010b08 100644 + ], + ), + ) ++ dynamic_linking_features.append( ++ feature( ++ name = "no_as_needed", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = all_link_actions, ++ flag_groups = [ ++ flag_group( ++ flags = ["-Wl,-no-as-needed"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) + features = [ compile_and_link_flags, From e2195930df9e8cc7703593f0362666430ff3c813 Mon Sep 17 00:00:00 2001 From: justhecuke <70684719+justhecuke@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:48:27 -0700 Subject: [PATCH 17/19] fix(toolchain): use double dash --no-as-needed for zig cc --- patches/hermetic_cc_toolchain.patch | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/patches/hermetic_cc_toolchain.patch b/patches/hermetic_cc_toolchain.patch index 8c46de0..b512d5d 100644 --- a/patches/hermetic_cc_toolchain.patch +++ b/patches/hermetic_cc_toolchain.patch @@ -25,7 +25,7 @@ index 73cf613..9fee7da 100644 zigtarget = target_config.zigtarget diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl -index 72fa0c2..4f30389 100644 +index 72fa0c2..ed9b9f8 100644 --- a/toolchain/zig_cc_toolchain.bzl +++ b/toolchain/zig_cc_toolchain.bzl @@ -161,12 +161,95 @@ def _zig_cc_toolchain_config_impl(ctx): @@ -107,7 +107,7 @@ index 72fa0c2..4f30389 100644 + actions = all_link_actions, + flag_groups = [ + flag_group( -+ flags = ["-Wl,-no-as-needed"], ++ flags = ["-Wl,--no-as-needed"], + ), + ], + ), From f5f42c773c6ac16eb60c00780966a214121b3bb7 Mon Sep 17 00:00:00 2001 From: Justin Wei Date: Fri, 27 Nov 2026 11:47:29 -0600 Subject: [PATCH 18/19] fix(toolchain): emit -Wl,--no-as-needed before libraries_to_link on Linux --- patches/hermetic_cc_toolchain.patch | 156 +++++++++++++++++++++++++++- 1 file changed, 153 insertions(+), 3 deletions(-) diff --git a/patches/hermetic_cc_toolchain.patch b/patches/hermetic_cc_toolchain.patch index b512d5d..d134b56 100644 --- a/patches/hermetic_cc_toolchain.patch +++ b/patches/hermetic_cc_toolchain.patch @@ -25,10 +25,18 @@ index 73cf613..9fee7da 100644 zigtarget = target_config.zigtarget diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl -index 72fa0c2..ed9b9f8 100644 +index 72fa0c2..a1b2c3d 100644 --- a/toolchain/zig_cc_toolchain.bzl +++ b/toolchain/zig_cc_toolchain.bzl -@@ -161,12 +161,95 @@ def _zig_cc_toolchain_config_impl(ctx): +@@ -8,6 +8,7 @@ load( + "flag_set", + "tool", + "tool_path", ++ "variable_with_value", + ) + load("@rules_cc//cc/common:cc_common.bzl", "cc_common") + load("@rules_cc//cc/toolchains:cc_toolchain_config_info.bzl", "CcToolchainConfigInfo") +@@ -161,12 +162,237 @@ def _zig_cc_toolchain_config_impl(ctx): ], ) @@ -81,6 +89,11 @@ index 72fa0c2..ed9b9f8 100644 + ), + ) + else: ++ link_and_lto_actions = all_link_actions + [ ++ ACTION_NAMES.lto_index_for_dynamic_library, ++ ACTION_NAMES.lto_index_for_executable, ++ ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ++ ] + dynamic_linking_features.append( + feature( + name = "soname", @@ -98,13 +111,19 @@ index 72fa0c2..ed9b9f8 100644 + ], + ), + ) ++ # Zig CC passes --as-needed by default on Linux, which drops shared ++ # libraries that are only referenced transitively by another shared ++ # library (standard in Bazel's dynamic cc_library linking model). ++ # Define libraries_to_link, user_link_flags, and legacy_link_flags ++ # immediately after no_as_needed so -Wl,--no-as-needed precedes all ++ # -l inputs (rules_cc otherwise prepends legacy features first). + dynamic_linking_features.append( + feature( + name = "no_as_needed", + enabled = True, + flag_sets = [ + flag_set( -+ actions = all_link_actions, ++ actions = link_and_lto_actions, + flag_groups = [ + flag_group( + flags = ["-Wl,--no-as-needed"], @@ -114,6 +133,137 @@ index 72fa0c2..ed9b9f8 100644 + ], + ), + ) ++ dynamic_linking_features.append( ++ feature( ++ name = "libraries_to_link", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_true = "thinlto_param_file", ++ flags = ["-Wl,@%{thinlto_param_file}"], ++ ), ++ flag_group( ++ expand_if_available = "libraries_to_link", ++ iterate_over = "libraries_to_link", ++ flag_groups = [ ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ expand_if_false = "libraries_to_link.is_whole_archive", ++ flags = ["-Wl,--start-lib"], ++ ), ++ flag_group( ++ expand_if_true = "libraries_to_link.is_whole_archive", ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["-Wl,-whole-archive"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ iterate_over = "libraries_to_link.object_files", ++ flags = ["%{libraries_to_link.object_files}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "interface_library", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "dynamic_library", ++ ), ++ flags = ["-l%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "versioned_dynamic_library", ++ ), ++ flags = ["-l:%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_true = "libraries_to_link.is_whole_archive", ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["-Wl,-no-whole-archive"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ expand_if_false = "libraries_to_link.is_whole_archive", ++ flags = ["-Wl,--end-lib"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ dynamic_linking_features.append( ++ feature( ++ name = "user_link_flags", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "user_link_flags", ++ iterate_over = "user_link_flags", ++ flags = ["%{user_link_flags}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ dynamic_linking_features.append( ++ feature( ++ name = "legacy_link_flags", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "legacy_link_flags", ++ iterate_over = "legacy_link_flags", ++ flags = ["%{legacy_link_flags}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) + features = [ compile_and_link_flags, From f065c831e0af5cfd1e097924eefdc6a452d75af3 Mon Sep 17 00:00:00 2001 From: Justin Wei Date: Fri, 27 Nov 2026 11:58:44 -0600 Subject: [PATCH 19/19] build(linux): set --dynamic_mode=off to prevent duplicate static libc++abi across cc_library .so boundaries --- .bazelrc | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.bazelrc b/.bazelrc index 0175683..405e5e1 100644 --- a/.bazelrc +++ b/.bazelrc @@ -24,6 +24,14 @@ build:windows --nolegacy_external_runfiles # hermetic x86_64-pc-windows-gnu toolchain instead of the C++ toolchain wrapper. build:windows --@rules_rust//rust/settings:toolchain_linker_preference=rust +# Linux-specific settings +# Zig CC statically links libc++/libc++abi/libunwind into every shared library, +# duplicating C++ runtime state and breaking exception propagation across +# dynamically linked cc_library (.so) boundaries. Link cc_library targets +# statically while still linking explicit shared libraries (e.g. Rust cdylibs) +# dynamically. +build:linux --dynamic_mode=off + # Linting settings # To run linting: bazel build --config=lint //... build:lint --aspects=//tools:lint.bzl%ruff,@rules_rust//rust:defs.bzl%rust_clippy_aspect,@rules_rust//rust:defs.bzl%rustfmt_aspect