Repository navigation
Add support for -Zembed-metadata - #15378
Conversation
|
I have already discussed this before with Ed, so: r? @epage |
|
One of the concerns we had about this is how cargo sometimes "uplifts" rlibs to the output directory. I'm not really sure that's a good thing that cargo does it, but it is some historical baggage that we carry. If I understand correctly with this, those rlibs would not be usable. I think that's something we'll probably need to examine on what the best path forward would be. |
The uplifted copy alone already wouldn't be usable if the rlib has any dependencies. |
I believe there are some users who use |
That should be fine. As long as the .rmeta file is next to the .rlib file in the deps directory (which it should, as Cargo AFAIK always passes |
|
Try this: |
|
When you use We could uplift also the |
|
We were wondering if it would be possible to avoid using |
|
That should be possible, I can take a look. I would like to understand the concern better though. Suppose that we make it so that both the .rlib and .rmeta files are uplifted, and any previous manual rustc invocations still work (even if you don't pass |
|
The concern is that if someone is using Uplifting the We also have uncertainty about how much this use case should really be supported. To what degree of breakage would we be willing to do? If it looks like it will be complicated to detect if something is uplifted, then I think I would be fine with just including the |
The way I see it, the contents of the
I think that it shouldn't be that complicated, we could not apply the optimization to the roots. However, this will remove the disk savings effect for dylibs (one of the two motivations mentioned in the PR description) that people ship externally. It's also a bit weird that we apply Note that just uplifting |
I don't quite understand this part. What is the use case for shipping a Rust dylib to someone? And if the metadata is split, then isn't it required to also include the rmeta file, otherwise the dylib is useless? |
|
You don't need the rmeta file to use (call its functions) the dylib at runtime, it is only needed at compilation time. Shipping a dylib can be useful for sharing functionality between multiple Rust applications, we also ship the compiler and the stdlib as a dylib. On Linux, the x64 stdlib .so file has 13 MiB, out of which ~8 MiB is metadata. |
|
I've been playing around with this some more, and I'm feeling more worried that this will be a breaking change. For example, building rustc itself doesn't work. I'm ok with experimenting with this behind a I think at least for the rustc use case, this will need to at least uplift the I would also recommend trying to play around with this in the rustc build system to see if you can get it to work. Supporting basic things like building rustdoc, supporting diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs
index 4e0a22e27..bc2137065 100644
--- a/src/cargo/core/compiler/build_context/target_info.rs
+++ b/src/cargo/core/compiler/build_context/target_info.rs
@@ -45,6 +45,8 @@ pub struct TargetInfo {
cfg: Vec<Cfg>,
/// `supports_std` information extracted from `rustc --print=target-spec-json`
pub supports_std: Option<bool>,
+
+ pub supports_embed: bool,
/// Supported values for `-Csplit-debuginfo=` flag, queried from rustc
support_split_debuginfo: Vec<String>,
/// Path to the sysroot.
@@ -172,6 +174,14 @@ impl TargetInfo {
// Search `--print` to see what we query so far.
let mut process = rustc.workspace_process();
apply_env_config(gctx, &mut process)?;
+
+ let mut p = process.clone();
+ p.arg("-Zembed-metadata=no");
+ p.arg("--target=aarch64-apple-darwin");
+ p.arg("--print=sysroot");
+ let status = p.status()?;
+ let supports_embed = status.success();
+
process
.arg("-")
.arg("--crate-name")
@@ -344,6 +354,7 @@ impl TargetInfo {
crate_type_process,
crate_types: RefCell::new(map),
sysroot,
+ supports_embed,
sysroot_target_libdir,
rustflags: rustflags.into(),
rustdocflags: extra_args(
diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs
index fc8be4a87..dcb5ff0e9 100644
--- a/src/cargo/core/compiler/mod.rs
+++ b/src/cargo/core/compiler/mod.rs
@@ -1713,7 +1713,13 @@ fn envify(s: &str) -> String {
/// Returns true if -Zembed-metadata=no mode should be used when compiling Rust artifacts.
fn use_embed_metadata(build_runner: &BuildRunner<'_, '_>) -> bool {
- build_runner.bcx.gctx.nightly_features_allowed
+ let supports = build_runner
+ .bcx
+ .target_data
+ .info(CompileKind::Host)
+ .supports_embed;
+
+ build_runner.bcx.gctx.nightly_features_allowed && supports
}
/// Configuration of the display of messages emitted by the compiler, |
|
I was trying to play with that, and quickly figured out that it won't work until stage0 supports the flag :) It seemed to me that the latest beta bump should have had the flag in already, but apparently it didn't. So I'm waiting for the next beta bump before continuing rustc experiments. I agree that at least for now this should be gated somehow, so that we can land it without it being enabled by default, and thus make it possible to experiment with it in the wild. Should I add an environment variable or an unstable Cargo flag to enable it? |
Bootstrap doesn't use the uplifted rlibs at all. Rather it looks at the json messages with all build artifacts and does additional filtering to omit build artifacts that aren't necessary like the |
An unstable |
|
Funny, I could swear I already did that, but couldn't find it in any local nor git history. Turns out I did the change to a second Cargo checkout that I had on disk 🤦 I'll create the tracking issue now. |
|
Created a tracking issue and mentioned it in |
Found while trying to create a tracking issue for #15378.
|
(maybe remove my username from the PR description to avoid me getting pinged every time the commit gets pushed to someones fork?) |
|
I removed the |
|
I think it does, GH merge queues by default use the PR description for the commit message. |
|
Yeah, the mention ended up in 7bdd872. |
|
Oh! None of my other repositories were set up that way. I wonder how that got set up differently. Sorry about that. |
Update cargo 25 commits in 7918c7eb59614c39f1c4e27e99d557720976bdd7..056f5f4f3c100cb36b5e9aed2d20b9ea70aae295 2025-04-27 09:44:23 +0000 to 2025-05-09 14:54:18 +0000 - Revert "doc: Mention `XDG_DATA_HOME`" (rust-lang/cargo#15512) - docs: update version notice for deprecation removal (rust-lang/cargo#15511) - doc: Update instructions on using native-completions (rust-lang/cargo#15480) - feat(network): use Retry-After header for HTTP 429 responses (rust-lang/cargo#15463) - CI: Require schema job to pass (rust-lang/cargo#15504) - chore(config): migrate renovate config (rust-lang/cargo#15501) - Make cargo script ignore workspaces (rust-lang/cargo#15496) - fix(rustc): Don't panic on unknown bins (rust-lang/cargo#15497) - test: Remove unused nightly requirements (rust-lang/cargo#15498) - Add support for `-Zembed-metadata` (rust-lang/cargo#15378) - Fix tracking issue template link (rust-lang/cargo#15494) - Refactor artifact deps in FeatureResolver::deps (rust-lang/cargo#15492) - Improved error message for versions prefixed with `v` (rust-lang/cargo#15484) - chore: fix some typos in comment (rust-lang/cargo#15485) - fix: default to all targets when using `--edition` and ` --edition-idioms` in cargo fix (rust-lang/cargo#15192) - Update fingerprint footnote (rust-lang/cargo#15478) - feat(add): suggest similarly named features (rust-lang/cargo#15438) - In package-workspace, keep dev-dependencies if they have a version (rust-lang/cargo#15470) - docs: fix a typo in DependencyUI (rust-lang/cargo#15472) - fix grammar, and remove confusing example (rust-lang/cargo#15457) - Added tracing spans for rustc invocations (rust-lang/cargo#15464) - Trivial tweaks to 'target_short_hash' (rust-lang/cargo#15461) - chore(deps): update msrv (3 versions) to v1.84 (rust-lang/cargo#15456) - feat(add/install): check if given crate argument would be valid with inserted @ symbol (rust-lang/cargo#15441) - chang 1 tries to 1 try (rust-lang/cargo#15328) r? ghost
`[no-mentions]` is for preventing something like <#15378 (comment)>. Well, maybe not working for PR description, I don't know. `[note]` is for somebody else wanting to help summarize but having no permission to edit top-level comments. See docs for more: * https://forge.rust-lang.org/triagebot/note.html * https://forge.rust-lang.org/triagebot/no-mentions.html
As of nightly 2026-01-14 the rust stdlib is compiled using -Zno-embed-metadata. This removes the rmeta data from .rlib object files. Fixing this means we need to include the .rmeta files in the stdlib file group. Breaking change in rustc: rust-lang/rust#145343 Context on -Zno-embed-metadata: rust-lang/cargo#15378
…=petrochenkov Stabilize `-Zembed-metadata` Tracking issue: rust-lang#139165 This PR proposes to stabilize the `-Zembed-metadata` compiler flag, so that Cargo can start using `-Cembed-metadata=no` by default on the stable channel. The flag can be used to avoid duplicating the metadata of Rust crates within `.rlib` and `.rmeta` files. This can reduce the size of the `target` directory anywhere from 5% to 35% on real-world projects, depending on the chosen compilation profile ([1][kobzol-blog], [2][cargo-blog]). Additionally, `-Cembed-metadata=no` also removes the metadata out of Rust `dylib`s, and thus reduces their size. The plan is to stabilize this compiler flag so that Cargo can start using it on the stable channel. The stabilization plan thus has two parts: - Stabilize the `-Cembed-metadata` flag in `rustc` - Change Cargo to use `-Cembed-metadata=no` by default The Cargo team has prepared their side of the [stabilization report](rust-lang/cargo#17533). You can examine it to see the whole picture. ## What is being stabilized The `-Zembed-metadata` compiler flag. Note that `rustc` will still default to `-Cembed-metadata=yes`, as that is its original behavior since [Rust 1.16.0](https://blog.rust-lang.org/2017/03/16/Rust-1.16/#other-improvements). But it will now be possible to pass `-Cembed-metadata=no` on stable. ## Motivation When compiling Rust crates as libraries, Cargo uses pipelined compilation, which tells `rustc` (using `--emit=metadata`) to output an `.rmeta` file as soon as possible, so that Cargo can start follow-up `rustc` instances sooner and speed up the compilation process. This file contains the Rust-specific metadata of the compiled crate. However, after the compilation of the Rust crate finishes, the compiler will also write an `.rlib` file to disk, which contains both the compiled object code, but also the same metadata that is already contained in the `.rmeta` file. This means that after the compilation finishes, the metadata of each (non-leaf) compiled crate will be duplicated on disk. The metadata can be quite large, and it is not uncommon that it takes hundreds of megabytes for real-world projects. This duplication thus contributes to increasing the size of the `target` directory, which large size is one of the top 3 most pressing [challenges](https://blog.rust-lang.org/2026/03/02/2025-State-Of-Rust-Survey-results/#challenges-and-wishes-about-rust) that Rust users struggle with. The `-Cembed-metadata=no` flag removes this duplication (see [below](#What-does-the-flag-do) on how it works). Some size benchmark results can be found in ([1][kobzol-blog], [2][cargo-blog]). It can reach up to 35% size reduction on real-world projects in `release` mode, with the effect being smaller for `dev` builds (because incremental artifacts and debuginfo start to dominate the `target` directory size). A slight bonus is that we only write the metadata to disk once, thus resulting in less I/O. I haven't noticed any measurable effect (either positive or negative) on compile times though, at least on Linux. The main motivation is disk size, not compilation speed. ## What does the flag do When you pass `-Cembed-metadata=no`, `rustc` will not write the full metadata of the compiled crate into the emitted `.rlib` file. Instead, it will only write a ["metadata stub"](https://github.com/rust-lang/rust/blob/79ee8dc08073a0abf93d2b494ac5c1be11d4342e/compiler/rustc_metadata/src/rmeta/encoder.rs#L2552), which only contains the most basic information (name, target tuple, SVH). Note that this flag should usually be combined with `--emit=metadata` to write the metadata to a `.rmeta` file, otherwise no metadata would be generated at all. When loading crate dependencies passed via `--extern`, `rustc` will read the metadata of the passed `.rlib`. If it only contains a stub, it expects that you will also pass another `--extern` flag with a path to a `.rmeta` file with the full metadata. If you don't, you will be met with the following error: ``` error: only metadata stub found for `rlib` dependency `foo`. Please provide path to the corresponding .rmeta file with full metadata ``` Note that `rustc` will still default to the original behavior of embedding metadata, so build systems that wrap `rustc` will have to explicitly opt into using `-Cembed-metadata=no`, and at that point they will also have to start passing `--extern=<...>.rmeta` flags to `rustc`. That is what Cargo currently does if you use `nightly` or if you use the unstable `-Zembed-metadata=no` *Cargo* flag. In theory, we could relax the requirement to pass both paths to the `.rlib` and the `.rmeta` file for each direct dependency in the future, and let `rustc --extern=foo/bar.rlib` automatically attempt to load `--extern=foo/bar.rmeta` when the `.rmeta` file path is not passed explicitly. `.rlib` and `.rmeta` files produced using `-Cembed-metadata=no` and `-Cembed-metadata=yes` can be freely combined, and a downstream `rustc` invocation that consumes artifacts produced by `=no` does not need to itself receive the `=no` flag. ## Ecosystem impact The `-Zembed-metadata` flag has been used for the standard library that we ship since January 2026 (rust-lang#145343) and for the compiler itself and codegen backends (cg_clif and cg_gcc) since August 2026 (rust-lang#151061). The flag has also been used by Cargo by default on the `nightly` channel since the second half of August 2026. A blog post with a call for testing can be found [here](https://blog.rust-lang.org/inside-rust/2026/08/18/reducing-target-dir-size-on-nightly/). I'm not aware of any regressions or issues reported in relation to this, not is the Cargo team (AFAIK). There are some unresolved questions about backwards compability if Cargo starts passing `-Cembed-metadata=no` by default, but those are related strictly to Cargo, and not the compiler flag itself (because the compiler flag will remain opt-in). ## History The issue of duplicated metadata was originally noted back in 2015 (rust-lang#23366, rust-lang#29511), back then because of the metadata being duplicated in Rust `dylib`s. Since Cargo started using pipelined compilation by default, it became more acute, because the metadata of all compiled `.rlib` crate dependencies started being duplicated in the `target` directory. @bjorn3 proposed to add a compiler flag to split out the metadata into a separate file in rust-lang#57076. The implementation was attempted in rust-lang#93945 and later in rust-lang#120855, but there was non-trivial complexity due to Cargo integration. In 2025, I opened an [MCP](rust-lang/compiler-team#851) with the plan to implement this flag in two stages (first in rustc, and only then in Cargo), to reduce the implementation complexity, which was accepted. The implementation in `rustc` then happened in rust-lang#137535. Implementation history: - rust-lang#137535 (April 2025): Introduction of `-Zembed-metadata`, reviewed by @petrochenkov - rust-lang/cargo#15378 (May 2025): Initial integration in Cargo, reviewed by @epage - rust-lang#145343 (January 2026): Dogfood the flag for stdlib, reviewed by @bjorn3 - rust-lang#151061 (August 2026): Dogfood the flag for rustc and codegen backends, authored by @bjorn3 - rust-lang/cargo#17267 (August 2026): Enabled the `-Cembed-metadata=no` flag by default by Cargo on the `nightly` channel ## Unresolved questions/concerns ### Command-line length limit This is more related to the Cargo side of things, but I also wanted to mention it here, because there is a possible improvement we could do on the compiler side in the future. As noted [above](#What-does-the-flag-do), usage of `-Cembed-metadata=no` requires the build system/user to pass two `--extern` flags for each direct dependency of a given `rustc` invocation. This can increase the size of the executed command-line arguments, which can in edge cases start running into operating system limits. Recently, we saw something similar in action with the Cargo's new build dir layout stabilization, where Cargo suddenly started passing a lot more `-L` flags to `rustc`, which caused issues around CLI length limits and `PATH` env. var. length limits. Cargo can work around the CLI length limit by using response files (`rustc @args`), but not all downstream tools (such as `sccache`) support those fully (yet). Based on the experience with the new build dir layout, some work was done to improve this support in the ecosystem though, and to optimize the number of flags that Cargo passes to `rustc`. If this became a problem in practice, we could teach `rustc` to start implicitly assuming `--extern=foo.rmeta` when `--extern=foo.rlib` was passed. This would reduce the number of required `--extern` flags passed to the same count as with `-Cembed-metadata=yes` (or without using that flag at all). I think that we can always do this retroactively if needed without breaking backwards compatibility, so it does not have to block this stabilization. ### Landing this change Given that this compiler flag is expected to have tight integration with Cargo, and Cargo already uses it on the nightly channel by default, we have to be a bit careful about how we actually land the `-Zembed-metadata` => `-Cembed-metadata` change. Problem A: if we simply switched it from `-Z` to `-C` in `rust-lang/rust`, then nightly would break from the following day, because Cargo would be still attempting to pass the `-Z` flag, while `rustc` would already be expecting the `-C` variant of the flag. Problem B: furthermore, bootstrap currently unconditionally passes `-Zembed-metadata=no`, both to in-tree Cargo and to beta Cargo, so that also requires some attention. There are several options of how we could resolve this: 1. Conclude the nightly Cargo experiment, so that it will not pass `-Zembed-metadata=no` to `rustc` by default anymore. Then sync Cargo to `rust-lang/rust`, and only then merge this PR. This solves A. 2. Move Cargo from a git submodule to a (Josh) subtree, so that we can atomically change both Cargo and `rustc` to use `-C` instead of `-Z` (inside this PR), to avoid breaking nightly users. This solves A. - Even though I would like to do this migration anyway, I don't think that we need to tie it to this stabilization, as it can take some time before we resolve all concerns about the migration. 3. Do what 2. proposes, but without a subtree. That means that we have to: - Change to `-C` in Cargo - Change to `-C` in `rust-lang/rust` - Sync the Cargo change back to `rust-lang/rust` in the same day that we land the `rustc` change While this solves A, it might run into some staging issues in bootstrap, and it looks very complicated to pull off. 4. Teach `rustc` to accept both the `-Z` and the `-C` variant of the flag for some time. This solves both A and B, and also gives people who use `-Zembed-metadata` manually on `nightly` some breathing room to upgrade to the `-C` variant of the flag (but GitHub code search didn't find many usages of this flag, and this is normally an expected breakage for users of unstable compiler flags). I decided to go with 4, because the integration with Cargo is tight, and modifying bootstrap back and forth to support `-Z`/no flag /`-C` would be busy work. This solves both A and B and requires little implementation effort. ## Acknowledgments - @bjorn3 for coming up with the idea, providing a reference implementation and mentoring me to finish up the implementation - @petrochenkov for reviewing the compiler side of things - @epage and @weihanglo for reviewing the Cargo side of things [kobzol-blog]: https://kobzol.github.io/rust/rustc/2025/06/02/reduce-cargo-target-dir-size-with-z-no-embed-metadata.html#cargo-integration [cargo-blog]: https://blog.rust-lang.org/inside-rust/2026/08/18/reducing-target-dir-size-on-nightly/#how-much-does-it-help CC @bjorn3 @petrochenkov @weihanglo @epage r? petrochenkov @rustbot label +needs-fcp +T-compiler
Rollup merge of #163436 - Kobzol:stabilize-embed-metadata, r=petrochenkov Stabilize `-Zembed-metadata` Tracking issue: #139165 This PR proposes to stabilize the `-Zembed-metadata` compiler flag, so that Cargo can start using `-Cembed-metadata=no` by default on the stable channel. The flag can be used to avoid duplicating the metadata of Rust crates within `.rlib` and `.rmeta` files. This can reduce the size of the `target` directory anywhere from 5% to 35% on real-world projects, depending on the chosen compilation profile ([1][kobzol-blog], [2][cargo-blog]). Additionally, `-Cembed-metadata=no` also removes the metadata out of Rust `dylib`s, and thus reduces their size. The plan is to stabilize this compiler flag so that Cargo can start using it on the stable channel. The stabilization plan thus has two parts: - Stabilize the `-Cembed-metadata` flag in `rustc` - Change Cargo to use `-Cembed-metadata=no` by default The Cargo team has prepared their side of the [stabilization report](rust-lang/cargo#17533). You can examine it to see the whole picture. ## What is being stabilized The `-Zembed-metadata` compiler flag. Note that `rustc` will still default to `-Cembed-metadata=yes`, as that is its original behavior since [Rust 1.16.0](https://blog.rust-lang.org/2017/03/16/Rust-1.16/#other-improvements). But it will now be possible to pass `-Cembed-metadata=no` on stable. ## Motivation When compiling Rust crates as libraries, Cargo uses pipelined compilation, which tells `rustc` (using `--emit=metadata`) to output an `.rmeta` file as soon as possible, so that Cargo can start follow-up `rustc` instances sooner and speed up the compilation process. This file contains the Rust-specific metadata of the compiled crate. However, after the compilation of the Rust crate finishes, the compiler will also write an `.rlib` file to disk, which contains both the compiled object code, but also the same metadata that is already contained in the `.rmeta` file. This means that after the compilation finishes, the metadata of each (non-leaf) compiled crate will be duplicated on disk. The metadata can be quite large, and it is not uncommon that it takes hundreds of megabytes for real-world projects. This duplication thus contributes to increasing the size of the `target` directory, which large size is one of the top 3 most pressing [challenges](https://blog.rust-lang.org/2026/03/02/2025-State-Of-Rust-Survey-results/#challenges-and-wishes-about-rust) that Rust users struggle with. The `-Cembed-metadata=no` flag removes this duplication (see [below](#What-does-the-flag-do) on how it works). Some size benchmark results can be found in ([1][kobzol-blog], [2][cargo-blog]). It can reach up to 35% size reduction on real-world projects in `release` mode, with the effect being smaller for `dev` builds (because incremental artifacts and debuginfo start to dominate the `target` directory size). A slight bonus is that we only write the metadata to disk once, thus resulting in less I/O. I haven't noticed any measurable effect (either positive or negative) on compile times though, at least on Linux. The main motivation is disk size, not compilation speed. ## What does the flag do When you pass `-Cembed-metadata=no`, `rustc` will not write the full metadata of the compiled crate into the emitted `.rlib` file. Instead, it will only write a ["metadata stub"](https://github.com/rust-lang/rust/blob/79ee8dc08073a0abf93d2b494ac5c1be11d4342e/compiler/rustc_metadata/src/rmeta/encoder.rs#L2552), which only contains the most basic information (name, target tuple, SVH). Note that this flag should usually be combined with `--emit=metadata` to write the metadata to a `.rmeta` file, otherwise no metadata would be generated at all. When loading crate dependencies passed via `--extern`, `rustc` will read the metadata of the passed `.rlib`. If it only contains a stub, it expects that you will also pass another `--extern` flag with a path to a `.rmeta` file with the full metadata. If you don't, you will be met with the following error: ``` error: only metadata stub found for `rlib` dependency `foo`. Please provide path to the corresponding .rmeta file with full metadata ``` Note that `rustc` will still default to the original behavior of embedding metadata, so build systems that wrap `rustc` will have to explicitly opt into using `-Cembed-metadata=no`, and at that point they will also have to start passing `--extern=<...>.rmeta` flags to `rustc`. That is what Cargo currently does if you use `nightly` or if you use the unstable `-Zembed-metadata=no` *Cargo* flag. In theory, we could relax the requirement to pass both paths to the `.rlib` and the `.rmeta` file for each direct dependency in the future, and let `rustc --extern=foo/bar.rlib` automatically attempt to load `--extern=foo/bar.rmeta` when the `.rmeta` file path is not passed explicitly. `.rlib` and `.rmeta` files produced using `-Cembed-metadata=no` and `-Cembed-metadata=yes` can be freely combined, and a downstream `rustc` invocation that consumes artifacts produced by `=no` does not need to itself receive the `=no` flag. ## Ecosystem impact The `-Zembed-metadata` flag has been used for the standard library that we ship since January 2026 (#145343) and for the compiler itself and codegen backends (cg_clif and cg_gcc) since August 2026 (#151061). The flag has also been used by Cargo by default on the `nightly` channel since the second half of August 2026. A blog post with a call for testing can be found [here](https://blog.rust-lang.org/inside-rust/2026/08/18/reducing-target-dir-size-on-nightly/). I'm not aware of any regressions or issues reported in relation to this, not is the Cargo team (AFAIK). There are some unresolved questions about backwards compability if Cargo starts passing `-Cembed-metadata=no` by default, but those are related strictly to Cargo, and not the compiler flag itself (because the compiler flag will remain opt-in). ## History The issue of duplicated metadata was originally noted back in 2015 (#23366, #29511), back then because of the metadata being duplicated in Rust `dylib`s. Since Cargo started using pipelined compilation by default, it became more acute, because the metadata of all compiled `.rlib` crate dependencies started being duplicated in the `target` directory. @bjorn3 proposed to add a compiler flag to split out the metadata into a separate file in #57076. The implementation was attempted in #93945 and later in #120855, but there was non-trivial complexity due to Cargo integration. In 2025, I opened an [MCP](rust-lang/compiler-team#851) with the plan to implement this flag in two stages (first in rustc, and only then in Cargo), to reduce the implementation complexity, which was accepted. The implementation in `rustc` then happened in #137535. Implementation history: - #137535 (April 2025): Introduction of `-Zembed-metadata`, reviewed by @petrochenkov - rust-lang/cargo#15378 (May 2025): Initial integration in Cargo, reviewed by @epage - #145343 (January 2026): Dogfood the flag for stdlib, reviewed by @bjorn3 - #151061 (August 2026): Dogfood the flag for rustc and codegen backends, authored by @bjorn3 - rust-lang/cargo#17267 (August 2026): Enabled the `-Cembed-metadata=no` flag by default by Cargo on the `nightly` channel ## Unresolved questions/concerns ### Command-line length limit This is more related to the Cargo side of things, but I also wanted to mention it here, because there is a possible improvement we could do on the compiler side in the future. As noted [above](#What-does-the-flag-do), usage of `-Cembed-metadata=no` requires the build system/user to pass two `--extern` flags for each direct dependency of a given `rustc` invocation. This can increase the size of the executed command-line arguments, which can in edge cases start running into operating system limits. Recently, we saw something similar in action with the Cargo's new build dir layout stabilization, where Cargo suddenly started passing a lot more `-L` flags to `rustc`, which caused issues around CLI length limits and `PATH` env. var. length limits. Cargo can work around the CLI length limit by using response files (`rustc @args`), but not all downstream tools (such as `sccache`) support those fully (yet). Based on the experience with the new build dir layout, some work was done to improve this support in the ecosystem though, and to optimize the number of flags that Cargo passes to `rustc`. If this became a problem in practice, we could teach `rustc` to start implicitly assuming `--extern=foo.rmeta` when `--extern=foo.rlib` was passed. This would reduce the number of required `--extern` flags passed to the same count as with `-Cembed-metadata=yes` (or without using that flag at all). I think that we can always do this retroactively if needed without breaking backwards compatibility, so it does not have to block this stabilization. ### Landing this change Given that this compiler flag is expected to have tight integration with Cargo, and Cargo already uses it on the nightly channel by default, we have to be a bit careful about how we actually land the `-Zembed-metadata` => `-Cembed-metadata` change. Problem A: if we simply switched it from `-Z` to `-C` in `rust-lang/rust`, then nightly would break from the following day, because Cargo would be still attempting to pass the `-Z` flag, while `rustc` would already be expecting the `-C` variant of the flag. Problem B: furthermore, bootstrap currently unconditionally passes `-Zembed-metadata=no`, both to in-tree Cargo and to beta Cargo, so that also requires some attention. There are several options of how we could resolve this: 1. Conclude the nightly Cargo experiment, so that it will not pass `-Zembed-metadata=no` to `rustc` by default anymore. Then sync Cargo to `rust-lang/rust`, and only then merge this PR. This solves A. 2. Move Cargo from a git submodule to a (Josh) subtree, so that we can atomically change both Cargo and `rustc` to use `-C` instead of `-Z` (inside this PR), to avoid breaking nightly users. This solves A. - Even though I would like to do this migration anyway, I don't think that we need to tie it to this stabilization, as it can take some time before we resolve all concerns about the migration. 3. Do what 2. proposes, but without a subtree. That means that we have to: - Change to `-C` in Cargo - Change to `-C` in `rust-lang/rust` - Sync the Cargo change back to `rust-lang/rust` in the same day that we land the `rustc` change While this solves A, it might run into some staging issues in bootstrap, and it looks very complicated to pull off. 4. Teach `rustc` to accept both the `-Z` and the `-C` variant of the flag for some time. This solves both A and B, and also gives people who use `-Zembed-metadata` manually on `nightly` some breathing room to upgrade to the `-C` variant of the flag (but GitHub code search didn't find many usages of this flag, and this is normally an expected breakage for users of unstable compiler flags). I decided to go with 4, because the integration with Cargo is tight, and modifying bootstrap back and forth to support `-Z`/no flag /`-C` would be busy work. This solves both A and B and requires little implementation effort. ## Acknowledgments - @bjorn3 for coming up with the idea, providing a reference implementation and mentoring me to finish up the implementation - @petrochenkov for reviewing the compiler side of things - @epage and @weihanglo for reviewing the Cargo side of things [kobzol-blog]: https://kobzol.github.io/rust/rustc/2025/06/02/reduce-cargo-target-dir-size-with-z-no-embed-metadata.html#cargo-integration [cargo-blog]: https://blog.rust-lang.org/inside-rust/2026/08/18/reducing-target-dir-size-on-nightly/#how-much-does-it-help CC @bjorn3 @petrochenkov @weihanglo @epage r? petrochenkov @rustbot label +needs-fcp +T-compiler
What does this PR try to resolve?
This PR adds Cargo integration for the new unstable
-Zembed-metadatarustc flag, which was implemented in rust-lang/rust#137535 (tracking issue). The new behavior has to be enabled explicitly using a new unstable CLI flag-Zno-embed-metadata.Tracking issue: #15495
The
-Zembed-metadata=norustc flag can reduce disk usage of compiled artifacts, and also the size of Rust dynamic library artifacts shipped to users. However, it is not enough to just pass this flag throughRUSTFLAGS; it needs to be integrated within Cargo, because it interacts with how the--emitflag is passed to rustc, and also how--externargs are passed to the final linked artifact build by Cargo. Furthermore, using the flag for all crates in a crate graph compiled by Cargo would be suboptimal (this will all be described below).When you pass
-Zembed-metadata=noto rustc, it will not store Rust metadata into the compiled artifact. This is important when compiling libs/rlibs/dylibs, since it reduces their size on disk. However, this also means that everytime we use this flag, we have to make sure that we also:metadatain the--emitflag to generate a.rmetafile, otherwise no metadata would be generated whatsoever, which would mean that the artifact wouldn't be usable as a dependency.--extern <dep>=<path>.rmetawhen compiling the final linkable artifact. Before, Cargo would only pass--extern <dep>=<path>.[rlib|so|dll]. Since with-Zembed-metadata=no, the metadata is only in the.rmetafile and not in the rlib/dylib, this is needed to help rustc find out where the metadata lies.The two points above is what this PR implements, and why this rustc flag needs Cargo integration.
The
-Zembed-metadataflag is only passed to libs, rlibs and dylibs. It does not seem to make sense for other crate types. The one situation where it might make sense are proc macros, but according to bjorn3 (who initially came up with the idea for-Zembed-metadata, it isn't really worth it).Here is a table that summarizes the changes in passed flags and generated files on disk for rlibs and dylibs:
--emit=dep-info,metadata,link.rlib(with metadata),.rmeta(for pipelining)--emit=dep-info,metadata,link -Zembed-metadata=no.rlib(without metadata),.rmeta(for metadata/pipelining)--emit=dep-info,link[.so|.dll](with metadata)--emit=dep-info,metadata,link -Zembed-metadata=no[.so|.dll](without metadata),.rmetaBehavior for other target kinds/crate types should be unchanged.
From the table above, we can see two benefits of using
-Zembed-metadata=no:.so/.dll) to users without also shipping the metadata. This would slightly reduce e.g. the size of the shipped rustc toolchains (note that the size reduction here is after the toolchain has been already heavily compressed).Note that if this behavior ever becomes the default, it should be possible to simplify the code quite a bit, and essentially merge the
requires_upstream_objectsandbenefits_from_split_metadatafunctions.I did a very simple initial benchmark to evaluate the space savings on cargo itself and hyperqueue (a mid-size crate from my work) using

cargo buildandcargo build --releasewith and without-Zembed-metadata=no:For debug/incremental builds, the effect is smaller, as the artifact disk usage is dwarfed by incremental artifacts and debuginfo. But for (non-incremental) release builds, the disk savings (and also performed I/O operations) are significantly reduced.
How should we test and review this PR?
I wrote two basic tests. The second one tests a situation where a crate depends on a dylib dependency, which is quite rare, but the behavior of this has actually changed in this PR (see comparison table above). Testing this on various real-world projects (or even trying to enable it by default across the whole Cargo suite?) might be beneficial.
Unresolved questions
Is this a breaking change?
With this new behavior, dylibs and rlibs will no longer contain metadata. If they are compiled with Cargo, that shouldn't matter, but other build systems might have to adapt.
Should this become the default?
I think that in terms of disk size usage and performed I/O operations, it is a pure win. It should either generate less disk data (for rlibs) or the ~same amount of data for dylibs (the data will be a bit larger, because the dylib will still contain a metadata stub header, but that's like 50 bytes and doesn't scale with the size of the dylib, so it's negligible).
So I think that eventually, we should just do this by default in Cargo, unless some concerns are found. I suppose that before stabilizing we should also benchmark the effect on compilation performance.