Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/test_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,14 @@ impl SingleAttributeParser for RustcTestMarkerParser {
Some(AttributeKind::RustcTestMarker(value_str))
}
}

pub(crate) struct RustcTestEntrypointMarkerParser;

impl NoArgsAttributeParser for RustcTestEntrypointMarkerParser {
const PATH: &[Symbol] = &[sym::rustc_test_entrypoint_marker];
const ALLOWED_TARGETS: AllowedTargets<'_> =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::Closure)]);
const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn;
const STABILITY: AttributeStability = unstable!(rustc_attrs);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcTestEntrypointMarker;
}
1 change: 1 addition & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ attribute_parsers!(
Single<WithoutArgs<RustcSpecializationTraitParser>>,
Single<WithoutArgs<RustcStdInternalSymbolParser>>,
Single<WithoutArgs<RustcStrictCoherenceParser>>,
Single<WithoutArgs<RustcTestEntrypointMarkerParser>>,
Single<WithoutArgs<RustcTrivialFieldReadsParser>>,
Single<WithoutArgs<RustcUnsafeSpecializationMarkerParser>>,
Single<WithoutArgs<SplatParser>>,
Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_builtin_macros/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
///
/// We mark item with an inert attribute "rustc_test_marker" which the test generation
/// logic will pick up on.
///
/// The test function also gains a `#[rustc_test_entrypoint_marker]` attribute for tools to pick up
/// on. This behavior is *unstable*.
pub(crate) fn expand_test_case(
ecx: &mut ExtCtxt<'_>,
attr_sp: Span,
Expand Down Expand Up @@ -381,6 +384,12 @@ pub(crate) fn expand_test_or_bench(
let test_extern =
cx.item(sp, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None, test_ident));

let item = {
let mut item = item;
item.attrs.push(cx.attr_word(sym::rustc_test_entrypoint_marker, attr_sp));
item
};

debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const));

