Skip to content

Introduce -Zsplit-metadata option - #93945

Closed
bjorn3 wants to merge 10 commits into
rust-lang:masterfrom
bjorn3:split_metadata3
Closed

bjorn3 wants to merge 10 commits into
rust-lang:masterfrom
bjorn3:split_metadata3

Conversation

@bjorn3

@bjorn3 bjorn3 commented Feb 12, 2022 •

Copy link
Copy Markdown
Member

This will split the crate metadata out of library files. Instead only the svh is preserved to allow for loading the right rmeta file. This significicantly reduces library size. In addition it allows for cheaper checks if different library files are the same crate.

Fixes #23366
Fixes #57076
Fixes #10786 (through 453d9a0bf778e385b45ecced681a71315fe8517e)
Should fix #82151 (through 453d9a0bf778e385b45ecced681a71315fe8517e, unconfirmed)

@bjorn3 bjorn3 added A-metadata Area: Crate metadata T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Feb 12, 2022
@rust-highfive

Copy link
Copy Markdown
Contributor

r? @davidtwco

(rust-highfive has picked a reviewer for you, use r? to override)

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Feb 12, 2022
@bjorn3

bjorn3 commented Feb 12, 2022

Copy link
Copy Markdown
Member Author

@bors try @rust-timer queue

@rust-timer

Copy link
Copy Markdown
Collaborator

Awaiting bors try build completion.

@rustbot label: +S-waiting-on-perf

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Feb 12, 2022
@bors

bors commented Feb 12, 2022

Copy link
Copy Markdown
Collaborator

⌛ Trying commit bf8a8f82a73414610384b4e36323c0966db8e908 with merge 86e45ec336f0ccde044af1ace8b3c425239d01f2...

@rust-log-analyzer

This comment was marked as outdated.

@rust-log-analyzer

This comment was marked as outdated.

@bors

bors commented Feb 12, 2022

Copy link
Copy Markdown
Collaborator

💔 Test failed - checks-actions

@bors bors added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Feb 12, 2022
Comment thread compiler/rustc_metadata/src/locator.rs Outdated
Comment on lines 549 to 556

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this comment doesn't make sense with the code below it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure where it came from. Maybe it was correct in an old draft? I finished a draft from September last year just now.

Dylib metadata compression increases code complexity and will become less
important once -Zsplit-metadata is introduced
I don't think it is necessary anymore. As I understand it from issue
39504 the original problem was that rustbuild changed a hardlink in the
cargo build dir to point to copy in the sysroot while cargo may have
hardlinked it to the original first. I don't think this happens anymore
and as such this workaround is no longer necessary.
If a crate is both an rlib and cdylib, the metadata loader would
previously incorrectly assume that it is possible to link against the
cdylib. Cdylibs don't export all symbols required for linking as rust
library.

Possibly fixes issue number 82151
This will make it easier to report rustc versions for older metadata formats.
This will split the crate metadata out of library files. Instead only
the svh is preserved to allow for loading the right rmeta file. This
significicantly reduces library size. In addition it allows for cheaper
checks if different library files are the same crate.
@bjorn3

bjorn3 commented Feb 12, 2022

Copy link
Copy Markdown
Member Author

@bors try @rust-timer queue

@rust-timer

Copy link
Copy Markdown
Collaborator

Awaiting bors try build completion.

@rustbot label: +S-waiting-on-perf

@bors

bors commented Feb 12, 2022

Copy link
Copy Markdown
Collaborator

⌛ Trying commit af25358 with merge 3e62ae8cce9be671b29a9715b3d390e4ad0c92d2...

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

Copy link
Copy Markdown
Collaborator

The job x86_64-gnu-llvm-12 failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
   Compiling std_detect v0.1.5 (/checkout/library/stdarch/crates/std_detect)
   Compiling hashbrown v0.12.0
   Compiling miniz_oxide v0.4.0
   Compiling addr2line v0.16.0
