Skip to content

Introduce -Zsplit-metadata option #120855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed

Conversation

bjorn3
Copy link
Member

@bjorn3 bjorn3 commented Feb 9, 2024

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 #23366
Closes #29511
Fixes #57076

Revives #93945

@rustbot
Copy link
Collaborator

rustbot commented Feb 9, 2024

r? @cjgillot

rustbot has assigned @cjgillot.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-bootstrap Relevant to the bootstrap subteam: Rust's build system (x.py and src/bootstrap) T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Feb 9, 2024
rlibs.insert(loc_canon, PathKind::ExternFlag);
} else if loc.file_name().unwrap().to_str().unwrap().ends_with(".rmeta") {
rmetas.insert(loc_canon, PathKind::ExternFlag);
} else {
rmetas.insert(loc_canon.with_extension("rmeta"), PathKind::ExternFlag);
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a hack. It should probably be replaced with proper lookup in the library search path, or with cargo passing --extern twice for both the rlib/dylib and the rmeta file.

if extension == "so" || extension == "dylib" {
// FIXME workaround for the fact that cargo doesn't understand `-Zsplit-metadata`
toplevel.push((file_stem.clone(), "rmeta".to_owned(), None));
}
Copy link
Member Author

Choose a reason for hiding this comment

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

This together with the rustc wrapper passing --emit metadata is a big hack working around the fact that cargo doesn't support -Zsplit-metadata and as such doesn't cause a .rmeta file to be emitted and also doesn't track it in the compiler-artifact json message. This also causes issues with recompilations as the loop below may copy outdated rmeta files into the sysroot, which would then result in compiler errors.

@@ -1,4 +1,4 @@
// normalize-stderr-test "loaded from .*libstd-.*.rlib" -> "loaded from SYSROOT/libstd-*.rlib"
// normalize-stderr-test "loaded from .*libstd-.*.rmeta" -> "loaded from SYSROOT/libstd-*.rmeta"
Copy link
Member Author

Choose a reason for hiding this comment

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

The .rmeta file is now considered the canonical one as the .rlib doesn't contain any crate metadata beyond the header.

@bjorn3
Copy link
Member Author

bjorn3 commented Feb 9, 2024

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Feb 9, 2024
@bors
Copy link
Collaborator

bors commented Feb 9, 2024

⌛ Trying commit 7770002 with merge 8fb65ac...

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
Copy link
Member Author

bjorn3 commented Feb 9, 2024

What would be the best way to handle the necessary cargo changes? We can't use them until the bootstrap compiler includes the cargo changes, but cargo would depend on -Zsplit-metadata which doesn't exist yet. Would unconditionally creating a .rmeta file for dylibs like we do for rlibs be fine? Or should I add a -Zsplit-metadata option to cargo without it getting tested and then once the bootstrap bump happens, change this PR to use this option? Or land -Zsplit-metadata first without actually making any use of it, then update cargo and finally make use of it in the standard library?

@rust-log-analyzer

This comment has been minimized.

@petrochenkov petrochenkov self-assigned this Feb 9, 2024
@bors
Copy link
Collaborator

bors commented Feb 9, 2024

☀️ Try build successful - checks-actions
Build commit: 8fb65ac (8fb65acf1a11f547302c62c93bf83cca3ff4cd9d)

@rust-timer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (8fb65ac): comparison URL.

Overall result: ❌✅ regressions and improvements - ACTION NEEDED

Benchmarking this pull request likely means that it is perf-sensitive, so we're automatically marking it as not fit for rolling up. While you can manually mark this PR as fit for rollup, we strongly recommend not doing so since this PR may lead to changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please indicate this with @rustbot label: +perf-regression-triaged along with sufficient written justification. If you cannot justify the regressions please fix the regressions and do another perf run. If the next run shows neutral or positive results, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

This is a highly reliable metric that was used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
1.4% [0.3%, 2.7%] 7
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-0.4% [-0.5%, -0.4%] 3
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
7.1% [5.4%, 8.4%] 4
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-5.2% [-5.2%, -5.2%] 1
All ❌✅ (primary) - - 0

Cycles

This benchmark run did not return any relevant results for this metric.

Binary size

This benchmark run did not return any relevant results for this metric.

Bootstrap: 666.509s -> 669.311s (0.42%)
Artifact size: 307.99 MiB -> 301.34 MiB (-2.16%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Feb 9, 2024
@bjorn3
Copy link
Member Author

bjorn3 commented Feb 10, 2024

This should save about 4MB on the download size of a toolchain without any extra targets other than the host:

component e28fae5 (no split metadata) 8fb65ac (split metadata) diff
rustc 70.54MB 68.39MB -2.15MB
rust-std 27.63MB 25.61MB -2MB
rustc-dev 110.84MB 110.90MB +0.06MB

For Bevy the size of the target dir shrinks a lot:

mode normal build --emit metadata -Zsplit-metadata diff relative diff
debug mode 4.6GiB 4.3GiB -300MiB -6.5%
debug mode (no incr comp) 2.8GiB 2.6GiB -200MiB -7%
release mode 843.6MiB 614.3MiB -230MiB -27%

@bors
Copy link
Collaborator

bors commented Feb 16, 2024

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

@cjgillot cjgillot removed their assignment Feb 18, 2024
@petrochenkov
Copy link
Contributor

petrochenkov commented Mar 7, 2024

@bjorn3
Could you

  • Split 2eb24d9 into a separate PR in case it causes regressions
  • Split all preparatory refactorings like 1065559 into a separate PR
  • Rebase the remaining changes, make CI green, cleanup history, and add FIXME comments to logic that only exists due to lacking cargo support

(I'll be able to review the first two PRs quickly.)
@rustbot author

@rustbot rustbot 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 Mar 7, 2024
@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@bors
Copy link
Collaborator

bors commented Dec 27, 2024

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

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@bjorn3 bjorn3 force-pushed the split_metadata4 branch 2 times, most recently from 0e3b1b5 to 32bd529 Compare January 14, 2025 16:13
bjorn3 and others added 3 commits January 14, 2025 16:15
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.
@rust-log-analyzer

This comment has been minimized.

@petrochenkov
Copy link
Contributor

Status is not very clear, still waiting on author.
@bjorn3 Do you plan to work on completing it this year?

@bjorn3
Copy link
Member Author

bjorn3 commented Feb 19, 2025

I do still plan on working on this.

@petrochenkov
Copy link
Contributor

Closing in favor of #137535.

@bjorn3 bjorn3 deleted the split_metadata4 branch March 13, 2025 13:32
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`
github-merge-queue bot pushed a commit to rust-lang/cargo that referenced this pull request May 6, 2025
### What does this PR try to resolve?

This PR adds Cargo integration for the new unstable `-Zembed-metadata`
rustc flag, which was implemented in
rust-lang/rust#137535 ([tracking
issue](rust-lang/rust#139165)). The new
behavior has to be enabled explicitly using a new unstable CLI flag
`-Zno-embed-metadata`.

The `-Zembed-metadata=no` rustc 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 through
`RUSTFLAGS`; it needs to be integrated within Cargo, because it
interacts with how the `--emit` flag is passed to rustc, and also how
`--extern` args 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=no` to 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:
- Include `metadata` in the `--emit` flag to generate a `.rmeta` file,
otherwise no metadata would be generated whatsoever, which would mean
that the artifact wouldn't be usable as a dependency.
- Pass also `--extern <dep>=<path>.rmeta` when 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 `.rmeta` file and not in the rlib/dylib, this is
needed to help rustc find out where the metadata lies.
- Note: this essentially doubles the cmdline length when compiling the
final linked artifact. Not sure if that is a concern.

The two points above is what this PR implements, and why this rustc flag
needs Cargo integration.

The `-Zembed-metadata` flag 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:

| **Crate type** | **Flags** | **Generated files** | **Disk usage** |
|--|--|--|--|
| Rlib/Lib (before) | `--emit=dep-info,metadata,link` | `.rlib` (with
metadata), `.rmeta` (for pipelining) | - |
| Rlib/Lib (after) | `--emit=dep-info,metadata,link -Zembed-metadata=no`
| `.rlib` (without metadata), `.rmeta` (for metadata/pipelining) |
Reduced (metadata no longer duplicated) |
| Dylib (before) | `--emit=dep-info,link` | `[.so\|.dll]` (with
metadata) | - |
| Dylib (after) | `--emit=dep-info,metadata,link -Zembed-metadata=no` |
`[.so\|.dll]` (without metadata), `.rmeta` | Unchanged, but split
between two files |

Behavior for other target kinds/crate types should be unchanged.

From the table above, we can see two benefits of using
`-Zembed-metadata=no`:
- For rlibs/dylibs, we no longer store their metadata twice in the
target directory, thus reducing target directory size.
- For dylibs, we store esssentially the same amount of data on disk, but
the benefit is that the metadata is now in a separate .rmeta file. This
means that you can ship the dylib (`.so`/`.dll`) to users without also
shipping the metadata. This would slightly reduce e.g. the
[size](rust-lang/rust#120855 (comment))
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_objects` and `benefits_from_split_metadata`
functions.

I did a very simple initial benchmark to evaluate the space savings on
cargo itself and
[hyperqueue](https://github.com/It4innovations/hyperqueue) (a mid-size
crate from my work) using `cargo build` and `cargo build --release` with
and without `-Zembed-metadata=no`:

![image](https://github.com/user-attachments/assets/a26994a2-156f-4863-a823-1042ebe03bf0)

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
perf-regression Performance regression. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-bootstrap Relevant to the bootstrap subteam: Rust's build system (x.py and src/bootstrap) T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
7 participants