if is_stmt {
Expand Down
101 changes: 84 additions & 17 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use rustc_lint_defs::builtin::LINKER_INFO;
use rustc_macros::Diagnostic;
use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
use rustc_metadata::{
EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
EncodedMetadata, NativeLibSearchFallback, find_bundled_library, find_native_static_library,
walk_native_lib_search_dirs,
};
use rustc_middle::bug;
Expand Down Expand Up @@ -396,8 +396,25 @@ fn link_rlib<'a>(
.map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
.collect();

let native_lib_filenames: Vec<Option<Symbol>> = crate_info
.used_libraries
.iter()
.map(|lib| {
find_bundled_library(
lib.name,
Some(lib.verbatim),
lib.kind,
lib.cfg.is_some(),
sess,
&crate_info.crate_types,
)
})
.collect();

let metadata_link_file = if matches!(flavor, RlibFlavor::Normal) {
let metadata_link = rmeta_link::RmetaLink { rust_object_files };
let native_lib_filenames: Vec<Option<String>> =
native_lib_filenames.iter().map(|f| f.map(|s| s.to_string())).collect();
let metadata_link = rmeta_link::RmetaLink { rust_object_files, native_lib_filenames };
let metadata_link_data = metadata_link.encode();
let (wrapper, _) =
create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
Expand Down Expand Up @@ -480,12 +497,12 @@ fn link_rlib<'a>(
// feature then we'll need to figure out how to record what objects were
// loaded from the libraries found here and then encode that into the
// metadata of the rlib we're generating somehow.
for lib in crate_info.used_libraries.iter() {
for (i, lib) in crate_info.used_libraries.iter().enumerate() {
let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
continue;
};
if flavor == RlibFlavor::Normal
&& let Some(filename) = lib.filename
&& let Some(filename) = native_lib_filenames[i]
{
let path = find_native_static_library(filename.as_str(), true, sess);
let src = read(path)
Expand Down Expand Up @@ -599,11 +616,21 @@ fn link_staticlib(
let lto = are_upstream_rust_objects_already_included(sess)
&& !ignored_for_lto(sess, crate_info, cnum);

let native_libs = crate_info.native_libraries[&cnum].iter();
let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
let native_libs = &crate_info.native_libraries[&cnum];
let bundled_filenames =
rmeta_link_cache.native_lib_filenames(&sess.target, path, native_libs);
let relevant_libs: FxIndexSet<_> = native_libs
.iter()
.enumerate()
.filter(|(_, lib)| relevant_lib(sess, lib))
.filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
.collect();

let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
let bundled_libs: FxIndexSet<_> = native_libs
.iter()
.enumerate()
.filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
.collect();
ab.add_archive(
path,
AddArchiveKind::Rlib(rmeta_link_cache, &|fname: &str, entry_kind| {
Expand Down Expand Up @@ -2804,6 +2831,7 @@ fn linker_with_args(
cmd,
sess,
archive_builder_builder,
rmeta_link_cache,
crate_info,
tmpdir,
link_output_kind,
Expand All @@ -2826,6 +2854,7 @@ fn linker_with_args(
cmd,
sess,
archive_builder_builder,
rmeta_link_cache,
crate_info,
tmpdir,
link_output_kind,
Expand Down Expand Up @@ -3125,6 +3154,7 @@ fn add_native_libs_from_crate(
cmd: &mut dyn Linker,
sess: &Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
rmeta_link_cache: &mut RmetaLinkCache,
crate_info: &CrateInfo,
tmpdir: &Path,
bundled_libs: &FxIndexSet<Symbol>,
Expand All @@ -3148,13 +3178,38 @@ fn add_native_libs_from_crate(
.unwrap_or_else(|e| sess.dcx().emit_fatal(e));
}

let native_libs = match cnum {
LOCAL_CRATE => &crate_info.used_libraries,
_ => &crate_info.native_libraries[&cnum],
let (native_libs, bundled_filenames): (&Vec<NativeLib>, Vec<Option<Symbol>>) = match cnum {
LOCAL_CRATE => {
let libs = &crate_info.used_libraries;
let filenames = libs
.iter()
.map(|lib| {
find_bundled_library(
lib.name,
Some(lib.verbatim),
lib.kind,
lib.cfg.is_some(),
sess,
&crate_info.crate_types,
)
})
.collect();
(libs, filenames)
}
_ => {
let native_libs = &crate_info.native_libraries[&cnum];
let filenames =
if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
rmeta_link_cache.native_lib_filenames(&sess.target, rlib_path, native_libs)
} else {
Vec::new()
};
(native_libs, filenames)
}
};

let mut last = (None, NativeLibKind::Unspecified, false);
for lib in native_libs {
for (i, lib) in native_libs.iter().enumerate() {
if !relevant_lib(sess, lib) {
continue;
}
Expand All @@ -3174,7 +3229,7 @@ fn add_native_libs_from_crate(
let bundle = bundle.unwrap_or(true);
let whole_archive = whole_archive == Some(true);
if bundle && cnum != LOCAL_CRATE {
if let Some(filename) = lib.filename {
if let Some(filename) = bundled_filenames.get(i).copied().flatten() {
// If rlib contains native libs as archives, they are unpacked to tmpdir.
let path = tmpdir.join(filename.as_str());
cmd.link_staticlib_by_path(&path, whole_archive);
Expand Down Expand Up @@ -3226,6 +3281,7 @@ fn add_local_native_libraries(
cmd: &mut dyn Linker,
sess: &Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
rmeta_link_cache: &mut RmetaLinkCache,
crate_info: &CrateInfo,
tmpdir: &Path,
link_output_kind: LinkOutputKind,
Expand All @@ -3237,6 +3293,7 @@ fn add_local_native_libraries(
cmd,
sess,
archive_builder_builder,
rmeta_link_cache,
crate_info,
tmpdir,
&Default::default(),
Expand Down Expand Up @@ -3296,10 +3353,17 @@ fn add_upstream_rust_crates(
match linkage {
Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
if link_static_crate {
bundled_libs = crate_info.native_libraries[&cnum]
.iter()
.filter_map(|lib| lib.filename)
.collect();
if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
bundled_libs = rmeta_link_cache
.native_lib_filenames(
&sess.target,
rlib_path,
&crate_info.native_libraries[&cnum],
)
.into_iter()
.flatten()
.collect();
}
add_static_crate(
cmd,
sess,
Expand Down Expand Up @@ -3333,6 +3397,7 @@ fn add_upstream_rust_crates(
cmd,
sess,
archive_builder_builder,
rmeta_link_cache,
crate_info,
tmpdir,
&bundled_libs,
Expand All @@ -3348,6 +3413,7 @@ fn add_upstream_native_libraries(
cmd: &mut dyn Linker,
sess: &Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
rmeta_link_cache: &mut RmetaLinkCache,
crate_info: &CrateInfo,
tmpdir: &Path,
link_output_kind: LinkOutputKind,
Expand All @@ -3371,6 +3437,7 @@ fn add_upstream_native_libraries(
cmd,
sess,
archive_builder_builder,
rmeta_link_cache,
crate_info,
tmpdir,
&Default::default(),
Expand Down
64 changes: 62 additions & 2 deletions compiler/rustc_codegen_ssa/src/back/rmeta_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,38 @@
//! and potentially other data collected and used when building or linking a rlib.
//! See <https://github.com/rust-lang/rust/issues/138243>.

use std::fs::File;
use std::path::{Path, PathBuf};

use object::read::archive::ArchiveFile;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::memmap::Mmap;
use rustc_hir::attrs::NativeLibKind;
use rustc_serialize::opaque::mem_encoder::MemEncoder;
use rustc_serialize::opaque::{MAGIC_END_BYTES, MemDecoder};
use rustc_serialize::{Decodable, Encodable};
use rustc_span::Symbol;
use rustc_target::spec::Target;
use tracing::debug;

use super::metadata::search_for_section;
use super::metadata::{get_metadata_xcoff, search_for_section};
use crate::NativeLib;

pub(crate) const FILENAME: &str = "lib.rmeta-link";
pub(crate) const SECTION: &str = ".rmeta-link";

pub struct RmetaLink {
pub rust_object_files: Vec<String>,
/// Positionally aligned with `native_libraries` in regular metadata: index `i` is the
/// bundled filename for native library `i`, or `None` if that library needs no bundling.
pub native_lib_filenames: Vec<Option<String>>,
}

impl RmetaLink {
pub(crate) fn encode(&self) -> Vec<u8> {
let mut encoder = MemEncoder::new();
self.rust_object_files.encode(&mut encoder);
self.native_lib_filenames.encode(&mut encoder);
let mut data = encoder.finish();
data.extend_from_slice(MAGIC_END_BYTES);
data
Expand All @@ -31,7 +42,8 @@ impl RmetaLink {
pub(crate) fn decode(data: &[u8]) -> Option<RmetaLink> {
let mut decoder = MemDecoder::new(data, 0).ok()?;
let rust_object_files = Vec::<String>::decode(&mut decoder);
Some(RmetaLink { rust_object_files })
let native_lib_filenames = Vec::<Option<String>>::decode(&mut decoder);
Some(RmetaLink { rust_object_files, native_lib_filenames })
}
}

Expand Down Expand Up @@ -69,4 +81,52 @@ impl RmetaLinkCache {
) -> Option<&RmetaLink> {
self.cache.entry(rlib_path.to_path_buf()).or_insert_with(load).as_ref()
}

pub fn native_lib_filenames(
&mut self,
target: &Target,
rlib_path: &Path,
native_libs: &[NativeLib],
) -> Vec<Option<Symbol>> {
if !crate_may_have_bundled_libs(native_libs) {
return Vec::new();
}
self.get_or_insert_with(rlib_path, || read_from_path(target, rlib_path))
.map(|rl| {
rl.native_lib_filenames.iter().map(|f| f.as_deref().map(Symbol::intern)).collect()
})
.unwrap_or_default()
}
}

fn crate_may_have_bundled_libs(libs: &[NativeLib]) -> bool {
libs.iter()
.any(|lib| matches!(lib.kind, NativeLibKind::Static { bundle: Some(true) | None, .. }))
}

// FIXME: this is mostly a copy-paste of `DefaultMetadataLoader::get_rlib_metadata`.
fn read_from_path(target: &Target, path: &Path) -> Option<RmetaLink> {
let Ok(file) = File::open(path) else {
debug!("failed to open rlib for rmeta-link: {}", path.display());
return None;
};
let Ok(mmap) = (unsafe { Mmap::map(file) }) else {
debug!("failed to mmap rlib for rmeta-link: {}", path.display());
return None;
};

if target.is_like_aix {
let archive = ArchiveFile::parse(&*mmap).ok()?;
for entry in archive.members() {
let entry = entry.ok()?;
if entry.name() == FILENAME.as_bytes() {
let member_data = entry.data(&*mmap).ok()?;
let section_data = get_metadata_xcoff(path, member_data).ok()?;
return RmetaLink::decode(section_data);
}
}
return None;
}

read_from_data(&mmap, path)
}
2 changes: 0 additions & 2 deletions compiler/rustc_codegen_ssa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ bitflags::bitflags! {
pub struct NativeLib {
pub kind: NativeLibKind,
pub name: Symbol,
pub filename: Option<Symbol>,
pub cfg: Option<CfgEntry>,
pub verbatim: bool,
pub dll_imports: Vec<cstore::DllImport>,
Expand All @@ -226,7 +225,6 @@ impl From<&cstore::NativeLib> for NativeLib {
fn from(lib: &cstore::NativeLib) -> Self {
NativeLib {
kind: lib.kind,
filename: lib.filename,
name: lib.name,
cfg: lib.cfg.clone(),
verbatim: lib.verbatim.unwrap_or(false),
Expand Down
Loading
Loading