Skip to content

Commit 75da570

Browse files
committed
Auto merge of #83640 - bjorn3:shared_metadata_reader, r=nagisa
Use the object crate for metadata reading This allows sharing the metadata reader between cg_llvm, cg_clif and other codegen backends. This is not currently useful for rlib reading with cg_spirv ([rust-gpu](https://github.com/EmbarkStudios/rust-gpu/)) as it uses tar rather than ar as .rlib format, but it is useful for dylib reading required for loading proc macros. (cc `@eddyb)` The object crate is already trusted as dependency of libstd through backtrace. As far as I know it supports reading all object file formats used by targets for which we support rust dylibs with crate metadata, but I am not certain. If this happens to not be the case, I could keep using LLVM for reading dylib metadata. Marked as WIP for a perf run and as it is based on #83637.
2 parents 36a4d14 + 6381aaf commit 75da570

File tree

10 files changed

+98
-195
lines changed

10 files changed

+98
-195
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3695,6 +3695,7 @@ dependencies = [
36953695
"itertools 0.9.0",
36963696
"jobserver",
36973697
"libc",
3698+
"object",
36983699
"pathdiff",
36993700
"rustc_apfloat",
37003701
"rustc_ast",

compiler/rustc_codegen_cranelift/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
165165
}
166166

167167
fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
168-
Box::new(crate::metadata::CraneliftMetadataLoader)
168+
Box::new(rustc_codegen_ssa::back::metadata::DefaultMetadataLoader)
169169
}
170170

171171
fn provide(&self, _providers: &mut Providers) {}

compiler/rustc_codegen_cranelift/src/metadata.rs

+1-65
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,9 @@
1-
//! Reading and writing of the rustc metadata for rlibs and dylibs
1+
//! Writing of the rustc metadata for dylibs
22
3-
use std::fs::File;
4-
use std::path::Path;
5-
6-
use rustc_codegen_ssa::METADATA_FILENAME;
7-
use rustc_data_structures::memmap::Mmap;
8-
use rustc_data_structures::owning_ref::OwningRef;
9-
use rustc_data_structures::rustc_erase_owner;
10-
use rustc_data_structures::sync::MetadataRef;
11-
use rustc_middle::middle::cstore::MetadataLoader;
123
use rustc_middle::ty::TyCtxt;
13-
use rustc_target::spec::Target;
144

155
use crate::backend::WriteMetadata;
166

17-
/// The metadata loader used by cg_clif.
18-
///
19-
/// The metadata is stored in the same format as cg_llvm.
20-
///
21-
/// # Metadata location
22-
///
23-
/// <dl>
24-
/// <dt>rlib</dt>
25-
/// <dd>The metadata can be found in the `lib.rmeta` file inside of the ar archive.</dd>
26-
/// <dt>dylib</dt>
27-
/// <dd>The metadata can be found in the `.rustc` section of the shared library.</dd>
28-
/// </dl>
29-
pub(crate) struct CraneliftMetadataLoader;
30-
31-
fn load_metadata_with(
32-
path: &Path,
33-
f: impl for<'a> FnOnce(&'a [u8]) -> Result<&'a [u8], String>,
34-
) -> Result<MetadataRef, String> {
35-
let file = File::open(path).map_err(|e| format!("{:?}", e))?;
36-
let data = unsafe { Mmap::map(file) }.map_err(|e| format!("{:?}", e))?;
37-
let metadata = OwningRef::new(data).try_map(f)?;
38-
return Ok(rustc_erase_owner!(metadata.map_owner_box()));
39-
}
40-
41-
impl MetadataLoader for CraneliftMetadataLoader {
42-
fn get_rlib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
43-
load_metadata_with(path, |data| {
44-
let archive = object::read::archive::ArchiveFile::parse(&*data)
45-
.map_err(|e| format!("{:?}", e))?;
46-
47-
for entry_result in archive.members() {
48-
let entry = entry_result.map_err(|e| format!("{:?}", e))?;
49-
if entry.name() == METADATA_FILENAME.as_bytes() {
50-
return Ok(entry.data());
51-
}
52-
}
53-
54-
Err("couldn't find metadata entry".to_string())
55-
})
56-
}
57-
58-
fn get_dylib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
59-
use object::{Object, ObjectSection};
60-
61-
load_metadata_with(path, |data| {
62-
let file = object::File::parse(&data).map_err(|e| format!("parse: {:?}", e))?;
63-
file.section_by_name(".rustc")
64-
.ok_or("no .rustc section")?
65-
.data()
66-
.map_err(|e| format!("failed to read .rustc section: {:?}", e))
67-
})
68-
}
69-
}
70-
717
// Adapted from https://github.com/rust-lang/rust/blob/da573206f87b5510de4b0ee1a9c044127e409bd3/src/librustc_codegen_llvm/base.rs#L47-L112
728
pub(crate) fn write_metadata<O: WriteMetadata>(tcx: TyCtxt<'_>, object: &mut O) {
739
use snap::write::FrameEncoder;

compiler/rustc_codegen_llvm/src/base.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ use crate::builder::Builder;
1818
use crate::common;
1919
use crate::context::CodegenCx;
2020
use crate::llvm;
21-
use crate::metadata;
2221
use crate::value::Value;
2322

2423
use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
@@ -47,6 +46,22 @@ pub fn write_compressed_metadata<'tcx>(
4746
use snap::write::FrameEncoder;
4847
use std::io::Write;
4948

49+
// Historical note:
50+
//
51+
// When using link.exe it was seen that the section name `.note.rustc`
52+
// was getting shortened to `.note.ru`, and according to the PE and COFF
53+
// specification:
54+
//
55+
// > Executable images do not use a string table and do not support
56+
// > section names longer than 8 characters
57+
//
58+
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
59+
//
60+
// As a result, we choose a slightly shorter name! As to why
61+
// `.note.rustc` works on MinGW, see
62+
// https://github.com/llvm/llvm-project/blob/llvmorg-12.0.0/lld/COFF/Writer.cpp#L1190-L1197
63+
let section_name = if tcx.sess.target.is_like_osx { "__DATA,.rustc" } else { ".rustc" };
64+
5065
let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
5166
let mut compressed = tcx.metadata_encoding_version();
5267
FrameEncoder::new(&mut compressed).write_all(&metadata.raw_data).unwrap();
@@ -59,7 +74,6 @@ pub fn write_compressed_metadata<'tcx>(
5974
unsafe { llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr()) };
6075
unsafe {
6176
llvm::LLVMSetInitializer(llglobal, llconst);
62-
let section_name = metadata::metadata_section_name(&tcx.sess.target);
6377
let name = SmallCStr::new(section_name);
6478
llvm::LLVMSetSection(llglobal, name.as_ptr());
6579

compiler/rustc_codegen_llvm/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ pub mod llvm {
6969
}
7070

7171
mod llvm_util;
72-
mod metadata;
7372
mod mono_item;
7473
mod type_;
7574
mod type_of;
@@ -251,7 +250,7 @@ impl CodegenBackend for LlvmCodegenBackend {
251250
}
252251

253252
fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
254-
Box::new(metadata::LlvmMetadataLoader)
253+
Box::new(rustc_codegen_ssa::back::metadata::DefaultMetadataLoader)
255254
}
256255