thread 'rustc' panicked at 'not yet implemented: return error', compiler/rustc_metadata/src/locator.rs:544:37
stack backtrace:
   0:     0x7f7549eb86dc - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h4c1ed0e5024ec2d0
   1:     0x7f7549f26e4e - core::fmt::write::h04f3cb9c5bd3369c
   2:     0x7f7549ea76e1 - std::io::Write::write_fmt::hec437177037c4304
   3:     0x7f7549eb850b - std::sys_common::backtrace::print::h9084352f72bce3d6
   4:     0x7f7549ebccd4 - std::panicking::default_hook::{{closure}}::h4e03c6131e9375ec
   5:     0x7f7549ebc8b6 - std::panicking::default_hook::h7c7d01494eae6d70
   6:     0x7f754a992e11 - rustc_driver[a93e051fcd12f9f8]::DEFAULT_HOOK::{closure#0}::{closure#0}
   7:     0x7f7549ebd3f3 - std::panicking::rust_panic_with_hook::hea69582e6c4a33d9
   8:     0x7f7549ebd207 - std::panicking::begin_panic_handler::{{closure}}::he6a21a353581f6cb
   9:     0x7f7549eb8bf4 - std::sys_common::backtrace::__rust_end_short_backtrace::h2d0a50649be03b70
  10:     0x7f7549ebcec9 - rust_begin_unwind
  11:     0x7f7549e739d3 - core::panicking::panic_fmt::h7802ba5043cb2ca5
  12:     0x7f754c72edd8 - <rustc_metadata[2c610e6225a46cf]::locator::CrateLocator>::extract_one
  13:     0x7f754c72c692 - <rustc_metadata[2c610e6225a46cf]::locator::CrateLocator>::extract_lib
  14:     0x7f754c72a311 - <rustc_metadata[2c610e6225a46cf]::locator::CrateLocator>::maybe_load_library_crate
  15:     0x7f754c6d203a - <rustc_metadata[2c610e6225a46cf]::creader::CrateLoader>::load
  16:     0x7f754c6ce55a - <rustc_metadata[2c610e6225a46cf]::creader::CrateLoader>::maybe_resolve_crate
  17:     0x7f754c6cd6d2 - <rustc_metadata[2c610e6225a46cf]::creader::CrateLoader>::resolve_crate
  18:     0x7f754c6d4b1c - <rustc_metadata[2c610e6225a46cf]::creader::CrateLoader>::process_extern_crate
  19:     0x7f754b488a43 - <rustc_resolve[e93c816d39f0de31]::build_reduced_graph::BuildReducedGraphVisitor as rustc_ast[fb718f914770ae88]::visit::Visitor>::visit_item
  20:     0x7f754b4ca29d - rustc_ast[fb718f914770ae88]::visit::walk_crate::<rustc_resolve[e93c816d39f0de31]::build_reduced_graph::BuildReducedGraphVisitor>
  21:     0x7f754b48b2fc - <rustc_resolve[e93c816d39f0de31]::build_reduced_graph::BuildReducedGraphVisitor as rustc_ast[fb718f914770ae88]::visit::Visitor>::visit_crate
  22:     0x7f754b4ab0cd - <rustc_resolve[e93c816d39f0de31]::Resolver as rustc_expand[3f6f1937b52b127f]::base::ResolverExpand>::visit_ast_fragment_with_placeholders
  23:     0x7f754c8bf357 - <rustc_expand[3f6f1937b52b127f]::expand::MacroExpander>::collect_invocations
  24:     0x7f754c8ba6df - <rustc_expand[3f6f1937b52b127f]::expand::MacroExpander>::fully_expand_fragment
  25:     0x7f754c8ba38b - <rustc_expand[3f6f1937b52b127f]::expand::MacroExpander>::expand_crate
  26:     0x7f754aaa5a63 - <rustc_session[22750a20d77a6d56]::session::Session>::time::<core[ba5cb6be30a93795]::result::Result<rustc_ast[fb718f914770ae88]::ast::Crate, rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_interface[768531affdc57d1c]::passes::configure_and_expand::{closure#1}>
  27:     0x7f754ab3c28d - rustc_interface[768531affdc57d1c]::passes::configure_and_expand
  28:     0x7f754aa89250 - <rustc_interface[768531affdc57d1c]::passes::boxed_resolver::BoxedResolver>::access::<<rustc_interface[768531affdc57d1c]::queries::Queries>::expansion::{closure#0}::{closure#0}, core[ba5cb6be30a93795]::result::Result<rustc_ast[fb718f914770ae88]::ast::Crate, rustc_errors[938271d98dcf7a]::ErrorReported>>
  29:     0x7f754ab1cc3d - <rustc_interface[768531affdc57d1c]::queries::Queries>::expansion
  30:     0x7f754a94412f - <rustc_interface[768531affdc57d1c]::interface::Compiler>::enter::<rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}::{closure#2}, core[ba5cb6be30a93795]::result::Result<core[ba5cb6be30a93795]::option::Option<rustc_interface[768531affdc57d1c]::queries::Linker>, rustc_errors[938271d98dcf7a]::ErrorReported>>
  31:     0x7f754a981ac9 - rustc_span[db79cfb26f8098d6]::with_source_map::<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_interface[768531affdc57d1c]::interface::create_compiler_and_run<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>::{closure#1}>
  32:     0x7f754a94242b - rustc_interface[768531affdc57d1c]::interface::create_compiler_and_run::<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>
  33:     0x7f754a91f57e - <scoped_tls[9ef8146b5f47b671]::ScopedKey<rustc_span[db79cfb26f8098d6]::SessionGlobals>>::set::<rustc_interface[768531affdc57d1c]::util::run_in_thread_pool_with_globals<rustc_interface[768531affdc57d1c]::interface::run_compiler<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#0}::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>
  34:     0x7f754a91cd05 - std[39bfa0482ff6d9eb]::sys_common::backtrace::__rust_begin_short_backtrace::<rustc_interface[768531affdc57d1c]::util::run_in_thread_pool_with_globals<rustc_interface[768531affdc57d1c]::interface::run_compiler<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>
  35:     0x7f754a984e21 - std[39bfa0482ff6d9eb]::panicking::try::<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, core[ba5cb6be30a93795]::panic::unwind_safe::AssertUnwindSafe<<std[39bfa0482ff6d9eb]::thread::Builder>::spawn_unchecked_<rustc_interface[768531affdc57d1c]::util::run_in_thread_pool_with_globals<rustc_interface[768531affdc57d1c]::interface::run_compiler<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#1}::{closure#0}>>
  36:     0x7f754a91f1f2 - <<std[39bfa0482ff6d9eb]::thread::Builder>::spawn_unchecked_<rustc_interface[768531affdc57d1c]::util::run_in_thread_pool_with_globals<rustc_interface[768531affdc57d1c]::interface::run_compiler<core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>, rustc_driver[a93e051fcd12f9f8]::run_compiler::{closure#1}>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#0}, core[ba5cb6be30a93795]::result::Result<(), rustc_errors[938271d98dcf7a]::ErrorReported>>::{closure#1} as core[ba5cb6be30a93795]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
  37:     0x7f7549ecc1c3 - std::sys::unix::thread::Thread::new::thread_start::h06eaa01755c40ab7
  38:     0x7f754423e609 - start_thread
  39:     0x7f7549d35293 - clone
  40:                0x0 - <unknown>
error: internal compiler error: unexpected panic

note: the compiler unexpectedly panicked. this is a bug.


note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: rustc 1.60.0-nightly (e6e90a610 2022-02-13) running on x86_64-unknown-linux-gnu

note: compiler flags: --crate-type dylib --crate-type rlib -C prefer-dynamic -C opt-level=3 -C embed-bitcode=no -C codegen-units=1 -C debuginfo=0 -C debug-assertions=on -C symbol-mangling-version=legacy -Z unstable-options -Z split-metadata -Z macro-backtrace -C link-args=-Wl,-z,origin -C link-args=-Wl,-rpath,$ORIGIN/../lib -C prefer-dynamic -C llvm-args=-import-instr-limit=10 -C embed-bitcode=yes -Z crate-attr=doc(html_root_url="https://doc.rust-lang.org/nightly/") -Z binary-dep-depinfo -Z force-unstable-if-unmarked
note: some of the compiler flags provided by cargo are hidden

query stack during panic:
end of query stack

@bjorn3
bjorn3 marked this pull request as draft February 13, 2022 11:50
@bjorn3

bjorn3 commented Feb 13, 2022

Copy link
Copy Markdown
Member Author

I think what happens is that when --extern some_lib=deps/libsome_lib.rlib -Ldeps is passed, it will try to load the rlib first and because the rlib is loaded, the rmeta file in deps is skipped, which fails as now there is no metadata loaded anymore.

@petrochenkov petrochenkov added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. S-waiting-on-perf Status: Waiting on a perf run to be completed. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Feb 14, 2022
@davidtwco davidtwco removed their assignment Feb 16, 2022
@bors

bors commented Feb 18, 2022

Copy link
Copy Markdown
Collaborator

☔ The latest upstream changes (presumably #94103) made this pull request unmergeable. Please resolve the merge conflicts.

@Dylan-DPC

Copy link
Copy Markdown
Member

closing this due to inactivity

@Dylan-DPC Dylan-DPC closed this Apr 5, 2022
@Dylan-DPC Dylan-DPC added S-inactive Status: Inactive and waiting on the author. This is often applied to closed PRs. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Apr 5, 2022
bors added a commit to rust-lang-ci/rust that referenced this pull request Feb 9, 2024
Introduce -Zsplit-metadata option

This will split the crate metadata out of library files. Instead only the svh and a bit of extra metadata is preserved to allow for loading the right rmeta file. This significantly reduces library size. In addition it allows for cheaper checks if different library files are the same crate.

A fair amount of the complexity in this PR is to work around the fact that cargo doesn't directly support this option yet.

Fixes rust-lang#23366
Fixes rust-lang#57076

Revives rust-lang#93945
@bjorn3

bjorn3 commented Feb 9, 2024

Copy link
Copy Markdown
Member Author

Opened #120855 to revive this.

@Dylan-DPC Dylan-DPC removed the S-inactive Status: Inactive and waiting on the author. This is often applied to closed PRs. label Feb 4, 2025
bors added a commit to rust-lang-ci/rust that referenced this pull request Apr 1, 2025
Introduce `-Zembed-metadata` to allow omitting full metadata from rlibs and dylibs

This is a continuation of rust-lang#120855 (I was mentored by `@bjorn3` to move it forward). Most of the original code was written by bjorn3, I tried to clean it up a bit and add some documentation and tests.

This PR introduces a new unstable compiler flag called `-Zembed-metadata=[no|yes]`, with the default being `yes` (see rust-lang#57076 for context). When set to `no`, rustc will only store a small metadata stub inside rlibs/dylibs instead of the full metadata, to keep their size smaller. It should be used in combination with `--emit=metadata`, so that the users of such a compiled library can still read the metadata from the corresponding `.rmeta` file. [This comment](rust-lang#120855 (comment)) shows an example of binary/artifact size wins that can be achieved using this approach.

Contrary to rust-lang#120855, this PR only introduces the new flag, along with a couple of run-make tests and documentation, but does not yet use it in bootstrap to actually compile rustc. I plan to do that as a follow-up step (along with integration in Cargo, which should ideally just always pass this flag to reduce the size of target directories).

Fixes rust-lang#23366
Closes rust-lang#29511
Fixes rust-lang#57076

Another attempt of rust-lang#93945 and rust-lang#120855.

r? `@petrochenkov`
lnicola pushed a commit to lnicola/rust-analyzer that referenced this pull request Apr 28, 2025
Introduce `-Zembed-metadata` to allow omitting full metadata from rlibs and dylibs

This is a continuation of rust-lang/rust#120855 (I was mentored by `@bjorn3` to move it forward). Most of the original code was written by bjorn3, I tried to clean it up a bit and add some documentation and tests.

This PR introduces a new unstable compiler flag called `-Zembed-metadata=[no|yes]`, with the default being `yes` (see rust-lang/rust#57076 for context). When set to `no`, rustc will only store a small metadata stub inside rlibs/dylibs instead of the full metadata, to keep their size smaller. It should be used in combination with `--emit=metadata`, so that the users of such a compiled library can still read the metadata from the corresponding `.rmeta` file. [This comment](rust-lang/rust#120855 (comment)) shows an example of binary/artifact size wins that can be achieved using this approach.

Contrary to rust-lang/rust#120855, this PR only introduces the new flag, along with a couple of run-make tests and documentation, but does not yet use it in bootstrap to actually compile rustc. I plan to do that as a follow-up step (along with integration in Cargo, which should ideally just always pass this flag to reduce the size of target directories).

Fixes rust-lang/rust#23366
Closes rust-lang/rust#29511
Fixes rust-lang/rust#57076

Another attempt of rust-lang/rust#93945 and rust-lang/rust#120855.

r? `@petrochenkov`
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Oct 19, 2026
…=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
rust-bors Bot pushed a commit that referenced this pull request Oct 19, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-metadata Area: Crate metadata T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet