@@ -0,0 +1,865 @@
+# Squash of:
+# https://chromium-review.googlesource.com/c/chromium/src/+/8559360
+# https://chromium-review.googlesource.com/c/chromium/src/+/8560244
+# https://chromium-review.googlesource.com/c/chromium/src/+/8563940
+# https://chromium-review.googlesource.com/c/chromium/src/+/8561424
+# https://chromium-review.googlesource.com/c/chromium/src/+/8564239
+# https://chromium-review.googlesource.com/c/chromium/src/+/8268230
+--- a/build/config/rust.gni
++++ b/build/config/rust.gni
+@@ -63,6 +63,21 @@ declare_args() {
+ # the bindgen exectuable).
+ rust_bindgen_root = "//third_party/rust-toolchain"
+
++ # Directory under which to find Crubit tools and support libraries:
++ # * `bin/cc_bindings_from_rs` and `bin/rs_bindings_from_cc`
++ # * `lib/third_party/crubit` (support libraries and their `BUILD.gn` files)
++ #
++ # Unlike `rust_bindgen_root` we don't set `rust_crubit_root` to
++ # `"//third_party/rust-toolchain"` by default, because `cc_bindings_from_rs`
++ # has to be built from the same Rust compiler sources as `rustc` (see
++ # https://github.com/google/crubit/blob/89417b58802e20a6a11db7fea7c31692fef25276/docs/design/design.md?plain=1#L599-L602).
++ # Because of the above `rust_crubit_root` has to be explicitly set when using
++ # a custom toolchain via `rust_sysroot_absolute`. OTOH, when
++ # `use_chromium_rust_toolchain` is set then defaulting to
++ # `"//third_party/rust-toolchain"` is ok (see the `if (rust_crubit_root...
++ # use_chromium_rust_toolchain` code below).
++ rust_crubit_root = ""
++
+ # If you're using a Rust toolchain as specified by rust_sysroot_absolute,
+ # set this to the output of `rustc -V`. Changing this string will cause all
+ # Rust targets to be rebuilt, which allows you to update your toolchain and
+@@ -150,18 +165,6 @@ if (enable_rust) {
+ _version_lines =
+ read_file("//third_party/rust-toolchain/VERSION", "list lines")
+ rustc_revision = _version_lines[0]
+-
+- # Example:
+- # rustc 1.88.0 c8f94230282a8e8c1148f3e657f0199aad909228 (c8f94230282a8e8c1148f3e657f0199aad909228-1-llvmorg-21-init-9266-g09006611 chromium)
+- # Trim it down as much as we can using GN.
+- rustc_revision = string_replace(rustc_revision, "rustc ", "")
+- rustc_revision = string_replace(rustc_revision, " chromium", "")
+- rustc_revision = string_replace(rustc_revision, "init-", "")
+- rustc_revision = string_replace(rustc_revision, "llvmorg-", "")
+- rustc_revision = string_replace(rustc_revision, " ", "")
+- rustc_revision = string_replace(rustc_revision, ".", "")
+- rustc_revision = string_replace(rustc_revision, "(", "-")
+- rustc_revision = string_replace(rustc_revision, ")", "")
+ }
+
+ # The same as written in `config.toml.template`.
+@@ -170,6 +173,19 @@ if (enable_rust) {
+ toolchain_has_rust = custom_toolchain_supports_platform
+ rustc_revision = rustc_version
+ }
++
++ # Trim down `rustc_revision`. This is partially done for aesthetics and
++ # brevity. But more importantly, removing spaces avoids errors that would
++ # otherwise happen when passing `--cfg cr_rustc_revision=...` in `rustflags`.
++ # See also the `build/config/compiler:rustc_revision` config.
++ rustc_revision = string_replace(rustc_revision, "rustc ", "")
++ rustc_revision = string_replace(rustc_revision, " chromium", "")
++ rustc_revision = string_replace(rustc_revision, "init-", "")
++ rustc_revision = string_replace(rustc_revision, "llvmorg-", "")
++ rustc_revision = string_replace(rustc_revision, " ", "")
++ rustc_revision = string_replace(rustc_revision, ".", "")
++ rustc_revision = string_replace(rustc_revision, "(", "-")
++ rustc_revision = string_replace(rustc_revision, ")", "")
+ }
+
+ # TODO(crbug.com/40809974): To build unit tests for Android we need to build
+@@ -188,6 +204,18 @@ if (enable_rust) {
+ }
+ }
+
++if (rust_crubit_root == "" && use_chromium_rust_toolchain) {
++ rust_crubit_root = "//third_party/rust-toolchain"
++}
++
++# Message for `assert(rust_crubit_root != "", rust_crubit_root_missing_message)`
++# in places that need Crubit.
++rust_crubit_root_missing_message =
++ "Crubit is required, but `rust_crubit_root` GN arg is not set. It has " +
++ "to be set when using a custom Rust toolchain via " +
++ "`rust_sysroot_absolute`. See `rust_crubit_root` in " +
++ "//build/config/rust.gni for more details."
++
+ # Figure out the Rust target triple (aka 'rust_abi_target')
+ #
+ # This is here rather than in the toolchain files because it's used also by
+@@ -415,6 +443,10 @@ if (toolchain_for_rust_host_build_tools)
+ rust_prebuilt_stdlib =
+ !use_chromium_rust_toolchain || toolchain_for_rust_host_build_tools
+
++# `rust_sysroot` is the toolchain root (and the default sysroot of rustc),
++# but the locally built stdlib uses a different sysroot.
++local_rustc_sysroot = "$root_out_dir/local_rustc_sysroot"
++
+ # `cpp_api_from_rust` (aka `cc_bindings_from_rs`) is available when building
+ # Chromium, but may be missing or can't be used in some other cases.
+ # `enable_cpp_api_from_rust` is checked under `//build/rust/*.gni` (and may be
+@@ -422,8 +454,7 @@ rust_prebuilt_stdlib =
+ #
+ # See the `assert` comments in `cpp_api_from_rust.gni` for explanation of
+ # the conditions used here.
+-enable_cpp_api_from_rust = enable_rust && use_chromium_rust_toolchain &&
+- !rust_prebuilt_stdlib && build_with_chromium
++enable_cpp_api_from_rust = enable_rust && build_with_chromium
+
+ declare_args() {
+ # Whether it is okay to use `rust_api_from_cpp.gni`. The default is `false`,
+@@ -432,9 +463,8 @@ declare_args() {
+ # `true` in `args.gn` for local experimentation.
+ #
+ # TODO(crbug.com/40226863): After officially supporting `rust_api_from_cpp`:
+- # * Introduce `_enable_crubit = enable_rust && use_chromium_rust_toolchain &&
+- # build_with_chromium`
+- # * Set `enable_cpp_api_from_rust = _enable_crubit && !rust_prebuilt_stdlib`
++ # * Introduce `_enable_crubit = enable_rust && build_with_chromium`
++ # * Set `enable_cpp_api_from_rust = _enable_crubit`
+ # * Set `enable_rust_api_from_cpp = _enable_crubit`
+ # (and it should just be a variable, not an `args.gn` setting / not in
+ # `declare_args`)
+@@ -452,8 +482,13 @@ rustc_wrapper_inputs = [
+ "//build/rust/gni_impl/rustc_wrapper.py",
+ ]
+
+-if (host_os == "win") {
+- rustc_wrapper_inputs += [ "//third_party/rust-toolchain/bin/rustc.exe" ]
+-} else {
+- rustc_wrapper_inputs += [ "//third_party/rust-toolchain/bin/rustc" ]
++if (enable_rust) {
++ # Path to the `rustc` executable (from either the Chromium toolchain or
++ # from a custom toolchain specified via `rust_sysroot_absolute`).
++ rustc_exe_path = "$rust_sysroot/bin/rustc"
++ if (host_os == "win") {
++ rustc_exe_path += ".exe"
++ }
++
++ rustc_wrapper_inputs += [ rustc_exe_path ]
+ }
+--- a/build/rust/cargo_crate.gni
++++ b/build/rust/cargo_crate.gni
+@@ -479,14 +479,9 @@ template("cargo_crate") {
+ "//build/gn_helpers.py",
+ _rustflags_txt,
+ rustc_print_cfg_path,
++ rustc_exe_path,
+ ]
+
+- if (host_os == "win") {
+- inputs += [ "//third_party/rust-toolchain/bin/rustc.exe" ]
+- } else {
+- inputs += [ "//third_party/rust-toolchain/bin/rustc" ]
+- }
+-
+ build_script_target = ":${_build_script_name}($rust_macro_toolchain)"
+ deps = [
+ ":${_build_script_name}_write_rustflags",
+--- a/build/rust/crubit/BUILD.gn
++++ b/build/rust/crubit/BUILD.gn
+@@ -10,9 +10,7 @@ group("crubit") {
+ public_deps = [
+ "$crubit_src_dir/support:support_cpp",
+ "$crubit_src_dir/support/rs_std:rs_std_cpp",
+- "//build/rust/std/rules:alloc_bindings",
+- "//build/rust/std/rules:core_bindings",
+- "//build/rust/std/rules:std_bindings",
++ "//build/rust/std:std_bindings",
+ ]
+ }
+
+@@ -22,7 +20,7 @@ config("public_config") {
+ # `include_dirs` below help ensure that Chromium can use the same
+ # `#include` paths as other Crubit clients like google3 - e.g.
+ # `#include "third_party/crubit/support/rs_std/slice_ref.h"`.
+- include_dirs = [ "//third_party/rust-toolchain/lib" ]
++ include_dirs = [ "${rust_crubit_root}/lib" ]
+ }
+
+ # The `cref` crate provides `CRef<T>` and `CMut<T>` - Rust types that represent
+--- a/build/rust/gni_impl/cpp_api_from_rust.gni
++++ b/build/rust/gni_impl/cpp_api_from_rust.gni
+@@ -27,15 +27,22 @@ _globally_enabled_crubit_features = [
+ # rust_target
+ # Label of the Rust library to generate the bindings for.
+ #
+-# rustc_env_and_flags
++# rustc_env_and_flags (optional)
+ # Path to the `.rustflags.json` file generated by an earlier invocation
+ # of `rustc`. (`cpp_api_from_rust` needs to be invoked with the same
+-# arguments, target platform, etc. as `rust_target`.)
++# `-L` and `--extern` flags as `rust_target`.) Omitted for crates that
++# `rustc` can find on its own (e.g. crates from a prebuilt Rust standard
++# library in the sysroot).
+ #
+ # crate_name
+ # Name (potentially mangled/auto-generated) of the crate that `rust_target`
+ # is built into.
+ #
++# rmeta_path (optional)
++# Path to the `.rmeta` file produced by `rust_target`. Omitted for crates
++# that `rustc` can find on its own (e.g. crates from a prebuilt Rust
++# standard library in the sysroot).
++#
+ # h_out
+ # Path where the generated `.h` file should be written.
+ #
+@@ -46,24 +53,15 @@ _globally_enabled_crubit_features = [
+ #
+ # sources
+ # deps
+-# Dependencies for compiling `rust_target`.
++# Dependencies for compiling `rust_target`, or files that change together
++# with the `.rmeta` files read by Crubit (and the targets that generate
++# these files). This makes sure that the bindings are re-generated when the
++# `.rmeta` files change (e.g. when the Rust toolchain changes).
+ #
+ #
+ template("cpp_api_from_rust") {
+- # `enable_rust` and `use_chromium_rust_toolchain` enforce that `rustc` and
+- # `cpp_api_from_rust` use the same version of Rust compiler sources - this is
+- # required (e.g. to see the same memory layout of repr-Rusts structs) as
+- # explained in
+- # https://github.com/google/crubit/blob/89417b58802e20a6a11db7fea7c31692fef25276/docs/design/design.md?plain=1#L599-L602
+- assert(enable_rust && use_chromium_rust_toolchain)
+-
+- # TODO(https://crbug.com/549864599): `cpp_api_from_rust`-generated bindings
+- # may depend on C++ bindings of Rust standard library. Currently Chromium is
+- # only able to invoke Crubit in `.rs`-consuming mode (rather than
+- # `.rlib`-consuming mode). Together, these two constraints mean that
+- # `cpp_api_from_rust` only works for the target platform and doesn't yet work
+- # for the host platform.
+- assert(!rust_prebuilt_stdlib)
++ assert(enable_rust)
++ assert(rust_crubit_root != "", rust_crubit_root_missing_message)
+
+ # PDFium, V8 and other "2nd-party" Chromium projects don't yet have their own
+ # `//build_overrides/crubit.gni` build file. Until this is fixed, we assert
+@@ -76,16 +74,15 @@ template("cpp_api_from_rust") {
+ _h_target_name = target_name
+ _metadata_target_name = "${target_name}_crubit_metadata"
+
++ assert(defined(invoker.rustc_env_and_flags) == defined(invoker.rmeta_path))
+ assert(defined(invoker.deps))
+ assert(defined(invoker.sources))
+- assert(defined(invoker.rustc_env_and_flags))
+ assert(defined(invoker.rust_target))
+ assert(defined(invoker.original_attributes))
+ assert(defined(invoker.crate_name))
+ assert(defined(invoker.h_out))
+ _crate_name = invoker.crate_name
+ _rust_target = invoker.rust_target
+- _rust_target_name = get_label_info(_rust_target, "name")
+ _rust_target_dir = get_label_info(_rust_target, "dir")
+ _h_out = invoker.h_out
+ _rs_out = "${_h_out}.impl.rs"
+@@ -97,7 +94,8 @@ template("cpp_api_from_rust") {
+ if (!defined(_original_attributes.deps)) {
+ _original_attributes.deps = []
+ }
+- _is_rust_stdlib_target = _rust_target_dir == "//build/rust/std/rules"
++ _is_rust_stdlib_target = _rust_target_dir == "//build/rust/std/rules" ||
++ _rust_target_dir == "//build/rust/std"
+ if (!_is_rust_stdlib_target) {
+ _original_attributes.deps += [ "//build/rust/std:std_bindings" ]
+ }
+@@ -154,6 +152,12 @@ template("cpp_api_from_rust") {
+ "testonly",
+ ])
+ deps += [ ":${_rspgen_target_name}" ]
++ if (_is_rust_stdlib_target && !rust_prebuilt_stdlib &&
++ _crate_name != "core") {
++ # The local sysroot must contain the stdlib crates that the synthetic
++ # crate (generated by Crubit) may load implicitly.
++ deps += [ "//build/rust/std/rules:std" ]
++ }
+
+ visibility = [
+ ":$_h_target_name",
+@@ -165,9 +169,10 @@ template("cpp_api_from_rust") {
+ inputs += [
+ _action_rsp_path,
+ cpp_api_from_rust_exe_path,
+- rustfmt_exe_path,
+- rustfmt_config_path,
+ ]
++ if (defined(invoker.rmeta_path)) {
++ inputs += [ invoker.rmeta_path ]
++ }
+ outputs = [
+ _h_out,
+ _rs_out,
+@@ -177,20 +182,35 @@ template("cpp_api_from_rust") {
+ args = [
+ "--cpp-api-from-rust-exe-path",
+ rebase_path(cpp_api_from_rust_exe_path, root_build_dir),
+-
+- "--rustc-env-and-flags",
+- rebase_path(invoker.rustc_env_and_flags, root_build_dir),
+- "@" + rebase_path(_action_rsp_path, root_build_dir),
+ ]
++ if (defined(invoker.rustc_env_and_flags)) {
++ args += [
++ "--rustc-env-and-flags",
++ rebase_path(invoker.rustc_env_and_flags, root_build_dir),
++ ]
++ }
++ args += [ "@" + rebase_path(_action_rsp_path, root_build_dir) ]
++
++ if (rust_prebuilt_stdlib) {
++ _sysroot = rust_sysroot
++ } else {
++ _sysroot = local_rustc_sysroot
++ }
+
+ # `cpp_api_from_rust` flags:
+ args += [
+ "--",
+
+- # TODO(https://gn.issues.chromium.org/490160737): Enable this interface
+- # once we can get paths to rmeta files in GN.
+- "--enable-rmeta-interface=false",
+-
++ "--enable-rmeta-interface=true",
++ "--source-crate-name=${_crate_name}",
++ "--target=${rust_abi_target}",
++ "--sysroot=" + rebase_path(_sysroot, root_build_dir),
++ ]
++ if (defined(invoker.rmeta_path)) {
++ args += [ "--extern=${_crate_name}=" +
++ rebase_path(invoker.rmeta_path, root_build_dir) ]
++ }
++ args += [
+ "--h-out",
+ rebase_path(_h_out, root_build_dir),
+
+@@ -204,13 +224,21 @@ template("cpp_api_from_rust") {
+
+ "--crubit-support-path-format",
+ crubit_support_path_format,
++ ]
++ if (defined(rustfmt_exe_path)) {
++ inputs += [
++ rustfmt_exe_path,
++ rustfmt_config_path,
++ ]
++ args += [
++ "--rustfmt-exe-path",
++ rebase_path(rustfmt_exe_path, root_build_dir),
+
+- "--rustfmt-exe-path",
+- rebase_path(rustfmt_exe_path, root_build_dir),
+-
+- "--rustfmt-config-path",
+- rebase_path(rustfmt_config_path, root_build_dir),
+-
++ "--rustfmt-config-path",
++ rebase_path(rustfmt_config_path, root_build_dir),
++ ]
++ }
++ args += [
+ "--crate-namespace",
+ "self=${_cpp_namespace}",
+ ]
+@@ -261,10 +289,15 @@ template("cpp_api_from_rust") {
+ # of this crate is `_h_target_name`, which only consumes C ABI top-level
+ # entrypoints - this means that the crate name isn't used / doesn't leak
+ # anywhere. And therefore it doesn't matter what kind of mangling we do,
+- # as long as we ensure that it is globally unique.
++ # as long as we ensure that it is globally unique. (Note that
++ # `_rust_target` is not necessarily unique - e.g. with
++ # `use_rmeta_interface`, `//build/rust/std:std` is shared by all the
++ # crates of a prebuilt Rust standard library. This is why
++ # `_h_target_name` is used as `_crate_name_base` below.)
++ _crate_name_base = _h_target_name
+ _crate_name_suffix =
+- string_hash(get_label_info(_rust_target_name, "label_with_toolchain"))
+- crate_name = "${_rust_target_name}_crubit_${_crate_name_suffix}"
++ string_hash(get_label_info(_crate_name_base, "label_with_toolchain"))
++ crate_name = "${_crate_name_base}_crubit_${_crate_name_suffix}"
+ output_name = crate_name
+
+ crate_root = _rs_out
+--- a/build/rust/gni_impl/cpp_api_from_rust_wrapper.py
++++ b/build/rust/gni_impl/cpp_api_from_rust_wrapper.py
+@@ -8,12 +8,12 @@ import argparse
+ import subprocess
+ import pathlib
+ import sys
+-import tempfile
+
+ from rustc_wrapper import (
+ PrepareRustEnvForExecution,
+ LoadRustEnvAndFlags,
+ HandleReturnCode,
++ ExpandNestedRustStyleRspFiles,
+ )
+
+
+@@ -22,27 +22,34 @@ def main():
+ parser.add_argument(
+ '--cpp-api-from-rust-exe-path', required=True, type=pathlib.Path
+ )
+- parser.add_argument(
+- '--rustc-env-and-flags', type=pathlib.Path, required=True
+- )
++ # `--rustc-env-and-flags` is not used when generating bindings for a
++ # prebuilt stdlib in the sysroot.
++ parser.add_argument('--rustc-env-and-flags', type=pathlib.Path)
+ parser.add_argument('args', metavar='ARG', nargs='+')
+ args = parser.parse_args()
+
+- (rustenv, rustflags) = LoadRustEnvAndFlags(args.rustc_env_and_flags)
+- PrepareRustEnvForExecution(rustenv)
+-
+- rustflags = [*args.args, "--", *rustflags]
++ rustenv = None
++ rustflags = []
++ if args.rustc_env_and_flags:
++ (rustenv, rustflags) = LoadRustEnvAndFlags(args.rustc_env_and_flags)
++ PrepareRustEnvForExecution(rustenv)
++
++ expanded_rustflags = ExpandNestedRustStyleRspFiles(rustflags)
++ flag_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
++ flag_parser.add_argument('-L', action='append', default=[])
++ flag_parser.add_argument('--extern', action='append', default=[])
++ known, _ = flag_parser.parse_known_args(expanded_rustflags)
++ crubit_extra_args = [f'-L{x}' for x in known.L]
++ # Crubit requires `CRATE=PATH`. Skip sysroot crates like
++ # `--extern proc_macro`.
++ crubit_extra_args += [f'--extern={x}' for x in known.extern if '=' in x]
+
+- # `cpp_api_from_rust` should not write any files into the build directory
+- # (e.g. into `out/`).
+- assert not [x for x in rustflags if x.startswith("--emit")]
+- assert not [x for x in rustflags if x.startswith("-o")]
+- assert not [x for x in rustflags if x.startswith("--out-dir")]
+- temp_dir = tempfile.TemporaryDirectory()
+- rustflags += ["--out-dir", temp_dir.name]
++ crubit_args = [*args.args, *crubit_extra_args]
+
+ r = subprocess.run(
+- [args.cpp_api_from_rust_exe_path, *rustflags], env=rustenv, check=False
++ [args.cpp_api_from_rust_exe_path, *crubit_args],
++ env=rustenv,
++ check=False,
+ )
+ HandleReturnCode(r)
+ return 0
+--- a/build/rust/gni_impl/crubit_shared_args.gni
++++ b/build/rust/gni_impl/crubit_shared_args.gni
+@@ -5,24 +5,36 @@
+ # This `.gni` file defines constants that are shared / reused across
+ # `cpp_api_from_rust.gni` and `rust_api_from_cpp.gni`.
+
++import("//build/config/rust.gni")
++
+ crubit_support_path_format = "\"third_party/crubit/support/{header}\""
+ rustfmt_config_path = "//.rustfmt.toml"
+
+-_toolchain_bin_path = "//third_party/rust-toolchain/bin"
+-cpp_api_from_rust_exe_path = "${_toolchain_bin_path}/cc_bindings_from_rs"
+-rust_api_from_cpp_exe_path = "${_toolchain_bin_path}/rs_bindings_from_cc"
+-rustfmt_exe_path = "${_toolchain_bin_path}/rustfmt"
++_crubit_bin_path = "${rust_crubit_root}/bin"
++cpp_api_from_rust_exe_path = "${_crubit_bin_path}/cc_bindings_from_rs"
++rust_api_from_cpp_exe_path = "${_crubit_bin_path}/rs_bindings_from_cc"
+ if (host_os == "win") {
+ cpp_api_from_rust_exe_path += ".exe"
+ rust_api_from_cpp_exe_path += ".exe"
+- rustfmt_exe_path += ".exe"
+ }
+
+-# TODO(lukasza): Make this also work on other host platforms. (Possibly
+-# hoisting this Crubit-agnostic functionality into some other, reusable
+-# location elsewhere.)
+-if (host_os == "linux") {
+- clang_format_exe_path = "//buildtools/linux64-format/clang-format"
+-} else if (host_os == "win") {
+- clang_format_exe_path = "//buildtools/win-format/clang-format.exe"
++# Code generated by Crubit is only formatted when using Crubit from
++# //third_party/rust-toolchain. Formatting only makes the generated code easier
++# to read, and the formatting tools may not be available when using a
++# system-provided Crubit. Therefore `rustfmt_exe_path` and
++# `clang_format_exe_path` may be undefined.
++if (rust_crubit_root == "//third_party/rust-toolchain") {
++ rustfmt_exe_path = "//third_party/rust-toolchain/bin/rustfmt"
++ if (host_os == "win") {
++ rustfmt_exe_path += ".exe"
++ }
++
++ # TODO(lukasza): Make this also work on other host platforms. (Possibly
++ # hoisting this Crubit-agnostic functionality into some other, reusable
++ # location elsewhere.)
++ if (host_os == "linux") {
++ clang_format_exe_path = "//buildtools/linux64-format/clang-format"
++ } else if (host_os == "win") {
++ clang_format_exe_path = "//buildtools/win-format/clang-format.exe"
++ }
+ }
+--- a/build/rust/gni_impl/rust_target.gni
++++ b/build/rust/gni_impl/rust_target.gni
+@@ -386,6 +386,34 @@ template("rust_target") {
+ }
+ }
+
++ # `_output_dir` and `_output_name` are equivalents of `{{output_dir}}` and
++ # `{{target_output_name}}` in the toolchain.
++ _output_dir = target_out_dir
++ if (defined(invoker.output_dir) && invoker.output_dir != "") {
++ _output_dir = invoker.output_dir
++ }
++ if (defined(invoker.output_name)) {
++ _output_name = invoker.output_name
++ } else {
++ # Note that file names of libraries must start with the crate name in
++ # order for the compiler to find transitive dependencies in the
++ # directory search paths (since they are not all explicitly specified).
++ #
++ # For bin targets, we expect the target name to be unique, and the name
++ # of the exe should not add magic stuff to it. And bin crates can not be
++ # transitive dependencies.
++ if (invoker.target_type == "executable") {
++ _output_name = _target_name
++ } else {
++ # TODO(danakj): Since the crate name includes the whole path for 1p
++ # libraries, we could move the output_dir to `root_out_dir` here for
++ # them, which would make for shorter file paths. But we need to not
++ # do the same for 3p crates or those with a `crate_name` set
++ # explicitly.
++ _output_name = _crate_name
++ }
++ }
++
+ if (_override_crate_type_as_dylib) {
+ # Building a `--crate-type=dylib` means that `rustc` generates a `.dll` /
+ # `.so` in target-specific subdirectories of the build directory. This
+@@ -404,13 +432,6 @@ template("rust_target") {
+ # of replicating how `...toolchain.gni` calculates the `.so` path in the
+ # `outputs` of `tool("rust_dylib")` (which feels rather fragile).
+ #
+- # `_source_dir` is an equivalent of `{{output_dir}}` in the toolchain.
+- _source_dir = target_out_dir
+- if (defined(invoker.output_dir)) {
+- _source_dir = invoker.output_dir
+- }
+- _source_dir += "/"
+-
+ # `_source_ext` is an equivalent of `{{output_extension}}`
+ _source_ext = shlib_extension
+
+@@ -425,13 +446,11 @@ template("rust_target") {
+ # `_source_prefix` is an equivalent of `output_prefix` in `tool`.
+ _source_prefix = shlib_prefix
+
+- # `_source_name` is an equivalent of `{{target_output_name}}`.
+ assert(defined(invoker.output_name)) # Only tested with `cargo_crate`.
+- _source_name = invoker.output_name
+
+ # `_source_path` is the equivalent of `dllname` in the toolchain.
+- _source_filename = "${_source_prefix}${_source_name}${_source_ext}"
+- _source_path = "${_source_dir}${_source_filename}"
++ _source_filename = "${_source_prefix}${_output_name}${_source_ext}"
++ _source_path = "${_output_dir}/${_source_filename}"
+
+ # `_target_dir` is the equivalent of `default_output_dir` in toolchain.
+ if (defined(invoker.default_shlib_subdir)) {
+@@ -578,6 +597,7 @@ template("rust_target") {
+ "features",
+ "inputs",
+ "no_clippy",
++ "output_name",
+ "public_deps",
+ "rustenv",
+ "rustflags",
+@@ -627,26 +647,7 @@ template("rust_target") {
+
+ sources = _rust_sources
+ inputs = _rust_inputs
+-
+- if (!defined(output_name)) {
+- # Note that file names of libraries must start with the crate name in
+- # order for the compiler to find transitive dependencies in the
+- # directory search paths (since they are not all explicitly specified).
+- #
+- # For bin targets, we expect the target name to be unique, and the name
+- # of the exe should not add magic stuff to it. And bin crates can not be
+- # transitive dependencies.
+- if (invoker.target_type == "executable") {
+- output_name = _target_name
+- } else {
+- # TODO(danakj): Since the crate name includes the whole path for 1p
+- # libraries, we could move the output_dir to `root_out_dir` here for
+- # them, which would make for shorter file paths. But we need to not
+- # do the same for 3p crates or those with a `crate_name` set
+- # explicitly.
+- output_name = _crate_name
+- }
+- }
++ output_name = _output_name
+
+ if (!_allow_unsafe) {
+ configs += [ "//build/rust:forbid_unsafe" ]
+@@ -755,6 +756,12 @@ template("rust_target") {
+ }
+
+ if (_enable_cpp_api_from_rust_for_this_target) {
++ # TODO(https://crbug.com/gn/490160737): If `get_target_outputs` can
++ # support binary targets (unclear) then it should be used here, instead
++ # of replicating how `...toolchain.gni` calculates `rmetaname` in the
++ # `outputs` of `tool("rust_rlib")` (which feels rather fragile).
++ _rmeta_path = "${_output_dir}/lib${_output_name}.rmeta"
++
+ cpp_api_from_rust(_cpp_api_from_rust_target_name) {
+ forward_variables_from(_secondary_rust_compiler_attrs,
+ _SECONDARY_RUST_COMPILER_ATTR_NAMES)
+@@ -762,6 +769,7 @@ template("rust_target") {
+ rustc_env_and_flags = _rustc_env_and_flags
+ original_attributes = _cpp_api_from_rust_attributes
+ crate_name = _crate_name
++ rmeta_path = _rmeta_path
+
+ if (defined(_cpp_api_from_rust_attributes.h_out)) {
+ h_out = _cpp_api_from_rust_attributes.h_out
+@@ -778,5 +786,9 @@ template("rust_target") {
+ }
+ }
+ }
++ if (!_override_crate_type_as_dylib &&
++ !_enable_cpp_api_from_rust_for_this_target) {
++ not_needed([ "_output_dir" ])
++ }
+ }
+ }
+--- a/build/rust/gni_impl/rustc_wrapper.py
++++ b/build/rust/gni_impl/rustc_wrapper.py
+@@ -334,7 +334,7 @@ def _RecommendApplyFixesScript(tool, rus
+ print(f" {os.path.basename(tool)} {rustc_env_and_flags}", file=sys.stderr)
+
+
+-def _ExpandNestedRustStyleRspFiles(rsp_args):
++def ExpandNestedRustStyleRspFiles(rsp_args):
+ # `rustc` doesn't support using `@<file.rsp>` from **inside** `@another.rsp`.
+ # And things like `@cargo_flags.rs` (see build script handling inside
+ # `cargo_crate.gni`) may end up in `rustflags`. And since `rustflags` are
+@@ -411,7 +411,7 @@ def main():
+ remove_lib_suffix_from_extern_args(arg) for arg in rustc_args
+ ]
+ rsp_args = [remove_gn_escaping_from_rsp_args(arg) for arg in rsp_args]
+- rsp_args = _ExpandNestedRustStyleRspFiles(rsp_args)
++ rsp_args = ExpandNestedRustStyleRspFiles(rsp_args)
+ out_rsp = str(args.rsp) + ".rust"
+ with open(out_rsp, 'w') as rspfile:
+ # rustc needs the rsp file to be separated by newlines. Note that GN
+--- a/build/rust/rust_api_from_cpp.gni
++++ b/build/rust/rust_api_from_cpp.gni
+@@ -65,10 +65,8 @@ _globally_enabled_crubit_features = [
+ # targets that generate bindings for types from these other targets.
+ template("rust_api_from_cpp") {
+ assert(enable_rust_api_from_cpp)
+-
+- # At this point `rs_bindings_from_cc` is only distributed with the Chromium
+- # Rust toolchain.
+- assert(enable_rust && use_chromium_rust_toolchain)
++ assert(enable_rust)
++ assert(rust_crubit_root != "", rust_crubit_root_missing_message)
+
+ # PDFium, V8 and other "2nd-party" Chromium projects don't yet have their own
+ # `//build_overrides/crubit.gni` build file. Until this is fixed, we assert
+@@ -254,8 +252,6 @@ template("rust_api_from_cpp") {
+ "//build/rust/gni_impl/filter_clang_args.py",
+ _metadata_path,
+ rust_api_from_cpp_exe_path,
+- rustfmt_exe_path,
+- rustfmt_config_path,
+ ]
+
+ # Public headers are inputs to this action rather than sources,
+@@ -301,10 +297,18 @@ template("rust_api_from_cpp") {
+ "--public_headers=" + string_join(",", _rebased_public_headers),
+ "--target=${_current_lib_target_full_label}",
+ "--crubit_support_path_format=${crubit_support_path_format}",
+- "--rustfmt_exe_path=" + rebase_path(rustfmt_exe_path, root_build_dir),
+- "--rustfmt_config_path=" +
+- rebase_path(rustfmt_config_path, root_build_dir),
+ ]
++ if (defined(rustfmt_exe_path)) {
++ inputs += [
++ rustfmt_exe_path,
++ rustfmt_config_path,
++ ]
++ args += [
++ "--rustfmt_exe_path=" + rebase_path(rustfmt_exe_path, root_build_dir),
++ "--rustfmt_config_path=" +
++ rebase_path(rustfmt_config_path, root_build_dir),
++ ]
++ }
+
+ # TODO(https://crbug.com/40226863): Use
+ # `rust_enable_generated_code_formatting` (see https://crrev.com/c/8494684)
+--- a/build/rust/std/BUILD.gn
++++ b/build/rust/std/BUILD.gn
+@@ -19,6 +19,7 @@ import("//build/config/compiler/compiler
+ import("//build/config/coverage/coverage.gni")
+ import("//build/config/rust.gni")
+ import("//build/config/sanitizers/sanitizers.gni")
++import("//build/rust/gni_impl/cpp_api_from_rust.gni")
+
+ if (toolchain_has_rust) {
+ # List of Rust stdlib rlibs which are present in the official Rust toolchain
+@@ -180,8 +181,6 @@ if (toolchain_has_rust) {
+ sysroot_lib_subdir = "lib/rustlib/$rust_abi_target/lib"
+
+ if (!rust_prebuilt_stdlib) {
+- local_rustc_sysroot = "$root_out_dir/local_rustc_sysroot"
+-
+ # All std targets starting with core build with our sysroot. It starts empty
+ # and is incrementally built. The directory must exist at the start.
+ generated_file("empty_sysroot_for_std_build") {
+@@ -309,11 +308,7 @@ if (toolchain_has_rust) {
+ out_libdir = rebase_path(target_out_dir, root_build_dir)
+ out_depfile = rebase_path(depfile, root_build_dir)
+
+- if (host_os == "win") {
+- inputs = [ "//third_party/rust-toolchain/bin/rustc.exe" ]
+- } else {
+- inputs = [ "//third_party/rust-toolchain/bin/rustc" ]
+- }
++ inputs = [ rustc_exe_path ]
+
+ # For the rustc sysroot we must include even the rlibs we don't pass to
+ # the C++ linker.
+@@ -382,26 +377,19 @@ if (toolchain_has_rust) {
+ visibility = [ ":*" ]
+ }
+
+- config("prebuilt_stdlib_libs") {
+- ldflags = []
+- lib_dir = rebase_path("$prebuilt_rustc_sysroot/$sysroot_lib_subdir",
+- root_build_dir)
+-
+- # We're unable to make these files regular gn dependencies because
+- # they're prebuilt. Instead, we'll pass them in the ldflags. This doesn't
+- # work for all types of build because ldflags propagate differently from
+- # actual dependencies and therefore can end up in different targets from
+- # the remap_alloc.cc above. For example, in a component build, we might
+- # apply the remap_alloc.cc file and these ldlags to shared object A,
+- # while shared object B (that depends upon A) might get only the ldflags
+- # but not remap_alloc.cc, and thus the build will fail. There is
+- # currently no known solution to this for the prebuilt stdlib - this
+- # problem does not apply with configurations where we build the stdlib
+- # ourselves, which is what we'll use in production.
++ # The prebuilt rlibs are not built by GN, so they are passed to the linker
++ # via `libs`. `libs` set on a target (rather than in a config) propagate
++ # to dependents only until the nearest shared library or executable - the
++ # same way as GN dependencies on `//build/rust/allocator` and on other Rust
++ # libraries. This ensures that in a component build the rlibs are linked
++ # only into the shared libraries that contain Rust code (and therefore also
++ # the allocator shims that the rlibs depend on).
++ source_set("prebuilt_stdlib_libs") {
++ libs = []
+ foreach(lib, stdlib_files) {
+- this_file = "$lib_dir/lib$lib.rlib"
+- ldflags += [ this_file ]
++ libs += [ "$prebuilt_rustc_sysroot/$sysroot_lib_subdir/lib$lib.rlib" ]
+ }
++ deps = [ ":prebuilt_rustc_copy_to_sysroot" ]
+ visibility = [ ":*" ]
+ }
+
+@@ -413,11 +401,8 @@ if (toolchain_has_rust) {
+ }
+
+ group("std") {
+- all_dependent_configs = [
+- ":prebuilt_stdlib_libs",
+- ":stdlib_public_dependent_libs",
+- ]
+- deps = [ ":prebuilt_rustc_copy_to_sysroot" ]
++ all_dependent_configs = [ ":stdlib_public_dependent_libs" ]
++ deps = [ ":prebuilt_stdlib_libs" ]
+ }
+
+ # `stdlib_test_files` are already included in `all_stdlibs_to_copy` and
+@@ -425,5 +410,65 @@ if (toolchain_has_rust) {
+ group("test_support") {
+ deps = [ ":std" ]
+ }
++
++ if (enable_cpp_api_from_rust) {
++ # C++ bindings of the prebuilt Rust standard library. The in-tree stdlib
++ # build generates the bindings from the stdlib sources (see
++ # `//build/rust/std/rules`), but here Crubit reads the crate metadata
++ # from the `.rmeta` files in the sysroot.
++ _prebuilt_stdlib_bindings = [
++ {
++ crate_name = "core"
++ deps = []
++ },
++ {
++ crate_name = "alloc"
++ deps = [ ":prebuilt_core_bindings" ]
++ },
++ {
++ crate_name = "std"
++ deps = [
++ ":prebuilt_alloc_bindings",
++ ":prebuilt_core_bindings",
++ ]
++ },
++ ]
++ foreach(_bindings, _prebuilt_stdlib_bindings) {
++ cpp_api_from_rust("prebuilt_${_bindings.crate_name}_bindings") {
++ rust_target = ":std"
++ crate_name = _bindings.crate_name
++ h_out = "$root_gen_dir/third_party/crubit/support/rs_std/" +
++ "rs_${_bindings.crate_name}.h"
++ original_attributes = {
++ cpp_namespace = "rs::${_bindings.crate_name}"
++ deps = _bindings.deps
++ }
++
++ # Crubit reads the `.rmeta` files from `rust_sysroot`. The copies
++ # made by `:find_stdlib` change together with these files.
++ sources = get_target_outputs(":find_stdlib")
++ deps = [ ":find_stdlib" ]
++
++ visibility = [ ":*" ]
++ }
++ }
++
++ group("std_bindings") {
++ deps = [ ":std" ]
++ public_deps = [
++ ":prebuilt_alloc_bindings",
++ ":prebuilt_core_bindings",
++ ":prebuilt_std_bindings",
++ ]
++ }
++
++ group("std_bindings_crubit_metadata") {
++ public_deps = [
++ ":prebuilt_alloc_bindings_crubit_metadata",
++ ":prebuilt_core_bindings_crubit_metadata",
++ ":prebuilt_std_bindings_crubit_metadata",
++ ]
++ }
++ }
+ }
+ }
+--- a/build_overrides/crubit.gni
++++ b/build_overrides/crubit.gni
+@@ -2,7 +2,11 @@
+ # Use of this source code is governed by a BSD-style license that can be
+ # found in the LICENSE file.
+
+-crubit_src_dir = "//third_party/rust-toolchain/lib/third_party/crubit"
++import("//build/config/rust.gni")
++
++assert(rust_crubit_root != "", rust_crubit_root_missing_message)
++
++crubit_src_dir = "${rust_crubit_root}/lib/third_party/crubit"
+ crubit_absl_dep_target = "//third_party/abseil-cpp:absl"
+ crubit_gn_configs_to_remove = [
+ "//build/config/compiler:chromium_code",