257256
fn provide(&self, _providers: &mut ty::query::Providers) {}

compiler/rustc_codegen_llvm/src/metadata.rs

-112
This file was deleted.

compiler/rustc_codegen_ssa/Cargo.toml

+5
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,8 @@ rustc_index = { path = "../rustc_index" }
3333
rustc_macros = { path = "../rustc_macros" }
3434
rustc_target = { path = "../rustc_target" }
3535
rustc_session = { path = "../rustc_session" }
36+
37+
[dependencies.object]
38+
version = "0.22.0"
39+
default-features = false
40+
features = ["read_core", "elf", "macho", "pe", "unaligned", "archive"]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
//! Reading of the rustc metadata for rlibs and dylibs
2+
3+
use std::fs::File;
4+
use std::path::Path;
5+
6+
use rustc_data_structures::memmap::Mmap;
7+
use rustc_data_structures::owning_ref::OwningRef;
8+
use rustc_data_structures::rustc_erase_owner;
9+
use rustc_data_structures::sync::MetadataRef;
10+
use rustc_middle::middle::cstore::MetadataLoader;
11+
use rustc_target::spec::Target;
12+
13+
use crate::METADATA_FILENAME;
14+
15+
/// The default metadata loader. This is used by cg_llvm and cg_clif.
16+
///
17+
/// # Metadata location
18+
///
19+
/// <dl>
20+
/// <dt>rlib</dt>
21+
/// <dd>The metadata can be found in the `lib.rmeta` file inside of the ar archive.</dd>
22+
/// <dt>dylib</dt>
23+
/// <dd>The metadata can be found in the `.rustc` section of the shared library.</dd>
24+
/// </dl>
25+
pub struct DefaultMetadataLoader;
26+
27+
fn load_metadata_with(
28+
path: &Path,
29+
f: impl for<'a> FnOnce(&'a [u8]) -> Result<&'a [u8], String>,
30+
) -> Result<MetadataRef, String> {
31+
let file =
32+
File::open(path).map_err(|e| format!("failed to open file '{}': {}", path.display(), e))?;
33+
let data = unsafe { Mmap::map(file) }
34+
.map_err(|e| format!("failed to mmap file '{}': {}", path.display(), e))?;
35+
let metadata = OwningRef::new(data).try_map(f)?;
36+
return Ok(rustc_erase_owner!(metadata.map_owner_box()));
37+
}
38+
39+
impl MetadataLoader for DefaultMetadataLoader {
40+
fn get_rlib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
41+
load_metadata_with(path, |data| {
42+
let archive = object::read::archive::ArchiveFile::parse(&*data)
43+
.map_err(|e| format!("failed to parse rlib '{}': {}", path.display(), e))?;
44+
45+
for entry_result in archive.members() {
46+
let entry = entry_result
47+
.map_err(|e| format!("failed to parse rlib '{}': {}", path.display(), e))?;
48+
if entry.name() == METADATA_FILENAME.as_bytes() {
49+
return Ok(entry.data());
50+
}
51+
}
52+
53+
Err(format!("metadata not found in rlib '{}'", path.display()))
54+
})
55+
}
56+
57+
fn get_dylib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
58+
use object::{Object, ObjectSection};
59+
60+
load_metadata_with(path, |data| {
61+
let file = object::File::parse(&data)
62+
.map_err(|e| format!("failed to parse dylib '{}': {}", path.display(), e))?;
63+
file.section_by_name(".rustc")
64+
.ok_or_else(|| format!("no .rustc section in '{}'", path.display()))?
65+
.data()
66+
.map_err(|e| {
67+
format!("failed to read .rustc section in '{}': {}", path.display(), e)
68+
})
69+
})
70+
}
71+
}

compiler/rustc_codegen_ssa/src/back/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub mod command;
33
pub mod link;
44
pub mod linker;
55
pub mod lto;
6+
pub mod metadata;
67
pub mod rpath;
78
pub mod symbol_export;
89
pub mod write;

src/test/run-make-fulldeps/hotplug_codegen_backend/the_backend.rs

+1-13
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,11 @@ use rustc_target::spec::Target;
2828
use std::any::Any;
2929
use std::path::Path;
3030

31-
pub struct NoLlvmMetadataLoader;
32-
33-
impl MetadataLoader for NoLlvmMetadataLoader {
34-
fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<MetadataRef, String> {
35-
unreachable!("some_crate.rs shouldn't depend on any external crates");
36-
}
37-
38-
fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String> {
39-
unreachable!("some_crate.rs shouldn't depend on any external crates");
40-
}
41-
}
42-
4331
struct TheBackend;
4432

4533
impl CodegenBackend for TheBackend {
4634
fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
47-
Box::new(NoLlvmMetadataLoader)
35+
Box::new(rustc_codegen_ssa::back::metadata::DefaultMetadataLoader)
4836
}
4937

5038
fn provide(&self, providers: &mut Providers) {}

0 commit comments

Comments
 (0)