1mod raw_dylib;
23use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
1112use find_msvc_tools;
13use itertools::Itertools;
14use object::{Object, ObjectSection, ObjectSymbol};
15use regex::Regex;
16use rustc_arena::TypedArena;
17use rustc_attr_parsing::eval_config_entry;
18use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::DiagCtxtHandle;
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_lint_defs::builtin::LINKER_INFO;
26use rustc_macros::Diagnostic;
27use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
28use rustc_metadata::{
29EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
30walk_native_lib_search_dirs,
31};
32use rustc_middle::bug;
33use rustc_middle::lint::emit_lint_base;
34use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
35use rustc_middle::middle::dependency_format::Linkage;
36use rustc_middle::middle::exported_symbols::SymbolExportKind;
37use rustc_session::config::{
38self, CFGuard, CrateType, DebugInfo, InstrumentMcount, LinkerFeaturesCli, OutFileName,
39OutputFilenames, OutputType, PrintKind, SplitDwarfKind, Strip,
40};
41use rustc_session::lint::builtin::LINKER_MESSAGES;
42use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
43use rustc_session::search_paths::PathKind;
44/// For all the linkers we support, and information they might
45/// need out of the shared crate context before we get rid of it.
46use rustc_session::{Session, filesearch};
47use rustc_span::Symbol;
48use rustc_target::spec::crt_objects::CrtObjects;
49use rustc_target::spec::{
50Arch, BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
51LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
52RelroLevel, SanitizerSet, SplitDebuginfo,
53};
54use tracing::{debug, info, warn};
5556use super::archive::{
57AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind, ArchiveSymbols,
58};
59use super::command::Command;
60use super::linker::{self, Linker};
61use super::metadata::{MetadataPosition, create_wrapper_file};
62use super::rmeta_link::RmetaLinkCache;
63use super::rpath::{self, RPathConfig};
64use super::{apple, rmeta_link, versioned_llvm_target};
65use crate::base::needs_allocator_shim_for_linking;
66use crate::{CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors};
6768pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
69if let Err(e) = fs::remove_file(path) {
70if e.kind() != io::ErrorKind::NotFound {
71dcx.err(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to remove {0}: {1}",
path.display(), e))
})format!("failed to remove {}: {}", path.display(), e));
72 }
73 }
74}
7576/// Performs the linkage portion of the compilation phase. This will generate all
77/// of the requested outputs for this compilation session.
78pub fn link_binary(
79 sess: &Session,
80 archive_builder_builder: &dyn ArchiveBuilderBuilder,
81 compiled_modules: CompiledModules,
82 crate_info: CrateInfo,
83 metadata: EncodedMetadata,
84 outputs: &OutputFilenames,
85 codegen_backend: &'static str,
86) {
87let _timer = sess.timer("link_binary");
88let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
89let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
90let mut rmeta_link_cache = RmetaLinkCache::default();
91for &crate_type in &crate_info.crate_types {
92// Ignore executable crates if we have -Z no-codegen, as they will error.
93if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
94 && !output_metadata
95 && crate_type == CrateType::Executable
96 {
97continue;
98 }
99100if invalid_output_for_target(sess, crate_type) {
101::rustc_middle::util::bug::bug_fmt(format_args!("invalid output type `{0:?}` for target `{1}`",
crate_type, sess.opts.target_triple));bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
102 }
103104 sess.time("link_binary_check_files_are_writeable", || {
105for m in &compiled_modules.modules {
106if let Some(obj) = &m.object {
107 check_file_is_writeable(obj, sess);
108 }
109if let Some(obj) = &m.global_asm_object {
110 check_file_is_writeable(obj, sess);
111 }
112 }
113 });
114115if outputs.outputs.should_link() {
116let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
117let tmpdir = TempDirBuilder::new()
118 .prefix("rustc")
119 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
120 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
121let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
122123let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
124let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
125match crate_type {
126 CrateType::Rlib => {
127let _timer = sess.timer("link_rlib");
128{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:128",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(128u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing rlib to {0:?}",
out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing rlib to {:?}", out_filename);
129 link_rlib(
130 sess,
131 archive_builder_builder,
132&compiled_modules,
133&crate_info,
134&metadata,
135 RlibFlavor::Normal,
136&path,
137 )
138 .build(&out_filename, None);
139 }
140 CrateType::StaticLib => {
141 link_staticlib(
142 sess,
143 archive_builder_builder,
144&mut rmeta_link_cache,
145&compiled_modules,
146&crate_info,
147&metadata,
148&out_filename,
149&path,
150 );
151 }
152_ => {
153 link_natively(
154 sess,
155 archive_builder_builder,
156&mut rmeta_link_cache,
157 crate_type,
158&out_filename,
159&compiled_modules,
160&crate_info,
161&metadata,
162 path.as_ref(),
163 codegen_backend,
164 );
165 }
166 }
167if sess.opts.json_artifact_notifications {
168 sess.dcx().emit_artifact_notification(&out_filename, "link");
169 }
170171if sess.prof.enabled()
172 && let Some(artifact_name) = out_filename.file_name()
173 {
174// Record size for self-profiling
175let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
176177 sess.prof.artifact_size(
178"linked_artifact",
179 artifact_name.to_string_lossy(),
180 file_size,
181 );
182 }
183184if sess.target.binary_format == BinaryFormat::Elf {
185if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
186{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:186",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(186u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message", "err"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Error while checking if gold was the linker")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&err) as
&dyn Value))])
});
} else { ; }
};info!(?err, "Error while checking if gold was the linker");
187 }
188 }
189190if output.is_stdout() {
191if output.is_tty() {
192 sess.dcx().emit_err(errors::BinaryOutputToTty {
193 shorthand: OutputType::Exe.shorthand(),
194 });
195 } else if let Err(e) = copy_to_stdout(&out_filename) {
196 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
197 }
198 tempfiles_for_stdout_output.push(out_filename);
199 }
200 }
201 }
202203// Remove the temporary object file and metadata if we aren't saving temps.
204sess.time("link_binary_remove_temps", || {
205// If the user requests that temporaries are saved, don't delete any.
206if sess.opts.cg.save_temps {
207return;
208 }
209210let maybe_remove_temps_from_module =
211 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
212if !preserve_objects && let Some(ref obj) = module.object {
213ensure_removed(sess.dcx(), obj);
214 }
215216if !preserve_objects && let Some(ref obj) = module.global_asm_object {
217ensure_removed(sess.dcx(), obj);
218 }
219220if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
221ensure_removed(sess.dcx(), dwo_obj);
222 }
223 };
224225let remove_temps_from_module =
226 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
227228// Otherwise, always remove the allocator module temporaries.
229if let Some(ref allocator_module) = compiled_modules.allocator_module {
230remove_temps_from_module(allocator_module);
231 }
232233// Remove the temporary files if output goes to stdout
234for temp in tempfiles_for_stdout_output {
235 ensure_removed(sess.dcx(), &temp);
236 }
237238// If no requested outputs require linking, then the object temporaries should
239 // be kept.
240if !sess.opts.output_types.should_link() {
241return;
242 }
243244// Potentially keep objects for their debuginfo.
245let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
246{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:246",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(246u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["preserve_objects",
"preserve_dwarf_objects"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&preserve_objects)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&preserve_dwarf_objects)
as &dyn Value))])
});
} else { ; }
};debug!(?preserve_objects, ?preserve_dwarf_objects);
247248for module in &compiled_modules.modules {
249 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
250 }
251 });
252}
253254// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
255// crate types must use the same dependency formats.
256pub fn each_linked_rlib(
257 info: &CrateInfo,
258 crate_type: Option<CrateType>,
259 f: &mut dyn FnMut(CrateNum, &Path),
260) -> Result<(), errors::LinkRlibError> {
261let fmts = if let Some(crate_type) = crate_type {
262let Some(fmts) = info.dependency_formats.get(&crate_type) else {
263return Err(errors::LinkRlibError::MissingFormat);
264 };
265266fmts267 } else {
268let mut dep_formats = info.dependency_formats.iter();
269let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
270if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
271return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
272 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
273 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
274 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
275 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
276 });
277 }
278list1279 };
280281let used_dep_crates = info.used_crates.iter();
282for &cnum in used_dep_crates {
283match fmts.get(cnum) {
284Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
285Some(_) => {}
286None => return Err(errors::LinkRlibError::MissingFormat),
287 }
288let crate_name = info.crate_name[&cnum];
289let used_crate_source = &info.used_crate_source[&cnum];
290if let Some(path) = &used_crate_source.rlib {
291 f(cnum, path);
292 } else if used_crate_source.rmeta.is_some() {
293return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
294 } else {
295return Err(errors::LinkRlibError::NotFound { crate_name });
296 }
297 }
298Ok(())
299}
300301/// Create an 'rlib'.
302///
303/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
304/// The rlib primarily contains the object file of the crate, but it also some of the object files
305/// from native libraries.
306fn link_rlib<'a>(
307 sess: &'a Session,
308 archive_builder_builder: &dyn ArchiveBuilderBuilder,
309 compiled_modules: &CompiledModules,
310 crate_info: &CrateInfo,
311 metadata: &EncodedMetadata,
312 flavor: RlibFlavor,
313 tmpdir: &MaybeTempDir,
314) -> Box<dyn ArchiveBuilder + 'a> {
315let mut ab = archive_builder_builder.new_archive_builder(sess);
316317// Pre-compute the list of Rust object filenames and materialize the rmeta-link
318 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
319 // placed immediately after metadata in the archive, so consumers can find
320 // it without iterating every archive member.
321let rust_object_files: Vec<String> = compiled_modules322 .modules
323 .iter()
324 .filter_map(|m| m.object.as_ref())
325 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
326 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
327 .collect();
328329let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
330let metadata_link = rmeta_link::RmetaLink { rust_object_files };
331let metadata_link_data = metadata_link.encode();
332let (wrapper, _) =
333create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
334Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
335 } else {
336None337 };
338339let trailing_metadata = match flavor {
340 RlibFlavor::Normal => {
341let (metadata, metadata_position) =
342create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
343let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
344match metadata_position {
345 MetadataPosition::First => {
346// Most of the time metadata in rlib files is wrapped in a "dummy" object
347 // file for the target platform so the rlib can be processed entirely by
348 // normal linkers for the platform. Sometimes this is not possible however.
349 // If it is possible however, placing the metadata object first improves
350 // performance of getting metadata from rlibs.
351ab.add_file(&metadata, ArchiveEntryKind::Other);
352// Place the rmeta-link member immediately after metadata so consumers
353 // can find it without iterating the whole archive.
354if let Some(file) = &metadata_link_file {
355ab.add_file(file, ArchiveEntryKind::Other);
356 }
357None358 }
359 MetadataPosition::Last => Some(metadata),
360 }
361 }
362363 RlibFlavor::StaticlibBase => None,
364 };
365366for m in &compiled_modules.modules {
367if let Some(obj) = m.object.as_ref() {
368 ab.add_file(obj, ArchiveEntryKind::RustObj);
369 }
370371if let Some(obj) = m.global_asm_object.as_ref() {
372 ab.add_file(obj, ArchiveEntryKind::RustObj);
373 }
374375if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
376 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
377 }
378 }
379380match flavor {
381 RlibFlavor::Normal => {}
382 RlibFlavor::StaticlibBase => {
383if let Some(m) = &compiled_modules.allocator_module {
384if let Some(obj) = &m.object {
385ab.add_file(obj, ArchiveEntryKind::RustObj);
386 }
387if let Some(obj) = &m.global_asm_object {
388ab.add_file(obj, ArchiveEntryKind::RustObj);
389 }
390 }
391 }
392 }
393394// Used if packed_bundled_libs flag enabled.
395let mut packed_bundled_libs = Vec::new();
396397// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
398 // we may not be configured to actually include a static library if we're
399 // adding it here. That's because later when we consume this rlib we'll
400 // decide whether we actually needed the static library or not.
401 //
402 // To do this "correctly" we'd need to keep track of which libraries added
403 // which object files to the archive. We don't do that here, however. The
404 // #[link(cfg(..))] feature is unstable, though, and only intended to get
405 // liblibc working. In that sense the check below just indicates that if
406 // there are any libraries we want to omit object files for at link time we
407 // just exclude all custom object files.
408 //
409 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
410 // feature then we'll need to figure out how to record what objects were
411 // loaded from the libraries found here and then encode that into the
412 // metadata of the rlib we're generating somehow.
413for lib in crate_info.used_libraries.iter() {
414let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
415continue;
416 };
417if flavor == RlibFlavor::Normal
418 && let Some(filename) = lib.filename
419 {
420let path = find_native_static_library(filename.as_str(), true, sess);
421let src = read(path)
422 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
423let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
424let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
425 packed_bundled_libs.push(wrapper_file);
426 } else {
427let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
428 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
429 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
430 });
431 }
432 }
433434// On Windows, we add the raw-dylib import libraries to the rlibs already.
435 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
436 // Instead, we add all raw-dylibs to the final link on ELF.
437if sess.target.is_like_windows {
438for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
439 sess,
440 archive_builder_builder,
441 crate_info.used_libraries.iter(),
442 tmpdir.as_ref(),
443true,
444 ) {
445 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
446 sess.dcx()
447 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
448 });
449 }
450 }
451452if let Some(trailing_metadata) = trailing_metadata {
453// Note that it is important that we add all of our non-object "magical
454 // files" *after* all of the object files in the archive. The reason for
455 // this is as follows:
456 //
457 // * When performing LTO, this archive will be modified to remove
458 // objects from above. The reason for this is described below.
459 //
460 // * When the system linker looks at an archive, it will attempt to
461 // determine the architecture of the archive in order to see whether its
462 // linkable.
463 //
464 // The algorithm for this detection is: iterate over the files in the
465 // archive. Skip magical SYMDEF names. Interpret the first file as an
466 // object file. Read architecture from the object file.
467 //
468 // * As one can probably see, if "metadata" and "foo.bc" were placed
469 // before all of the objects, then the architecture of this archive would
470 // not be correctly inferred once 'foo.o' is removed.
471 //
472 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
473 // file for the target platform so the rlib can be processed entirely by
474 // normal linkers for the platform. Sometimes this is not possible however.
475 //
476 // Basically, all this means is that this code should not move above the
477 // code above.
478ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
479// Place the rmeta-link member immediately after metadata so consumers can
480 // find it without iterating the whole archive.
481if let Some(file) = &metadata_link_file {
482ab.add_file(file, ArchiveEntryKind::Other);
483 }
484 }
485486// Add all bundled static native library dependencies.
487 // Archives added to the end of .rlib archive, see comment above for the reason.
488for lib in packed_bundled_libs {
489 ab.add_file(&lib, ArchiveEntryKind::Other)
490 }
491492ab493}
494495/// Create a static archive.
496///
497/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
498/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
499/// dependencies as well.
500///
501/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
502/// library dependencies that they're not linked in.
503///
504/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
505/// object file (and also don't prepare the archive with a metadata file).
506fn link_staticlib(
507 sess: &Session,
508 archive_builder_builder: &dyn ArchiveBuilderBuilder,
509 rmeta_link_cache: &mut RmetaLinkCache,
510 compiled_modules: &CompiledModules,
511 crate_info: &CrateInfo,
512 metadata: &EncodedMetadata,
513 out_filename: &Path,
514 tempdir: &MaybeTempDir,
515) {
516{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:516",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(516u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing staticlib to {0:?}",
out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing staticlib to {:?}", out_filename);
517let mut ab = link_rlib(
518sess,
519archive_builder_builder,
520compiled_modules,
521crate_info,
522metadata,
523 RlibFlavor::StaticlibBase,
524tempdir,
525 );
526let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
527528let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
529let lto = are_upstream_rust_objects_already_included(sess)
530 && !ignored_for_lto(sess, crate_info, cnum);
531532let native_libs = crate_info.native_libraries[&cnum].iter();
533let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
534let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
535536let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
537ab.add_archive(
538path,
539 AddArchiveKind::Rlib(rmeta_link_cache, &|fname: &str, entry_kind| {
540// Ignore metadata and rmeta-link files.
541if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
542return true;
543 }
544545// Don't include Rust objects if LTO is enabled.
546if lto && entry_kind == ArchiveEntryKind::RustObj {
547return true;
548 }
549550// Skip objects for bundled libs.
551if bundled_libs.contains(&Symbol::intern(fname)) {
552return true;
553 }
554555false
556}),
557 )
558 .unwrap();
559560archive_builder_builder561 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
562 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
563564for filename in relevant_libs.iter() {
565let joined = tempdir.as_ref().join(filename.as_str());
566let path = joined.as_path();
567 ab.add_archive(path, AddArchiveKind::Other).unwrap();
568 }
569570all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
571 });
572if let Err(e) = res {
573sess.dcx().emit_fatal(e);
574 }
575576let hide = sess.opts.unstable_opts.staticlib_hide_internal_symbols;
577let rename = sess.opts.unstable_opts.staticlib_rename_internal_symbols;
578579let exported_symbols = if hide || rename {
580if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.binary_format {
BinaryFormat::Elf | BinaryFormat::MachO => true,
_ => false,
}matches!(sess.target.binary_format, BinaryFormat::Elf | BinaryFormat::MachO) {
581if hide {
582sess.dcx().emit_warn(errors::StaticlibHideInternalSymbolsUnsupported {
583 binary_format: sess.target.archive_format.to_string(),
584 });
585 }
586if rename {
587sess.dcx().emit_warn(errors::StaticlibRenameInternalSymbolsUnsupported {
588 binary_format: sess.target.archive_format.to_string(),
589 });
590 }
591None592 } else {
593crate_info594 .exported_symbols
595 .get(&CrateType::StaticLib)
596 .map(|symbols| symbols.iter().map(|(s, _)| s.clone()).collect())
597 }
598 } else {
599None600 };
601602let symbols = exported_symbols.map(|exported| ArchiveSymbols {
603exported,
604 rename_suffix: rename.then(|| crate_info.symbol_rename_suffix.clone()),
605hide,
606 });
607608ab.build(out_filename, symbols);
609610let crates = crate_info.used_crates.iter();
611612let fmts = crate_info613 .dependency_formats
614 .get(&CrateType::StaticLib)
615 .expect("no dependency formats for staticlib");
616617let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
618for &cnum in crates {
619let Some(Linkage::Dynamic) = fmts.get(cnum) else {
620continue;
621 };
622let crate_name = crate_info.crate_name[&cnum];
623let used_crate_source = &crate_info.used_crate_source[&cnum];
624if let Some(path) = &used_crate_source.dylib {
625 all_rust_dylibs.push(&**path);
626 } else if used_crate_source.rmeta.is_some() {
627 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
628 } else {
629 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
630 }
631 }
632633all_native_libs.extend_from_slice(&crate_info.used_libraries);
634635for print in &sess.opts.prints {
636if print.kind == PrintKind::NativeStaticLibs {
637 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
638 }
639 }
640}
641642/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
643/// DWARF package.
644fn link_dwarf_object(
645 sess: &Session,
646 compiled_modules: &CompiledModules,
647 crate_info: &CrateInfo,
648 executable_out_filename: &Path,
649) {
650let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
651dwp_out_filename.push(".dwp");
652{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:652",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(652u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["dwp_out_filename",
"executable_out_filename"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&dwp_out_filename)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&executable_out_filename)
as &dyn Value))])
});
} else { ; }
};debug!(?dwp_out_filename, ?executable_out_filename);
653654#[derive(#[automatically_derived]
impl<Relocations: ::core::default::Default> ::core::default::Default for
ThorinSession<Relocations> {
#[inline]
fn default() -> ThorinSession<Relocations> {
ThorinSession {
arena_data: ::core::default::Default::default(),
arena_mmap: ::core::default::Default::default(),
arena_relocations: ::core::default::Default::default(),
}
}
}Default)]
655struct ThorinSession<Relocations> {
656 arena_data: TypedArena<Vec<u8>>,
657 arena_mmap: TypedArena<Mmap>,
658 arena_relocations: TypedArena<Relocations>,
659 }
660661impl<Relocations> ThorinSession<Relocations> {
662fn alloc_mmap(&self, data: Mmap) -> &Mmap {
663&*self.arena_mmap.alloc(data)
664 }
665 }
666667impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
668fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
669&*self.arena_data.alloc(data)
670 }
671672fn alloc_relocation(&self, data: Relocations) -> &Relocations {
673&*self.arena_relocations.alloc(data)
674 }
675676fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
677let file = File::open(&path)?;
678let mmap = (unsafe { Mmap::map(file) })?;
679Ok(self.alloc_mmap(mmap))
680 }
681 }
682683match sess.time("run_thorin", || -> Result<(), thorin::Error> {
684let thorin_sess = ThorinSession::default();
685let mut package = thorin::DwarfPackage::new(&thorin_sess);
686687// Input objs contain .o/.dwo files from the current crate.
688match sess.opts.unstable_opts.split_dwarf_kind {
689 SplitDwarfKind::Single => {
690for m in &compiled_modules.modules {
691if let Some(input_obj) = &m.object {
692 package.add_input_object(input_obj)?;
693 }
694if let Some(input_obj) = &m.global_asm_object {
695 package.add_input_object(input_obj)?;
696 }
697 }
698 }
699 SplitDwarfKind::Split => {
700for input_obj in
701compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
702 {
703 package.add_input_object(input_obj)?;
704 }
705 }
706 }
707708// Input rlibs contain .o/.dwo files from dependencies.
709let input_rlibs = crate_info710 .used_crate_source
711 .items()
712 .filter_map(|(_, csource)| csource.rlib.as_ref())
713 .into_sorted_stable_ord();
714715for input_rlib in input_rlibs {
716{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:716",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(716u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["input_rlib"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&input_rlib)
as &dyn Value))])
});
} else { ; }
};debug!(?input_rlib);
717 package.add_input_object(input_rlib)?;
718 }
719720// Failing to read the referenced objects is expected for dependencies where the path in the
721 // executable will have been cleaned by Cargo, but the referenced objects will be contained
722 // within rlibs provided as inputs.
723 //
724 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
725 // found, but are provided explicitly above.
726 //
727 // Adding an executable is primarily done to make `thorin` check that all the referenced
728 // dwarf objects are found in the end.
729package.add_executable(
730 executable_out_filename,
731 thorin::MissingReferencedObjectBehaviour::Skip,
732 )?;
733734let output_stream = BufWriter::new(
735 OpenOptions::new()
736 .read(true)
737 .write(true)
738 .create(true)
739 .truncate(true)
740 .open(dwp_out_filename)?,
741 );
742let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
743 package.finish()?.emit(&mut output_stream)?;
744 output_stream.result()?;
745 output_stream.into_inner().flush()?;
746747Ok(())
748 }) {
749Ok(()) => {}
750Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
751 }
752}
753754#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for LinkerOutput
where G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
LinkerOutput { inner: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$inner}")));
;
diag.arg("inner", __binding_0);
diag
}
}
}
}
};Diagnostic)]
755#[diag("{$inner}")]
756/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
757/// end up with inconsistent languages within the same diagnostic.
758struct LinkerOutput {
759 inner: String,
760}
761762fn is_msvc_link_exe(sess: &Session) -> bool {
763let (linker_path, flavor) = linker_and_flavor(sess);
764sess.target.is_like_msvc
765 && flavor == LinkerFlavor::Msvc(Lld::No)
766// Match exactly "link.exe"
767&& linker_path.to_str() == Some("link.exe")
768}
769770fn is_macos_ld(sess: &Session) -> bool {
771let (_, flavor) = linker_and_flavor(sess);
772sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))773}
774775fn is_windows_gnu_ld(sess: &Session) -> bool {
776let (_, flavor) = linker_and_flavor(sess);
777sess.target.is_like_windows
778 && !sess.target.is_like_msvc
779 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))780 && sess.target.options.cfg_abi != CfgAbi::Llvm781}
782783fn is_windows_gnu_clang(sess: &Session) -> bool {
784let (_, flavor) = linker_and_flavor(sess);
785sess.target.is_like_windows
786 && !sess.target.is_like_msvc
787 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))788 && sess.target.options.cfg_abi == CfgAbi::Llvm789}
790791fn report_linker_output(
792 sess: &Session,
793 levels: CodegenLintLevelSpecs,
794 stdout: &[u8],
795 stderr: &[u8],
796) {
797let mut escaped_stderr = escape_string(&stderr);
798let mut escaped_stdout = escape_string(&stdout);
799let mut linker_info = String::new();
800801{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:801",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(801u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stderr:\n{0}",
&escaped_stderr) as &dyn Value))])
});
} else { ; }
};info!("linker stderr:\n{}", &escaped_stderr);
802{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:802",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(802u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stdout:\n{0}",
&escaped_stdout) as &dyn Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &escaped_stdout);
803804fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
805let mut output = String::new();
806if let Ok(str) = str::from_utf8(bytes) {
807{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:807",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(807u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("line: {0}",
str) as &dyn Value))])
});
} else { ; }
};info!("line: {str}");
808output = String::with_capacity(str.len());
809for line in str.lines() {
810 f(line.trim(), &mut output);
811 }
812 }
813escape_string(output.trim().as_bytes())
814 }
815816if is_msvc_link_exe(sess) {
817{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:817",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(817u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred MSVC link.exe")
as &dyn Value))])
});
} else { ; }
};info!("inferred MSVC link.exe");
818819escaped_stdout = for_each(&stdout, |line, output| {
820// Hide some progress messages from link.exe that we don't care about.
821 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
822 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
823 // missing, link.exe prints the path of the missing .exe followed by:
824let ilk_but_no_exe =
825"not found or not built by the last incremental link; performing full link";
826let trimmed = line.trim_start();
827if trimmed.starts_with("Creating library")
828 || trimmed.starts_with("Generating code")
829 || trimmed.starts_with("Finished generating code")
830 || trimmed.ends_with(ilk_but_no_exe)
831 {
832linker_info += line;
833linker_info += "\r\n";
834 } else {
835*output += line;
836*output += "\r\n"
837}
838 });
839 } else if is_macos_ld(sess) {
840{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:840",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(840u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred macOS LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred macOS LD");
841842// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
843let deployment_mismatch = |line: &str| {
844// ld64 (object files + dylibs) and ld_prime (object files only):
845(line.starts_with("ld: ")
846 && line.contains("was built for newer")
847 && line.contains("than being linked"))
848// ld_prime (Xcode 15+, dylibs only):
849|| (line.starts_with("ld: ")
850 && line.contains("building for")
851 && line.contains("but linking with")
852 && line.contains("which was built for newer version"))
853 };
854// FIXME: This is a real warning we would like to show, but it hits too many crates
855 // to want to turn it on immediately.
856let search_path = |line: &str| {
857line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
858 };
859escaped_stderr = for_each(&stderr, |line, output| {
860// This duplicate library warning is just not helpful at all.
861if line.starts_with("ld: warning: ignoring duplicate libraries: ")
862 || deployment_mismatch(line)
863 || search_path(line)
864 {
865linker_info += line;
866linker_info += "\n";
867 } else {
868*output += line;
869*output += "\n"
870}
871 });
872 } else if is_windows_gnu_ld(sess) {
873{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:873",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(873u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows GNU LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows GNU LD");
874875let mut saw_exclude_symbol = false;
876// See https://github.com/rust-lang/rust/issues/112368.
877 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
878let exclude_symbols = |line: &str| {
879line.starts_with("Warning: .drectve `-exclude-symbols:")
880 && line.ends_with("' unrecognized")
881 };
882escaped_stderr = for_each(&stderr, |line, output| {
883if exclude_symbols(line) {
884saw_exclude_symbol = true;
885linker_info += line;
886linker_info += "\n";
887 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
888linker_info += line;
889linker_info += "\n";
890 } else {
891*output += line;
892*output += "\n"
893}
894 });
895 } else if is_windows_gnu_clang(sess) {
896{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:896",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(896u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows Clang (GNU ABI)")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows Clang (GNU ABI)");
897escaped_stderr = for_each(&stderr, |line, output| {
898if line.contains("argument unused during compilation: '-nolibc'") {
899linker_info += line;
900linker_info += "\n";
901 } else {
902*output += line;
903*output += "\n"
904}
905 });
906 };
907908let lint_msg = |msg| {
909emit_lint_base(
910sess,
911LINKER_MESSAGES,
912levels.linker_messages,
913None,
914LinkerOutput { inner: msg },
915 );
916 };
917let lint_info = |msg| {
918emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
919 };
920921if !escaped_stderr.is_empty() {
922// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
923escaped_stderr =
924escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
925// Windows GNU LD prints uppercase Warning
926escaped_stderr = escaped_stderr927 .strip_prefix("Warning: ")
928 .unwrap_or(&escaped_stderr)
929 .replace(": warning: ", ": ");
930lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
931 }
932if !escaped_stdout.is_empty() {
933lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
934 }
935if !linker_info.is_empty() {
936lint_info(linker_info);
937 }
938}
939940/// Create a dynamic library or executable.
941///
942/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
943/// files as well.
944fn link_natively(
945 sess: &Session,
946 archive_builder_builder: &dyn ArchiveBuilderBuilder,
947 rmeta_link_cache: &mut RmetaLinkCache,
948 crate_type: CrateType,
949 out_filename: &Path,
950 compiled_modules: &CompiledModules,
951 crate_info: &CrateInfo,
952 metadata: &EncodedMetadata,
953 tmpdir: &Path,
954 codegen_backend: &'static str,
955) {
956{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:956",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(956u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing {0:?} to {1:?}",
crate_type, out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
957let (linker_path, flavor) = linker_and_flavor(sess);
958let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
959960// On AIX, we ship all libraries as .a big_af archive
961 // the expected format is lib<name>.a(libname.so) for the actual
962 // dynamic library. So we link to a temporary .so file to be archived
963 // at the final out_filename location
964let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
965let archive_member =
966should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
967let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
968969let mut cmd = linker_with_args(
970&linker_path,
971flavor,
972sess,
973archive_builder_builder,
974rmeta_link_cache,
975crate_type,
976tmpdir,
977temp_filename,
978compiled_modules,
979crate_info,
980metadata,
981self_contained_components,
982codegen_backend,
983 );
984985 linker::disable_localization(&mut cmd);
986987for (k, v) in sess.target.link_env.as_ref() {
988 cmd.env(k.as_ref(), v.as_ref());
989 }
990for k in sess.target.link_env_remove.as_ref() {
991 cmd.env_remove(k.as_ref());
992 }
993994for print in &sess.opts.prints {
995if print.kind == PrintKind::LinkArgs {
996let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
997 print.out.overwrite(&content, sess);
998 }
999 }
10001001// May have not found libraries in the right formats.
1002sess.dcx().abort_if_errors();
10031004// Invoke the system linker
1005{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1005",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1005u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1006let unknown_arg_regex =
1007Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
1008let mut prog;
1009loop {
1010prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
1011let Ok(ref output) = progelse {
1012break;
1013 };
1014if output.status.success() {
1015break;
1016 }
1017let mut out = output.stderr.clone();
1018out.extend(&output.stdout);
1019let out = String::from_utf8_lossy(&out);
10201021// Check to see if the link failed with an error message that indicates it
1022 // doesn't recognize the -no-pie option. If so, re-perform the link step
1023 // without it. This is safe because if the linker doesn't support -no-pie
1024 // then it should not default to linking executables as pie. Different
1025 // versions of gcc seem to use different quotes in the error message so
1026 // don't check for them.
1027if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1028 && unknown_arg_regex.is_match(&out)
1029 && out.contains("-no-pie")
1030 && cmd.get_args().iter().any(|e| e == "-no-pie")
1031 {
1032{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1032",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1032u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1033{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1033",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1033u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Linker does not support -no-pie command line option. Retrying without.")
as &dyn Value))])
});
} else { ; }
};warn!("Linker does not support -no-pie command line option. Retrying without.");
1034for arg in cmd.take_args() {
1035if arg != "-no-pie" {
1036 cmd.arg(arg);
1037 }
1038 }
1039{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1039",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1039u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1040continue;
1041 }
10421043// Check if linking failed with an error message that indicates the driver didn't recognize
1044 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1045 // to spawn multiple instances on the happy path to do version checking, and ensures things
1046 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1047 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1048if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1049 && unknown_arg_regex.is_match(&out)
1050 && out.contains("-fuse-ld=lld")
1051 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
1052 {
1053{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1053",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1053u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1054{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1054",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1054u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.")
as &dyn Value))])
});
} else { ; }
};info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
1055for arg in cmd.take_args() {
1056if arg.to_string_lossy() != "-fuse-ld=lld" {
1057 cmd.arg(arg);
1058 }
1059 }
1060{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1060",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1060u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1061continue;
1062 }
10631064// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1065 // Fallback from '-static-pie' to '-static' in that case.
1066if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1067 && unknown_arg_regex.is_match(&out)
1068 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1069 && cmd.get_args().iter().any(|e| e == "-static-pie")
1070 {
1071{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1071",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1071u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1072{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1072",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1072u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Linker does not support -static-pie command line option. Retrying with -static instead.")
as &dyn Value))])
});
} else { ; }
};warn!(
1073"Linker does not support -static-pie command line option. Retrying with -static instead."
1074);
1075// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1076let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1077let opts = &sess.target;
1078let pre_objects = if self_contained_crt_objects {
1079&opts.pre_link_objects_self_contained
1080 } else {
1081&opts.pre_link_objects
1082 };
1083let post_objects = if self_contained_crt_objects {
1084&opts.post_link_objects_self_contained
1085 } else {
1086&opts.post_link_objects
1087 };
1088let get_objects = |objects: &CrtObjects, kind| {
1089objects1090 .get(&kind)
1091 .iter()
1092 .copied()
1093 .flatten()
1094 .map(|obj| {
1095get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1096 })
1097 .collect::<Vec<_>>()
1098 };
1099let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1100let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1101let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1102let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1103// Assume that we know insertion positions for the replacement arguments from replaced
1104 // arguments, which is true for all supported targets.
1105if !(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty()) {
::core::panicking::panic("assertion failed: pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty()")
};assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
1106if !(post_objects_static.is_empty() || !post_objects_static_pie.is_empty()) {
::core::panicking::panic("assertion failed: post_objects_static.is_empty() || !post_objects_static_pie.is_empty()")
};assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
1107for arg in cmd.take_args() {
1108if arg == "-static-pie" {
1109// Replace the output kind.
1110cmd.arg("-static");
1111 } else if pre_objects_static_pie.contains(&arg) {
1112// Replace the pre-link objects (replace the first and remove the rest).
1113cmd.args(mem::take(&mut pre_objects_static));
1114 } else if post_objects_static_pie.contains(&arg) {
1115// Replace the post-link objects (replace the first and remove the rest).
1116cmd.args(mem::take(&mut post_objects_static));
1117 } else {
1118 cmd.arg(arg);
1119 }
1120 }
1121{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1121",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1121u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1122continue;
1123 }
11241125break;
1126 }
11271128match prog {
1129Ok(prog) => {
1130if !prog.status.success() {
1131let mut output = prog.stderr.clone();
1132output.extend_from_slice(&prog.stdout);
1133let escaped_output = escape_linker_output(&output, flavor);
1134let err = errors::LinkingFailed {
1135 linker_path: &linker_path,
1136 exit_status: prog.status,
1137 command: cmd,
1138escaped_output,
1139 verbose: sess.opts.verbose,
1140 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1141 };
1142sess.dcx().emit_err(err);
1143// If MSVC's `link.exe` was expected but the return code
1144 // is not a Microsoft LNK error then suggest a way to fix or
1145 // install the Visual Studio build tools.
1146if let Some(code) = prog.status.code() {
1147// All Microsoft `link.exe` linking ror codes are
1148 // four digit numbers in the range 1000 to 9999 inclusive
1149if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1150let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1151let has_linker =
1152 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1153 .is_some();
11541155sess.dcx().emit_note(errors::LinkExeUnexpectedError);
11561157// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1158 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1159const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1160if code == STATUS_STACK_BUFFER_OVERRUN {
1161sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1162 }
11631164if is_vs_installed && has_linker {
1165// the linker is broken
1166sess.dcx().emit_note(errors::RepairVSBuildTools);
1167sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1168 } else if is_vs_installed {
1169// the linker is not installed
1170sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1171 } else {
1172// visual studio is not installed
1173sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1174 }
1175 }
1176 }
11771178sess.dcx().abort_if_errors();
1179 }
11801181{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1181",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1181u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("reporting linker output: flavor={0:?}",
flavor) as &dyn Value))])
});
} else { ; }
};info!("reporting linker output: flavor={flavor:?}");
1182report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1183 }
1184Err(e) => {
1185let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11861187let err = if linker_not_found {
1188sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1189 } else {
1190sess.dcx().emit_err(errors::UnableToExeLinker {
1191linker_path,
1192 error: e,
1193 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1194 })
1195 };
11961197if sess.target.is_like_msvc && linker_not_found {
1198sess.dcx().emit_note(errors::MsvcMissingLinker);
1199sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1200sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1201 }
1202err.raise_fatal();
1203 }
1204 }
12051206match sess.split_debuginfo() {
1207// If split debug information is disabled or located in individual files
1208 // there's nothing to do here.
1209SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
12101211// If packed split-debuginfo is requested, but the final compilation
1212 // doesn't actually have any debug information, then we skip this step.
1213SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
12141215// On macOS the external `dsymutil` tool is used to create the packed
1216 // debug information. Note that this will read debug information from
1217 // the objects on the filesystem which we'll clean up later.
1218SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1219let prog = Command::new("dsymutil").arg(out_filename).output();
1220match prog {
1221Ok(prog) => {
1222if !prog.status.success() {
1223let mut output = prog.stderr.clone();
1224output.extend_from_slice(&prog.stdout);
1225sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1226 status: prog.status,
1227 output: escape_string(&output),
1228 });
1229 }
1230 }
1231Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1232 }
1233 }
12341235// On MSVC packed debug information is produced by the linker itself so
1236 // there's no need to do anything else here.
1237SplitDebuginfo::Packedif sess.target.is_like_windows => {}
12381239// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1240 //
1241 // We cannot rely on the .o paths in the executable because they may have been
1242 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1243 // the .o/.dwo paths explicitly.
1244SplitDebuginfo::Packed => {
1245link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1246 }
1247 }
12481249let strip = sess.opts.cg.strip;
12501251if sess.target.is_like_darwin {
1252let stripcmd = "rust-objcopy";
1253match (strip, crate_type) {
1254 (Strip::Debuginfo, _) => {
1255strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1256 }
12571258// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1259(
1260 Strip::Symbols,
1261 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1262 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1263 (Strip::Symbols, _) => {
1264strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1265 }
1266 (Strip::None, _) => {}
1267 }
1268 }
12691270if sess.target.is_like_solaris {
1271// Many illumos systems will have both the native 'strip' utility and
1272 // the GNU one. Use the native version explicitly and do not rely on
1273 // what's in the path.
1274 //
1275 // If cross-compiling and there is not a native version, then use
1276 // `llvm-strip` and hope.
1277let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1278match strip {
1279// Always preserve the symbol table (-x).
1280Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1281// Strip::Symbols is handled via the --strip-all linker option.
1282Strip::Symbols => {}
1283 Strip::None => {}
1284 }
1285 }
12861287if sess.target.is_like_aix {
1288// `llvm-strip` doesn't work for AIX - their strip must be used.
1289if !sess.host.is_like_aix {
1290sess.dcx().emit_warn(errors::AixStripNotUsed);
1291 }
1292let stripcmd = "/usr/bin/strip";
1293match strip {
1294 Strip::Debuginfo => {
1295// FIXME: AIX's strip utility only offers option to strip line number information.
1296strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1297 }
1298 Strip::Symbols => {
1299// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1300strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1301 }
1302 Strip::None => {}
1303 }
1304 }
13051306if should_archive {
1307let mut ab = archive_builder_builder.new_archive_builder(sess);
1308ab.add_file(temp_filename, ArchiveEntryKind::Other);
1309ab.build(out_filename, None);
1310 }
1311}
13121313fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1314let mut cmd = Command::new(util);
1315cmd.args(options);
13161317let mut new_path = sess.get_tools_search_paths(false);
1318if let Some(path) = env::var_os("PATH") {
1319new_path.extend(env::split_paths(&path));
1320 }
1321cmd.env("PATH", env::join_paths(new_path).unwrap());
13221323let prog = cmd.arg(out_filename).output();
1324match prog {
1325Ok(prog) => {
1326if !prog.status.success() {
1327let mut output = prog.stderr.clone();
1328output.extend_from_slice(&prog.stdout);
1329sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1330util,
1331 status: prog.status,
1332 output: escape_string(&output),
1333 });
1334 }
1335 }
1336Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1337 }
1338}
13391340fn escape_string(s: &[u8]) -> String {
1341match str::from_utf8(s) {
1342Ok(s) => s.to_owned(),
1343Err(_) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Non-UTF-8 output: {0}",
s.escape_ascii()))
})format!("Non-UTF-8 output: {}", s.escape_ascii()),
1344 }
1345}
13461347#[cfg(not(windows))]
1348fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1349escape_string(s)
1350}
13511352/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1353/// then try to convert the string from the OEM encoding.
1354#[cfg(windows)]
1355fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1356// This only applies to the actual MSVC linker.
1357if flavour != LinkerFlavor::Msvc(Lld::No) {
1358return escape_string(s);
1359 }
1360match str::from_utf8(s) {
1361Ok(s) => return s.to_owned(),
1362Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1363Some(s) => s,
1364// The string is not UTF-8 and isn't valid for the OEM code page
1365None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1366 },
1367 }
1368}
13691370/// Wrappers around the Windows API.
1371#[cfg(windows)]
1372mod win {
1373use windows::Win32::Globalization::{
1374 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1375 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1376 };
13771378/// Get the Windows system OEM code page. This is most notably the code page
1379 /// used for link.exe's output.
1380pub(super) fn oem_code_page() -> u32 {
1381unsafe {
1382let mut cp: u32 = 0;
1383// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1384 // But the API requires us to pass the data as though it's a [u16] string.
1385let len = size_of::<u32>() / size_of::<u16>();
1386let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1387let len_written = GetLocaleInfoEx(
1388 LOCALE_NAME_SYSTEM_DEFAULT,
1389 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1390Some(data),
1391 );
1392if len_written as usize == len { cp } else { CP_OEMCP }
1393 }
1394 }
1395/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1396 /// The string does not need to be null terminated.
1397 ///
1398 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1399 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1400 ///
1401 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1402 /// any invalid bytes for the expected encoding.
1403pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1404// `MultiByteToWideChar` requires a length to be a "positive integer".
1405if s.len() > isize::MAX as usize {
1406return None;
1407 }
1408// Error if the string is not valid for the expected code page.
1409let flags = MB_ERR_INVALID_CHARS;
1410// Call MultiByteToWideChar twice.
1411 // First to calculate the length then to convert the string.
1412let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1413if len > 0 {
1414let mut utf16 = vec![0; len as usize];
1415 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1416if len > 0 {
1417return utf16.get(..len as usize).map(String::from_utf16_lossy);
1418 }
1419 }
1420None
1421}
1422}
14231424fn add_sanitizer_libraries(
1425 sess: &Session,
1426 flavor: LinkerFlavor,
1427 crate_type: CrateType,
1428 linker: &mut dyn Linker,
1429) {
1430if sess.target.is_like_android {
1431// Sanitizer runtime libraries are provided dynamically on Android
1432 // targets.
1433return;
1434 }
14351436if sess.opts.unstable_opts.external_clangrt {
1437// Linking against in-tree sanitizer runtimes is disabled via
1438 // `-Z external-clangrt`
1439return;
1440 }
14411442if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1443return;
1444 }
14451446// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1447 // which should be linked to both executables and dynamic libraries.
1448 // Everywhere else the runtimes are currently distributed as static
1449 // libraries which should be linked to executables only.
1450if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1451 crate_type,
1452 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1453 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1454 {
1455return;
1456 }
14571458let sanitizer = sess.sanitizers();
1459if sanitizer.contains(SanitizerSet::ADDRESS) {
1460link_sanitizer_runtime(sess, flavor, linker, "asan");
1461 }
1462if sanitizer.contains(SanitizerSet::DATAFLOW) {
1463link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1464 }
1465if sanitizer.contains(SanitizerSet::LEAK)
1466 && !sanitizer.contains(SanitizerSet::ADDRESS)
1467 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1468 {
1469link_sanitizer_runtime(sess, flavor, linker, "lsan");
1470 }
1471if sanitizer.contains(SanitizerSet::MEMORY) {
1472link_sanitizer_runtime(sess, flavor, linker, "msan");
1473 }
1474if sanitizer.contains(SanitizerSet::THREAD) {
1475link_sanitizer_runtime(sess, flavor, linker, "tsan");
1476 }
1477if sanitizer.contains(SanitizerSet::HWADDRESS) {
1478link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1479 }
1480if sanitizer.contains(SanitizerSet::SAFESTACK) {
1481link_sanitizer_runtime(sess, flavor, linker, "safestack");
1482 }
1483if sanitizer.contains(SanitizerSet::REALTIME) {
1484link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1485 }
1486}
14871488fn link_sanitizer_runtime(
1489 sess: &Session,
1490 flavor: LinkerFlavor,
1491 linker: &mut dyn Linker,
1492 name: &str,
1493) {
1494fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1495let path = sess.target_tlib_path.dir.join(filename);
1496if path.exists() {
1497sess.target_tlib_path.dir.clone()
1498 } else {
1499 filesearch::make_target_lib_path(
1500&sess.opts.sysroot.default,
1501sess.opts.target_triple.tuple(),
1502 )
1503 }
1504 }
15051506let channel =
1507::core::option::Option::Some("nightly")option_env!("CFG_RELEASE_CHANNEL").map(|channel| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-{0}", channel))
})format!("-{channel}")).unwrap_or_default();
15081509if sess.target.is_like_darwin {
1510// On Apple platforms, the sanitizer is always built as a dylib, and
1511 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1512 // rpath to the library as well (the rpath should be absolute, see
1513 // PR #41352 for details).
1514let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1515let path = find_sanitizer_runtime(sess, &filename);
1516let rpath = path.to_str().expect("non-utf8 component in path");
1517linker.link_args(&["-rpath", rpath]);
1518linker.link_dylib_by_name(&filename, false, true);
1519 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1520// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1521 // compatible ASAN library.
1522linker.link_arg("/INFERASANLIBS");
1523 } else {
1524let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1525let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1526linker.link_staticlib_by_path(&path, true);
1527 }
1528}
15291530/// Returns a boolean indicating whether the specified crate should be ignored
1531/// during LTO.
1532///
1533/// Crates ignored during LTO are not lumped together in the "massive object
1534/// file" that we create and are linked in their normal rlib states. See
1535/// comments below for what crates do not participate in LTO.
1536///
1537/// It's unusual for a crate to not participate in LTO. Typically only
1538/// compiler-specific and unstable crates have a reason to not participate in
1539/// LTO.
1540pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1541// If our target enables builtin function lowering in LLVM then the
1542 // crates providing these functions don't participate in LTO (e.g.
1543 // no_builtins or compiler builtins crates).
1544!sess.target.no_builtins
1545 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1546}
15471548/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1549pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1550fn infer_from(
1551 sess: &Session,
1552 linker: Option<PathBuf>,
1553 flavor: Option<LinkerFlavor>,
1554 features: LinkerFeaturesCli,
1555 ) -> Option<(PathBuf, LinkerFlavor)> {
1556let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1557match (linker, flavor) {
1558 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1559// only the linker flavor is known; use the default linker for the selected flavor
1560(None, Some(flavor)) => Some((
1561PathBuf::from(match flavor {
1562 LinkerFlavor::Gnu(Cc::Yes, _)
1563 | LinkerFlavor::Darwin(Cc::Yes, _)
1564 | LinkerFlavor::WasmLld(Cc::Yes)
1565 | LinkerFlavor::Unix(Cc::Yes) => {
1566if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1567// On historical Solaris systems, "cc" may have
1568 // been Sun Studio, which is not flag-compatible
1569 // with "gcc". This history casts a long shadow,
1570 // and many modern illumos distributions today
1571 // ship GCC as "gcc" without also making it
1572 // available as "cc".
1573"gcc"
1574} else {
1575"cc"
1576}
1577 }
1578 LinkerFlavor::Gnu(_, Lld::Yes)
1579 | LinkerFlavor::Darwin(_, Lld::Yes)
1580 | LinkerFlavor::WasmLld(..)
1581 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1582 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1583"ld"
1584}
1585 LinkerFlavor::Msvc(..) => "link.exe",
1586 LinkerFlavor::EmCc => {
1587if falsecfg!(windows) {
1588"emcc.bat"
1589} else {
1590"emcc"
1591}
1592 }
1593 LinkerFlavor::Bpf => "bpf-linker",
1594 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1595 }),
1596flavor,
1597 )),
1598 (Some(linker), None) => {
1599let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1600sess.dcx().emit_fatal(errors::LinkerFileStem);
1601 });
1602let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1603let flavor = adjust_flavor_to_features(flavor, features);
1604Some((linker, flavor))
1605 }
1606 (None, None) => None,
1607 }
1608 }
16091610// While linker flavors and linker features are isomorphic (and thus targets don't need to
1611 // define features separately), we use the flavor as the root piece of data and have the
1612 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1613 // both yet.
1614fn adjust_flavor_to_features(
1615 flavor: LinkerFlavor,
1616 features: LinkerFeaturesCli,
1617 ) -> LinkerFlavor {
1618// Note: a linker feature cannot be both enabled and disabled on the CLI.
1619if features.enabled.contains(LinkerFeatures::LLD) {
1620flavor.with_lld_enabled()
1621 } else if features.disabled.contains(LinkerFeatures::LLD) {
1622flavor.with_lld_disabled()
1623 } else {
1624flavor1625 }
1626 }
16271628let features = sess.opts.cg.linker_features;
16291630// linker and linker flavor specified via command line have precedence over what the target
1631 // specification specifies
1632let linker_flavor = match sess.opts.cg.linker_flavor {
1633// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1634Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1635// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1636linker_flavor => {
1637linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1638 }
1639 };
1640if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1641return ret;
1642 }
16431644if let Some(ret) = infer_from(
1645sess,
1646sess.target.linker.as_deref().map(PathBuf::from),
1647Some(sess.target.linker_flavor),
1648features,
1649 ) {
1650return ret;
1651 }
16521653::rustc_middle::util::bug::bug_fmt(format_args!("Not enough information provided to determine how to invoke the linker"));bug!("Not enough information provided to determine how to invoke the linker");
1654}
16551656/// Returns a pair of boolean indicating whether we should preserve the object and
1657/// dwarf object files on the filesystem for their debug information. This is often
1658/// useful with split-dwarf like schemes.
1659fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1660// If the objects don't have debuginfo there's nothing to preserve.
1661if sess.opts.debuginfo == config::DebugInfo::None {
1662return (false, false);
1663 }
16641665match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1666// If there is no split debuginfo then do not preserve objects.
1667(SplitDebuginfo::Off, _) => (false, false),
1668// If there is packed split debuginfo, then the debuginfo in the objects
1669 // has been packaged and the objects can be deleted.
1670(SplitDebuginfo::Packed, _) => (false, false),
1671// If there is unpacked split debuginfo and the current target can not use
1672 // split dwarf, then keep objects.
1673(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1674// If there is unpacked split debuginfo and the target can use split dwarf, then
1675 // keep the object containing that debuginfo (whether that is an object file or
1676 // dwarf object file depends on the split dwarf kind).
1677(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1678 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1679 }
1680}
16811682#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for RlibFlavor {
#[inline]
fn eq(&self, other: &RlibFlavor) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1683enum RlibFlavor {
1684 Normal,
1685 StaticlibBase,
1686}
16871688fn print_native_static_libs(
1689 sess: &Session,
1690 out: &OutFileName,
1691 all_native_libs: &[NativeLib],
1692 all_rust_dylibs: &[&Path],
1693) {
1694let mut lib_args: Vec<_> = all_native_libs1695 .iter()
1696 .filter(|l| relevant_lib(sess, l))
1697 .filter_map(|lib| {
1698let name = lib.name;
1699match lib.kind {
1700 NativeLibKind::Static { bundle: Some(false), .. }
1701 | NativeLibKind::Dylib { .. }
1702 | NativeLibKind::Unspecified => {
1703let verbatim = lib.verbatim;
1704if sess.target.is_like_msvc {
1705let (prefix, suffix) = sess.staticlib_components(verbatim);
1706Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1707 } else if sess.target.linker_flavor.is_gnu() {
1708Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1709 } else {
1710Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1711 }
1712 }
1713 NativeLibKind::Framework { .. } => {
1714// ld-only syntax, since there are no frameworks in MSVC
1715Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1716 }
1717// These are included, no need to print them
1718NativeLibKind::Static { bundle: None | Some(true), .. }
1719 | NativeLibKind::LinkArg1720 | NativeLibKind::WasmImportModule1721 | NativeLibKind::RawDylib { .. } => None,
1722 }
1723 })
1724// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1725.dedup()
1726 .collect();
1727for path in all_rust_dylibs {
1728// FIXME deduplicate with add_dynamic_crate
17291730 // Just need to tell the linker about where the library lives and
1731 // what its name is
1732let parent = path.parent();
1733if let Some(dir) = parent {
1734let dir = fix_windows_verbatim_for_gcc(dir);
1735if sess.target.is_like_msvc {
1736let mut arg = String::from("/LIBPATH:");
1737 arg.push_str(&dir.display().to_string());
1738 lib_args.push(arg);
1739 } else {
1740 lib_args.push("-L".to_owned());
1741 lib_args.push(dir.display().to_string());
1742 }
1743 }
1744let stem = path.file_stem().unwrap().to_str().unwrap();
1745// Convert library file-stem into a cc -l argument.
1746let lib = if let Some(lib) = stem.strip_prefix("lib")
1747 && !sess.target.is_like_windows
1748 {
1749 lib
1750 } else {
1751 stem
1752 };
1753let path = parent.unwrap_or_else(|| Path::new(""));
1754if sess.target.is_like_msvc {
1755// When producing a dll, the MSVC linker may not actually emit a
1756 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1757 // check to see if the file is there and just omit linking to it if it's
1758 // not present.
1759let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1760if path.join(&name).exists() {
1761 lib_args.push(name);
1762 }
1763 } else {
1764 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1765 }
1766 }
17671768match out {
1769 OutFileName::Real(path) => {
1770out.overwrite(&lib_args.join(" "), sess);
1771sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1772 }
1773 OutFileName::Stdout => {
1774sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1775// Prefix for greppability
1776 // Note: This must not be translated as tools are allowed to depend on this exact string.
1777sess.dcx().note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("native-static-libs: {0}",
lib_args.join(" ")))
})format!("native-static-libs: {}", lib_args.join(" ")));
1778 }
1779 }
1780}
17811782fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1783let file_path = sess.target_tlib_path.dir.join(name);
1784if file_path.exists() {
1785return file_path;
1786 }
1787// Special directory with objects used only in self-contained linkage mode
1788if self_contained {
1789let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1790if file_path.exists() {
1791return file_path;
1792 }
1793 }
1794for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1795let file_path = search_path.dir.join(name);
1796if file_path.exists() {
1797return file_path;
1798 }
1799 }
1800PathBuf::from(name)
1801}
18021803fn exec_linker(
1804 sess: &Session,
1805 cmd: &Command,
1806 out_filename: &Path,
1807 flavor: LinkerFlavor,
1808 tmpdir: &Path,
1809) -> io::Result<Output> {
1810// When attempting to spawn the linker we run a risk of blowing out the
1811 // size limits for spawning a new process with respect to the arguments
1812 // we pass on the command line.
1813 //
1814 // Here we attempt to handle errors from the OS saying "your list of
1815 // arguments is too big" by reinvoking the linker again with an `@`-file
1816 // that contains all the arguments (aka 'response' files).
1817 // The theory is that this is then accepted on all linkers and the linker
1818 // will read all its options out of there instead of looking at the command line.
1819if !cmd.very_likely_to_exceed_some_spawn_limit() {
1820match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1821Ok(child) => {
1822let output = child.wait_with_output();
1823 flush_linked_file(&output, out_filename)?;
1824return output;
1825 }
1826Err(ref e) if command_line_too_big(e) => {
1827{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1827",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1827u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("command line to linker was too big: {0}",
e) as &dyn Value))])
});
} else { ; }
};info!("command line to linker was too big: {}", e);
1828 }
1829Err(e) => return Err(e),
1830 }
1831 }
18321833{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1833",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1833u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("falling back to passing arguments to linker via an @-file")
as &dyn Value))])
});
} else { ; }
};info!("falling back to passing arguments to linker via an @-file");
1834let mut cmd2 = cmd.clone();
1835let mut args = String::new();
1836for arg in cmd2.take_args() {
1837 args.push_str(
1838&Escape {
1839 arg: arg.to_str().unwrap(),
1840// Windows-style escaping for @-files is used by
1841 // - all linkers targeting MSVC-like targets, including LLD
1842 // - all LLD flavors running on Windows hosts
1843 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1844is_like_msvc: sess.target.is_like_msvc
1845 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1846 }
1847 .to_string(),
1848 );
1849 args.push('\n');
1850 }
1851let file = tmpdir.join("linker-arguments");
1852let bytes = if sess.target.is_like_msvc {
1853let mut out = Vec::with_capacity((1 + args.len()) * 2);
1854// start the stream with a UTF-16 BOM
1855for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1856// encode in little endian
1857out.push(c as u8);
1858 out.push((c >> 8) as u8);
1859 }
1860out1861 } else {
1862args.into_bytes()
1863 };
1864 fs::write(&file, &bytes)?;
1865cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1866{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1866",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1866u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoking linker {0:?}",
cmd2) as &dyn Value))])
});
} else { ; }
};info!("invoking linker {:?}", cmd2);
1867let output = cmd2.output();
1868 flush_linked_file(&output, out_filename)?;
1869return output;
18701871#[cfg(not(windows))]
1872fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1873Ok(())
1874 }
18751876#[cfg(windows)]
1877fn flush_linked_file(
1878 command_output: &io::Result<Output>,
1879 out_filename: &Path,
1880 ) -> io::Result<()> {
1881// On Windows, under high I/O load, output buffers are sometimes not flushed,
1882 // even long after process exit, causing nasty, non-reproducible output bugs.
1883 //
1884 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1885 //
1886 // А full writeup of the original Chrome bug can be found at
1887 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18881889if let &Ok(ref out) = command_output {
1890if out.status.success() {
1891if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1892 of.sync_all()?;
1893 }
1894 }
1895 }
18961897Ok(())
1898 }
18991900#[cfg(unix)]
1901fn command_line_too_big(err: &io::Error) -> bool {
1902err.raw_os_error() == Some(::libc::E2BIG)
1903 }
19041905#[cfg(windows)]
1906fn command_line_too_big(err: &io::Error) -> bool {
1907const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1908 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1909 }
19101911#[cfg(not(any(unix, windows)))]
1912fn command_line_too_big(_: &io::Error) -> bool {
1913false
1914}
19151916struct Escape<'a> {
1917 arg: &'a str,
1918 is_like_msvc: bool,
1919 }
19201921impl<'a> fmt::Displayfor Escape<'a> {
1922fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1923if self.is_like_msvc {
1924// This is "documented" at
1925 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1926 //
1927 // Unfortunately there's not a great specification of the
1928 // syntax I could find online (at least) but some local
1929 // testing showed that this seemed sufficient-ish to catch
1930 // at least a few edge cases.
1931f.write_fmt(format_args!("\""))write!(f, "\"")?;
1932for c in self.arg.chars() {
1933match c {
1934'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1935 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1936 }
1937 }
1938f.write_fmt(format_args!("\""))write!(f, "\"")?;
1939 } else {
1940// This is documented at https://linux.die.net/man/1/ld, namely:
1941 //
1942 // > Options in file are separated by whitespace. A whitespace
1943 // > character may be included in an option by surrounding the
1944 // > entire option in either single or double quotes. Any
1945 // > character (including a backslash) may be included by
1946 // > prefixing the character to be included with a backslash.
1947 //
1948 // We put an argument on each line, so all we need to do is
1949 // ensure the line is interpreted as one whole argument.
1950for c in self.arg.chars() {
1951match c {
1952'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1953 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1954 }
1955 }
1956 }
1957Ok(())
1958 }
1959 }
1960}
19611962fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1963let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1964 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1965 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1966 LinkOutputKind::DynamicPicExe1967 }
1968 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1969 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1970 LinkOutputKind::StaticPicExe1971 }
1972 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1973 (_, true, _) => LinkOutputKind::StaticDylib,
1974 (_, false, _) => LinkOutputKind::DynamicDylib,
1975 };
19761977// Adjust the output kind to target capabilities.
1978let opts = &sess.target;
1979let pic_exe_supported = opts.position_independent_executables;
1980let static_pic_exe_supported = opts.static_position_independent_executables;
1981let static_dylib_supported = opts.crt_static_allows_dylibs;
1982match kind {
1983 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1984 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1985 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1986_ => kind,
1987 }
1988}
19891990// Returns true if linker is located within sysroot
1991fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1992let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1993linker.with_extension("exe")
1994 } else {
1995linker.to_path_buf()
1996 };
1997for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1998let full_path = dir.join(&linker_with_extension);
1999// If linker comes from sysroot assume self-contained mode
2000if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
2001return false;
2002 }
2003 }
2004true
2005}
20062007/// Various toolchain components used during linking are used from rustc distribution
2008/// instead of being found somewhere on the host system.
2009/// We only provide such support for a very limited number of targets.
2010fn self_contained_components(
2011 sess: &Session,
2012 crate_type: CrateType,
2013 linker: &Path,
2014) -> LinkSelfContainedComponents {
2015// Turn the backwards compatible bool values for `self_contained` into fully inferred
2016 // `LinkSelfContainedComponents`.
2017let self_contained =
2018if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
2019// Emit an error if the user requested self-contained mode on the CLI but the target
2020 // explicitly refuses it.
2021if sess.target.link_self_contained.is_disabled() {
2022sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
2023 }
2024self_contained2025 } else {
2026match sess.target.link_self_contained {
2027 LinkSelfContainedDefault::False => false,
2028 LinkSelfContainedDefault::True => true,
20292030 LinkSelfContainedDefault::WithComponents(components) => {
2031// For target specs with explicitly enabled components, we can return them
2032 // directly.
2033return components;
2034 }
20352036// FIXME: Find a better heuristic for "native musl toolchain is available",
2037 // based on host and linker path, for example.
2038 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2039LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2040 LinkSelfContainedDefault::InferredForMingw => {
2041sess.host == sess.target
2042 && sess.target.cfg_abi != CfgAbi::Uwp2043 && detect_self_contained_mingw(sess, linker)
2044 }
2045 }
2046 };
2047if self_contained {
2048LinkSelfContainedComponents::all()
2049 } else {
2050LinkSelfContainedComponents::empty()
2051 }
2052}
20532054/// Add pre-link object files defined by the target spec.
2055fn add_pre_link_objects(
2056 cmd: &mut dyn Linker,
2057 sess: &Session,
2058 flavor: LinkerFlavor,
2059 link_output_kind: LinkOutputKind,
2060 self_contained: bool,
2061) {
2062// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2063 // so Fuchsia has to be special-cased.
2064let opts = &sess.target;
2065let empty = Default::default();
2066let objects = if self_contained {
2067&opts.pre_link_objects_self_contained
2068 } else if !(sess.target.os == Os::Fuchsia && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
2069&opts.pre_link_objects
2070 } else {
2071&empty2072 };
2073for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2074 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2075 }
2076}
20772078/// Add post-link object files defined by the target spec.
2079fn add_post_link_objects(
2080 cmd: &mut dyn Linker,
2081 sess: &Session,
2082 link_output_kind: LinkOutputKind,
2083 self_contained: bool,
2084) {
2085let objects = if self_contained {
2086&sess.target.post_link_objects_self_contained
2087 } else {
2088&sess.target.post_link_objects
2089 };
2090for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2091 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2092 }
2093}
20942095/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2096/// FIXME: Determine where exactly these args need to be inserted.
2097fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2098if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2099cmd.verbatim_args(args.iter().map(Deref::deref));
2100 }
21012102cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2103}
21042105/// Add a link script embedded in the target, if applicable.
2106fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2107match (crate_type, &sess.target.link_script) {
2108 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2109if !sess.target.linker_flavor.is_gnu() {
2110sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2111 }
21122113let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
21142115let path = tmpdir.join(file_name);
2116if let Err(error) = fs::write(&path, script.as_ref()) {
2117sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2118 }
21192120cmd.link_arg("--script").link_arg(path);
2121 }
2122_ => {}
2123 }
2124}
21252126/// Add arbitrary "user defined" args defined from command line.
2127/// FIXME: Determine where exactly these args need to be inserted.
2128fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2129cmd.verbatim_args(&sess.opts.cg.link_args);
2130}
21312132/// Add arbitrary "late link" args defined by the target spec.
2133/// FIXME: Determine where exactly these args need to be inserted.
2134fn add_late_link_args(
2135 cmd: &mut dyn Linker,
2136 sess: &Session,
2137 flavor: LinkerFlavor,
2138 crate_type: CrateType,
2139 crate_info: &CrateInfo,
2140) {
2141let any_dynamic_crate = crate_type == CrateType::Dylib2142 || crate_type == CrateType::Sdylib2143 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2144*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2145 });
2146if any_dynamic_crate {
2147if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2148cmd.verbatim_args(args.iter().map(Deref::deref));
2149 }
2150 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2151cmd.verbatim_args(args.iter().map(Deref::deref));
2152 }
2153if let Some(args) = sess.target.late_link_args.get(&flavor) {
2154cmd.verbatim_args(args.iter().map(Deref::deref));
2155 }
2156}
21572158/// Add arbitrary "post-link" args defined by the target spec.
2159/// FIXME: Determine where exactly these args need to be inserted.
2160fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2161if let Some(args) = sess.target.post_link_args.get(&flavor) {
2162cmd.verbatim_args(args.iter().map(Deref::deref));
2163 }
2164}
21652166/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2167/// the linker.
2168///
2169/// Background: we implement rlibs as static library (archives). Linkers treat archives
2170/// differently from object files: all object files participate in linking, while archives will
2171/// only participate in linking if they can satisfy at least one undefined reference (version
2172/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2173/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2174/// can't keep them either. This causes #47384.
2175///
2176/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2177/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2178/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2179/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2180/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2181/// from removing them, and this is especially problematic for embedded programming where every
2182/// byte counts.
2183///
2184/// This method creates a synthetic object file, which contains undefined references to all symbols
2185/// that are necessary for the linking. They are only present in symbol table but not actually
2186/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2187/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2188///
2189/// There's a few internal crates in the standard library (aka libcore and
2190/// libstd) which actually have a circular dependence upon one another. This
2191/// currently arises through "weak lang items" where libcore requires things
2192/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2193/// circular dependence to work correctly we declare some of these things
2194/// in this synthetic object.
2195fn add_linked_symbol_object(
2196 cmd: &mut dyn Linker,
2197 sess: &Session,
2198 tmpdir: &Path,
2199 symbols: &[(String, SymbolExportKind)],
2200) {
2201if symbols.is_empty() {
2202return;
2203 }
22042205let Some(mut file) = super::metadata::create_object_file(sess) else {
2206return;
2207 };
22082209if file.format() == object::BinaryFormat::Coff {
2210// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2211 // so add an empty section.
2212file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
22132214// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2215 // default mangler in `object` crate.
2216file.set_mangling(object::write::Mangling::None);
2217 }
22182219if file.format() == object::BinaryFormat::MachO {
2220// Divide up the sections into sub-sections via symbols for dead code stripping.
2221 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2222 // discard on MachO targets.
2223file.set_subsections_via_symbols();
2224 }
22252226// ld64 requires a relocation to load undefined symbols, see below.
2227 // Not strictly needed if linking with lld, but might as well do it there too.
2228let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2229Some(file.add_section(
2230file.segment_name(object::write::StandardSegment::Data).to_vec(),
2231"__data".into(),
2232 object::SectionKind::Data,
2233 ))
2234 } else {
2235None2236 };
22372238for (sym, kind) in symbols.iter() {
2239let symbol = file.add_symbol(object::write::Symbol {
2240 name: sym.clone().into(),
2241 value: 0,
2242 size: 0,
2243 kind: match kind {
2244 SymbolExportKind::Text => object::SymbolKind::Text,
2245 SymbolExportKind::Data => object::SymbolKind::Data,
2246 SymbolExportKind::Tls => object::SymbolKind::Tls,
2247 },
2248 scope: object::SymbolScope::Unknown,
2249 weak: false,
2250 section: object::write::SymbolSection::Undefined,
2251 flags: object::SymbolFlags::None,
2252 });
22532254// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2255 //
2256 // Code-wise, the relevant parts of ld64 are roughly:
2257 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2258 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2259 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2260 //
2261 // 2. Read the archive table of contents (__.SYMDEF file).
2262 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2263 //
2264 // 3. Begin linking by loading "atoms" from input files.
2265 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2266 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2267 //
2268 // a. Directly specified object files (`.o`) are parsed immediately.
2269 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2270 //
2271 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2272 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2273 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2274 //
2275 // - Relocations/fixups are atoms.
2276 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2277 //
2278 // b. Archives are not parsed yet.
2279 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2280 //
2281 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2282 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2283 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2284 //
2285 // All of the steps above are fairly similar to other linkers, except that **it completely
2286 // ignores undefined symbols**.
2287 //
2288 // So to make this trick work on ld64, we need to do something else to load the relevant
2289 // object files. We do this by inserting a relocation (fixup) for each symbol.
2290if let Some(section) = ld64_section_helper {
2291 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2292 .expect("failed adding relocation");
2293 }
2294 }
22952296let path = tmpdir.join("symbols.o");
2297let result = std::fs::write(&path, file.write().unwrap());
2298if let Err(error) = result {
2299sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2300 }
2301cmd.add_object(&path);
2302}
23032304/// Add object files containing code from the current crate.
2305fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2306for m in &compiled_modules.modules {
2307if let Some(obj) = &m.object {
2308 cmd.add_object(obj);
2309 }
2310if let Some(obj) = &m.global_asm_object {
2311 cmd.add_object(obj);
2312 }
2313 }
2314}
23152316/// Add object files for allocator code linked once for the whole crate tree.
2317fn add_local_crate_allocator_objects(
2318 cmd: &mut dyn Linker,
2319 compiled_modules: &CompiledModules,
2320 crate_info: &CrateInfo,
2321 crate_type: CrateType,
2322) {
2323if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2324 && let Some(m) = &compiled_modules.allocator_module
2325 {
2326if let Some(obj) = &m.object {
2327cmd.add_object(obj);
2328 }
2329if let Some(obj) = &m.global_asm_object {
2330cmd.add_object(obj);
2331 }
2332 }
2333}
23342335/// Add object files containing metadata for the current crate.
2336fn add_local_crate_metadata_objects(
2337 cmd: &mut dyn Linker,
2338 sess: &Session,
2339 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2340 crate_type: CrateType,
2341 tmpdir: &Path,
2342 crate_info: &CrateInfo,
2343 metadata: &EncodedMetadata,
2344) {
2345// When linking a dynamic library, we put the metadata into a section of the
2346 // executable. This metadata is in a separate object file from the main
2347 // object file, so we create and link it in here.
2348if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2349let data = archive_builder_builder.create_dylib_metadata_wrapper(
2350sess,
2351&metadata,
2352&crate_info.metadata_symbol,
2353 );
2354let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
23552356cmd.add_object(&obj);
2357 }
2358}
23592360/// Add sysroot and other globally set directories to the directory search list.
2361fn add_library_search_dirs(
2362 cmd: &mut dyn Linker,
2363 sess: &Session,
2364 self_contained_components: LinkSelfContainedComponents,
2365 apple_sdk_root: Option<&Path>,
2366) {
2367if !sess.opts.unstable_opts.link_native_libraries {
2368return;
2369 }
23702371let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2372let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2373if is_framework {
2374cmd.framework_path(dir);
2375 } else {
2376cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2377 }
2378 ControlFlow::<()>::Continue(())
2379 });
2380}
23812382/// Add options making relocation sections in the produced ELF files read-only
2383/// and suppressing lazy binding.
2384fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2385match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2386 RelroLevel::Full => cmd.full_relro(),
2387 RelroLevel::Partial => cmd.partial_relro(),
2388 RelroLevel::Off => cmd.no_relro(),
2389 RelroLevel::None => {}
2390 }
2391}
23922393/// Add library search paths used at runtime by dynamic linkers.
2394fn add_rpath_args(
2395 cmd: &mut dyn Linker,
2396 sess: &Session,
2397 crate_info: &CrateInfo,
2398 out_filename: &Path,
2399) {
2400if !sess.target.has_rpath {
2401return;
2402 }
24032404// FIXME (#2397): At some point we want to rpath our guesses as to
2405 // where extern libraries might live, based on the
2406 // add_lib_search_paths
2407if sess.opts.cg.rpath {
2408let libs = crate_info2409 .used_crates
2410 .iter()
2411 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2412 .collect::<Vec<_>>();
2413let rpath_config = RPathConfig {
2414 libs: &*libs,
2415 out_filename: out_filename.to_path_buf(),
2416 is_like_darwin: sess.target.is_like_darwin,
2417 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2418 };
2419cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2420 }
2421}
24222423fn strip_numeric_suffix<'a>(base: &'a str, suffix: impl AsRef<str>, fallback: &'a str) -> &'a str {
2424if suffix.as_ref().parse::<u32>().is_ok() { base } else { fallback }
2425}
24262427fn undecorate_c_symbol<'a>(
2428 name: &'a str,
2429 sess: &Session,
2430 kind: SymbolExportKind,
2431) -> Option<&'a str> {
2432match sess.target.binary_format {
2433 BinaryFormat::MachO => {
2434// Mach-O: strip the leading underscore that all external symbols have.
2435 // The Darwin linker's export_symbols will add it back.
2436name.strip_prefix('_')
2437 }
2438 BinaryFormat::Coff => {
2439// MSVC C++ mangled names start with '?' and use a completely different
2440 // decorating scheme that includes '@@' as structural delimiters.
2441 // They must not be subjected to C calling-convention undecoration.
2442if name.starts_with('?') {
2443return Some(name);
2444 }
2445Some(match sess.target.arch {
2446 Arch::X86 => {
2447// COFF 32-bit: strip calling-convention decorations.
2448if let Some(rest) = name.strip_prefix('@') {
2449// fastcall: @foo@N -> foo
2450rest.rsplit_once('@')
2451 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2452 .unwrap_or(name)
2453 } else if let Some(stripped) = name.strip_prefix('_') {
2454if let Some((base, suffix)) = stripped.rsplit_once('@') {
2455// stdcall: _foo@N -> foo
2456strip_numeric_suffix(base, suffix, stripped)
2457 } else {
2458// cdecl: _foo -> foo
2459stripped2460 }
2461 } else {
2462// vectorcall: foo@@N -> foo
2463name.rsplit_once("@@")
2464 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2465 .unwrap_or(name)
2466 }
2467 }
2468 Arch::X86_64 => {
2469// COFF 64-bit: vectorcall mangling (foo@@N -> foo) also applies on x86_64.
2470name.rsplit_once("@@")
2471 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2472 .unwrap_or(name)
2473 }
2474 Arch::Arm64ECif kind == SymbolExportKind::Text => {
2475// Arm64EC: `#` prefix distinguishes ARM64EC text symbols from x64 thunks.
2476name.strip_prefix('#').unwrap_or(name)
2477 }
2478_ => name,
2479 })
2480 }
2481// ELF: no decoration
2482_ => Some(name),
2483 }
2484}
24852486fn add_c_staticlib_symbols(
2487 sess: &Session,
2488 lib: &NativeLib,
2489 out: &mut Vec<(String, SymbolExportKind)>,
2490) -> io::Result<()> {
2491let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
24922493let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
24942495let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2496 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24972498for member in archive.members() {
2499let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
25002501let data = member
2502 .data(&*archive_map)
2503 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
25042505// clang LTO: raw LLVM bitcode
2506if data.starts_with(b"BC\xc0\xde") {
2507return Err(io::Error::new(
2508 io::ErrorKind::InvalidData,
2509"LLVM bitcode object in C static library (LTO not supported)",
2510 ));
2511 }
25122513let object = object::File::parse(&*data)
2514 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
25152516// gcc / clang ELF / Mach-O LTO
2517if object.sections().any(|s| {
2518 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2519 }) {
2520return Err(io::Error::new(
2521 io::ErrorKind::InvalidData,
2522"LTO object in C static library is not supported",
2523 ));
2524 }
25252526for symbol in object.symbols() {
2527// The `object` crate returns `Dynamic` for ELF/Mach-O global symbols,
2528 // but always returns `Linkage` for COFF external symbols.
2529 // Accept both for COFF (Windows and UEFI).
2530let scope = symbol.scope();
2531if scope != object::SymbolScope::Dynamic
2532 && !(sess.target.binary_format == BinaryFormat::Coff
2533 && scope == object::SymbolScope::Linkage)
2534 {
2535continue;
2536 }
25372538let name = match symbol.name() {
2539Ok(n) => n,
2540Err(_) => continue,
2541 };
25422543let export_kind = match symbol.kind() {
2544 object::SymbolKind::Text => SymbolExportKind::Text,
2545 object::SymbolKind::Data => SymbolExportKind::Data,
2546_ => continue,
2547 };
25482549let Some(undecorated) = undecorate_c_symbol(name, sess, export_kind) else {
2550continue;
2551 };
2552 out.push((undecorated.to_string(), export_kind));
2553 }
2554 }
25552556Ok(())
2557}
25582559/// Produce the linker command line containing linker path and arguments.
2560///
2561/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2562/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2563/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2564/// to the linking process as a whole.
2565/// Order-independent options may still override each other in order-dependent fashion,
2566/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2567fn linker_with_args(
2568 path: &Path,
2569 flavor: LinkerFlavor,
2570 sess: &Session,
2571 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2572 rmeta_link_cache: &mut RmetaLinkCache,
2573 crate_type: CrateType,
2574 tmpdir: &Path,
2575 out_filename: &Path,
2576 compiled_modules: &CompiledModules,
2577 crate_info: &CrateInfo,
2578 metadata: &EncodedMetadata,
2579 self_contained_components: LinkSelfContainedComponents,
2580 codegen_backend: &'static str,
2581) -> Command {
2582let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2583let cmd = &mut *super::linker::get_linker(
2584sess,
2585path,
2586flavor,
2587self_contained_components.are_any_components_enabled(),
2588&crate_info.target_cpu,
2589codegen_backend,
2590 );
2591let link_output_kind = link_output_kind(sess, crate_type);
25922593let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
25942595if crate_type == CrateType::Cdylib {
2596let mut seen = FxHashSet::default();
25972598for lib in &crate_info.used_libraries {
2599if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2600 && seen.insert((lib.name, lib.verbatim))
2601 {
2602if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2603 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2604"failed to process C static library `{}`: {}",
2605 lib.name, err
2606 ));
2607 }
2608 }
2609 }
2610 }
26112612// ------------ Early order-dependent options ------------
26132614 // If we're building something like a dynamic library then some platforms
2615 // need to make sure that all symbols are exported correctly from the
2616 // dynamic library.
2617 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2618 // at least on some platforms (e.g. windows-gnu).
2619cmd.export_symbols(tmpdir, crate_type, &export_symbols);
26202621// Can be used for adding custom CRT objects or overriding order-dependent options above.
2622 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2623 // introduce a target spec option for order-independent linker options and migrate built-in
2624 // specs to it.
2625add_pre_link_args(cmd, sess, flavor);
26262627// ------------ Object code and libraries, order-dependent ------------
26282629 // Pre-link CRT objects.
2630add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
26312632add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
26332634// Sanitizer libraries.
2635add_sanitizer_libraries(sess, flavor, crate_type, cmd);
26362637// Object code from the current crate.
2638 // Take careful note of the ordering of the arguments we pass to the linker
2639 // here. Linkers will assume that things on the left depend on things to the
2640 // right. Things on the right cannot depend on things on the left. This is
2641 // all formally implemented in terms of resolving symbols (libs on the right
2642 // resolve unknown symbols of libs on the left, but not vice versa).
2643 //
2644 // For this reason, we have organized the arguments we pass to the linker as
2645 // such:
2646 //
2647 // 1. The local object that LLVM just generated
2648 // 2. Local native libraries
2649 // 3. Upstream rust libraries
2650 // 4. Upstream native libraries
2651 //
2652 // The rationale behind this ordering is that those items lower down in the
2653 // list can't depend on items higher up in the list. For example nothing can
2654 // depend on what we just generated (e.g., that'd be a circular dependency).
2655 // Upstream rust libraries are not supposed to depend on our local native
2656 // libraries as that would violate the structure of the DAG, in that
2657 // scenario they are required to link to them as well in a shared fashion.
2658 //
2659 // Note that upstream rust libraries may contain native dependencies as
2660 // well, but they also can't depend on what we just started to add to the
2661 // link line. And finally upstream native libraries can't depend on anything
2662 // in this DAG so far because they can only depend on other native libraries
2663 // and such dependencies are also required to be specified.
2664add_local_crate_regular_objects(cmd, compiled_modules);
2665add_local_crate_metadata_objects(
2666cmd,
2667sess,
2668archive_builder_builder,
2669crate_type,
2670tmpdir,
2671crate_info,
2672metadata,
2673 );
2674add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
26752676// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2677 // at the point at which they are specified on the command line.
2678 // Must be passed before any (dynamic) libraries to have effect on them.
2679 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2680 // so it will ignore unreferenced ELF sections from relocatable objects.
2681 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2682 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2683 // and move this option back to the top.
2684cmd.add_as_needed();
26852686// Local native libraries of all kinds.
2687add_local_native_libraries(
2688cmd,
2689sess,
2690archive_builder_builder,
2691crate_info,
2692tmpdir,
2693link_output_kind,
2694 );
26952696// Upstream rust crates and their non-dynamic native libraries.
2697add_upstream_rust_crates(
2698cmd,
2699sess,
2700archive_builder_builder,
2701rmeta_link_cache,
2702crate_info,
2703crate_type,
2704tmpdir,
2705link_output_kind,
2706 );
27072708// Dynamic native libraries from upstream crates.
2709add_upstream_native_libraries(
2710cmd,
2711sess,
2712archive_builder_builder,
2713crate_info,
2714tmpdir,
2715link_output_kind,
2716 );
27172718// Raw-dylibs from all crates.
2719let raw_dylib_dir = tmpdir.join("raw-dylibs");
2720if sess.target.binary_format == BinaryFormat::Elf {
2721// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2722 // instead we need to pass them via -l. To find the stub, we need to add
2723 // the directory of the stub to the linker search path.
2724 // We make an extra directory for this to avoid polluting the search path.
2725if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2726sess.dcx().emit_fatal(errors::CreateTempDir { error })
2727 }
2728cmd.include_path(&raw_dylib_dir);
2729 }
27302731// Link with the import library generated for any raw-dylib functions.
2732if sess.target.is_like_windows {
2733for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2734 sess,
2735 archive_builder_builder,
2736 crate_info.used_libraries.iter(),
2737 tmpdir,
2738true,
2739 ) {
2740 cmd.add_object(&output_path);
2741 }
2742 } else {
2743for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2744 sess,
2745 crate_info.used_libraries.iter(),
2746&raw_dylib_dir,
2747 ) {
2748// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2749cmd.link_dylib_by_name(&link_path, true, as_needed);
2750 }
2751 }
2752// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2753 // they are used within inlined functions or instantiated generic functions. We do this *after*
2754 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2755 // by the linker.
2756let dependency_linkage = crate_info2757 .dependency_formats
2758 .get(&crate_type)
2759 .expect("failed to find crate type in dependency format list");
27602761// We sort the libraries below
2762#[allow(rustc::potential_query_instability)]
2763let mut native_libraries_from_nonstatics = crate_info2764 .native_libraries
2765 .iter()
2766 .filter_map(|(&cnum, libraries)| {
2767if sess.target.is_like_windows {
2768 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2769 } else {
2770Some(libraries)
2771 }
2772 })
2773 .flatten()
2774 .collect::<Vec<_>>();
2775native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
27762777if sess.target.is_like_windows {
2778for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2779 sess,
2780 archive_builder_builder,
2781 native_libraries_from_nonstatics,
2782 tmpdir,
2783false,
2784 ) {
2785 cmd.add_object(&output_path);
2786 }
2787 } else {
2788for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2789 sess,
2790 native_libraries_from_nonstatics,
2791&raw_dylib_dir,
2792 ) {
2793// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2794cmd.link_dylib_by_name(&link_path, true, as_needed);
2795 }
2796 }
27972798// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2799 // command line shorter, reset it to default here before adding more libraries.
2800cmd.reset_per_library_state();
28012802// FIXME: Built-in target specs occasionally use this for linking system libraries,
2803 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2804 // and remove the option.
2805add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
28062807// ------------ Arbitrary order-independent options ------------
28082809 // Add order-independent options determined by rustc from its compiler options,
2810 // target properties and source code.
2811add_order_independent_options(
2812cmd,
2813sess,
2814link_output_kind,
2815self_contained_components,
2816flavor,
2817crate_type,
2818crate_info,
2819out_filename,
2820tmpdir,
2821 );
28222823// Can be used for arbitrary order-independent options.
2824 // In practice may also be occasionally used for linking native libraries.
2825 // Passed after compiler-generated options to support manual overriding when necessary.
2826add_user_defined_link_args(cmd, sess);
28272828// ------------ Builtin configurable linker scripts ------------
2829 // The user's link args should be able to overwrite symbols in the compiler's
2830 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2831 // to work correctly, the user needs to be able to specify linker arguments like
2832 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2833add_link_script(cmd, sess, tmpdir, crate_type);
28342835// ------------ Object code and libraries, order-dependent ------------
28362837 // Post-link CRT objects.
2838add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
28392840// ------------ Late order-dependent options ------------
28412842 // Doesn't really make sense.
2843 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2844 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2845 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2846add_post_link_args(cmd, sess, flavor);
28472848cmd.take_cmd()
2849}
28502851fn add_order_independent_options(
2852 cmd: &mut dyn Linker,
2853 sess: &Session,
2854 link_output_kind: LinkOutputKind,
2855 self_contained_components: LinkSelfContainedComponents,
2856 flavor: LinkerFlavor,
2857 crate_type: CrateType,
2858 crate_info: &CrateInfo,
2859 out_filename: &Path,
2860 tmpdir: &Path,
2861) {
2862// Take care of the flavors and CLI options requesting the `lld` linker.
2863add_lld_args(cmd, sess, flavor, self_contained_components);
28642865add_apple_link_args(cmd, sess, flavor);
28662867let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
28682869if sess.target.os == Os::Fuchsia2870 && crate_type == CrateType::Executable2871 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2872 {
2873let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2874cmd.link_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--dynamic-linker={0}ld.so.1",
prefix))
})format!("--dynamic-linker={prefix}ld.so.1"));
2875 }
28762877if sess.target.eh_frame_header {
2878cmd.add_eh_frame_header();
2879 }
28802881// Make the binary compatible with data execution prevention schemes.
2882cmd.add_no_exec();
28832884if self_contained_components.is_crt_objects_enabled() {
2885cmd.no_crt_objects();
2886 }
28872888if sess.target.os == Os::Emscripten {
2889cmd.cc_arg("-fwasm-exceptions");
2890 }
28912892if flavor == LinkerFlavor::Llbc {
2893cmd.link_args(&[
2894"--target",
2895&versioned_llvm_target(sess),
2896"--target-cpu",
2897&crate_info.target_cpu,
2898 ]);
2899if crate_info.target_features.len() > 0 {
2900cmd.link_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target-feature={0}",
&crate_info.target_features.join(",")))
})format!("--target-feature={}", &crate_info.target_features.join(",")));
2901 }
2902 } else if flavor == LinkerFlavor::Bpf {
2903cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2904if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2905 .into_iter()
2906 .find(|feat| !feat.is_empty())
2907 {
2908cmd.link_args(&["--cpu-features", feat]);
2909 }
2910 }
29112912cmd.linker_plugin_lto();
29132914add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
29152916cmd.output_filename(out_filename);
29172918if crate_type == CrateType::Executable2919 && sess.target.is_like_windows
2920 && let Some(s) = &crate_info.windows_subsystem
2921 {
2922cmd.windows_subsystem(*s);
2923 }
29242925// Try to strip as much out of the generated object by removing unused
2926 // sections if possible. See more comments in linker.rs
2927if !sess.link_dead_code() {
2928// If PGO is enabled sometimes gc_sections will remove the profile data section
2929 // as it appears to be unused. This can then cause the PGO profile file to lose
2930 // some functions. If we are generating a profile we shouldn't strip those metadata
2931 // sections to ensure we have all the data for PGO.
2932let keep_metadata =
2933crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2934cmd.gc_sections(keep_metadata);
2935 }
29362937cmd.set_output_kind(link_output_kind, crate_type, out_filename);
29382939add_relro_args(cmd, sess);
29402941// Pass optimization flags down to the linker.
2942cmd.optimize();
29432944// Gather the set of NatVis files, if any, and write them out to a temp directory.
2945let natvis_visualizers = collect_natvis_visualizers(
2946tmpdir,
2947sess,
2948&crate_info.local_crate_name,
2949&crate_info.natvis_debugger_visualizers,
2950 );
29512952// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2953cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
29542955// We want to prevent the compiler from accidentally leaking in any system libraries,
2956 // so by default we tell linkers not to link to any default libraries.
2957if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2958cmd.no_default_libraries();
2959 }
29602961if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2962cmd.pgo_gen();
2963 }
29642965if sess.opts.unstable_opts.instrument_mcount != InstrumentMcount::Disabled {
2966cmd.enable_profiling();
2967 }
29682969if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2970cmd.control_flow_guard();
2971 }
29722973// OBJECT-FILES-NO, AUDIT-ORDER
2974if sess.opts.unstable_opts.ehcont_guard {
2975cmd.ehcont_guard();
2976 }
29772978add_rpath_args(cmd, sess, crate_info, out_filename);
2979}
29802981// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2982fn collect_natvis_visualizers(
2983 tmpdir: &Path,
2984 sess: &Session,
2985 crate_name: &Symbol,
2986 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2987) -> Vec<PathBuf> {
2988let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
29892990for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2991let visualizer_out_file = tmpdir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}-{1}.natvis",
crate_name.as_str(), index))
})format!("{}-{}.natvis", crate_name.as_str(), index));
29922993match fs::write(&visualizer_out_file, &visualizer.src) {
2994Ok(()) => {
2995 visualizer_paths.push(visualizer_out_file);
2996 }
2997Err(error) => {
2998 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2999 path: visualizer_out_file,
3000 error,
3001 });
3002 }
3003 };
3004 }
3005visualizer_paths3006}
30073008fn add_native_libs_from_crate(
3009 cmd: &mut dyn Linker,
3010 sess: &Session,
3011 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3012 crate_info: &CrateInfo,
3013 tmpdir: &Path,
3014 bundled_libs: &FxIndexSet<Symbol>,
3015 cnum: CrateNum,
3016 link_static: bool,
3017 link_dynamic: bool,
3018 link_output_kind: LinkOutputKind,
3019) {
3020if !sess.opts.unstable_opts.link_native_libraries {
3021// If `-Zlink-native-libraries=false` is set, then the assumption is that an
3022 // external build system already has the native dependencies defined, and it
3023 // will provide them to the linker itself.
3024return;
3025 }
30263027if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
3028// If rlib contains native libs as archives, unpack them to tmpdir.
3029let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
3030archive_builder_builder3031 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
3032 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
3033 }
30343035let native_libs = match cnum {
3036LOCAL_CRATE => &crate_info.used_libraries,
3037_ => &crate_info.native_libraries[&cnum],
3038 };
30393040let mut last = (None, NativeLibKind::Unspecified, false);
3041for lib in native_libs {
3042if !relevant_lib(sess, lib) {
3043continue;
3044 }
30453046// Skip if this library is the same as the last.
3047last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
3048continue;
3049 } else {
3050 (Some(lib.name), lib.kind, lib.verbatim)
3051 };
30523053let name = lib.name.as_str();
3054let verbatim = lib.verbatim;
3055match lib.kind {
3056 NativeLibKind::Static { bundle, whole_archive, .. } => {
3057if link_static {
3058let bundle = bundle.unwrap_or(true);
3059let whole_archive = whole_archive == Some(true);
3060if bundle && cnum != LOCAL_CRATE {
3061if let Some(filename) = lib.filename {
3062// If rlib contains native libs as archives, they are unpacked to tmpdir.
3063let path = tmpdir.join(filename.as_str());
3064 cmd.link_staticlib_by_path(&path, whole_archive);
3065 }
3066 } else {
3067 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
3068 }
3069 }
3070 }
3071 NativeLibKind::Dylib { as_needed } => {
3072if link_dynamic {
3073 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
3074 }
3075 }
3076 NativeLibKind::Unspecified => {
3077// If we are generating a static binary, prefer static library when the
3078 // link kind is unspecified.
3079if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
3080if link_static {
3081 cmd.link_staticlib_by_name(name, verbatim, false);
3082 }
3083 } else if link_dynamic {
3084 cmd.link_dylib_by_name(name, verbatim, true);
3085 }
3086 }
3087 NativeLibKind::Framework { as_needed } => {
3088if link_dynamic {
3089 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
3090 }
3091 }
3092 NativeLibKind::RawDylib { as_needed: _ } => {
3093// Handled separately in `linker_with_args`.
3094}
3095 NativeLibKind::WasmImportModule => {}
3096 NativeLibKind::LinkArg => {
3097if link_static {
3098if verbatim {
3099 cmd.verbatim_arg(name);
3100 } else {
3101 cmd.link_arg(name);
3102 }
3103 }
3104 }
3105 }
3106 }
3107}
31083109fn add_local_native_libraries(
3110 cmd: &mut dyn Linker,
3111 sess: &Session,
3112 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3113 crate_info: &CrateInfo,
3114 tmpdir: &Path,
3115 link_output_kind: LinkOutputKind,
3116) {
3117// All static and dynamic native library dependencies are linked to the local crate.
3118let link_static = true;
3119let link_dynamic = true;
3120add_native_libs_from_crate(
3121cmd,
3122sess,
3123archive_builder_builder,
3124crate_info,
3125tmpdir,
3126&Default::default(),
3127LOCAL_CRATE,
3128link_static,
3129link_dynamic,
3130link_output_kind,
3131 );
3132}
31333134fn add_upstream_rust_crates(
3135 cmd: &mut dyn Linker,
3136 sess: &Session,
3137 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3138 rmeta_link_cache: &mut RmetaLinkCache,
3139 crate_info: &CrateInfo,
3140 crate_type: CrateType,
3141 tmpdir: &Path,
3142 link_output_kind: LinkOutputKind,
3143) {
3144// All of the heavy lifting has previously been accomplished by the
3145 // dependency_format module of the compiler. This is just crawling the
3146 // output of that module, adding crates as necessary.
3147 //
3148 // Linking to a rlib involves just passing it to the linker (the linker
3149 // will slurp up the object files inside), and linking to a dynamic library
3150 // involves just passing the right -l flag.
3151let data = crate_info3152 .dependency_formats
3153 .get(&crate_type)
3154 .expect("failed to find crate type in dependency format list");
31553156if sess.target.is_like_aix {
3157// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3158 // the dependency name when outputting a shared library. Thus, `ld` will
3159 // use the full path to shared libraries as the dependency if passed it
3160 // by default unless `noipath` is passed.
3161 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3162cmd.link_or_cc_arg("-bnoipath");
3163 }
31643165for &cnum in &crate_info.used_crates {
3166// We may not pass all crates through to the linker. Some crates may appear statically in
3167 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3168 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3169 // Even if they were already included into a dylib
3170 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3171 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3172 // See the comment in inject_profiler_runtime for why this is the case.
3173let linkage = data[cnum];
3174let link_static_crate = linkage == Linkage::Static
3175 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3176 && (crate_info.compiler_builtins == Some(cnum)
3177 || crate_info.profiler_runtime == Some(cnum));
31783179let mut bundled_libs = Default::default();
3180match linkage {
3181 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3182if link_static_crate {
3183 bundled_libs = crate_info.native_libraries[&cnum]
3184 .iter()
3185 .filter_map(|lib| lib.filename)
3186 .collect();
3187 add_static_crate(
3188 cmd,
3189 sess,
3190 archive_builder_builder,
3191 rmeta_link_cache,
3192 crate_info,
3193 tmpdir,
3194 cnum,
3195&bundled_libs,
3196 );
3197 }
3198 }
3199 Linkage::Dynamic => {
3200let src = &crate_info.used_crate_source[&cnum];
3201 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3202 }
3203 }
32043205// Static libraries are linked for a subset of linked upstream crates.
3206 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3207 // because the rlib is just an archive.
3208 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3209 // the native library because it is already linked into the dylib, and even if
3210 // inline/const/generic functions from the dylib can refer to symbols from the native
3211 // library, those symbols should be exported and available from the dylib anyway.
3212 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3213let link_static = link_static_crate;
3214// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3215let link_dynamic = false;
3216 add_native_libs_from_crate(
3217 cmd,
3218 sess,
3219 archive_builder_builder,
3220 crate_info,
3221 tmpdir,
3222&bundled_libs,
3223 cnum,
3224 link_static,
3225 link_dynamic,
3226 link_output_kind,
3227 );
3228 }
3229}
32303231fn add_upstream_native_libraries(
3232 cmd: &mut dyn Linker,
3233 sess: &Session,
3234 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3235 crate_info: &CrateInfo,
3236 tmpdir: &Path,
3237 link_output_kind: LinkOutputKind,
3238) {
3239for &cnum in &crate_info.used_crates {
3240// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3241 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3242 // are linked together with their respective upstream crates, and in their originally
3243 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3244 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3245let link_static = false;
3246// Dynamic libraries are linked for all linked upstream crates.
3247 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3248 // because the rlib is just an archive.
3249 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3250 // the native library too because inline/const/generic functions from the dylib can refer
3251 // to symbols from the native library, so the native library providing those symbols should
3252 // be available when linking our final binary.
3253let link_dynamic = true;
3254 add_native_libs_from_crate(
3255 cmd,
3256 sess,
3257 archive_builder_builder,
3258 crate_info,
3259 tmpdir,
3260&Default::default(),
3261 cnum,
3262 link_static,
3263 link_dynamic,
3264 link_output_kind,
3265 );
3266 }
3267}
32683269// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3270// to be relative to the sysroot directory, which may be a relative path specified by the user.
3271//
3272// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3273// linker command line can be non-deterministic due to the paths including the current working
3274// directory. The linker command line needs to be deterministic since it appears inside the PDB
3275// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3276//
3277// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3278fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3279let sysroot_lib_path = &sess.target_tlib_path.dir;
3280let canonical_sysroot_lib_path =
3281 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
32823283let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3284if canonical_lib_dir == canonical_sysroot_lib_path {
3285// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3286sysroot_lib_path.clone()
3287 } else {
3288fix_windows_verbatim_for_gcc(lib_dir)
3289 }
3290}
32913292fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3293if let Some(dir) = path.parent() {
3294let file_name = path.file_name().expect("library path has no file name component");
3295rehome_sysroot_lib_dir(sess, dir).join(file_name)
3296 } else {
3297fix_windows_verbatim_for_gcc(path)
3298 }
3299}
33003301// Adds the static "rlib" versions of all crates to the command line.
3302// There's a bit of magic which happens here specifically related to LTO,
3303// namely that we remove upstream object files.
3304//
3305// When performing LTO, almost(*) all of the bytecode from the upstream
3306// libraries has already been included in our object file output. As a
3307// result we need to remove the object files in the upstream libraries so
3308// the linker doesn't try to include them twice (or whine about duplicate
3309// symbols). We must continue to include the rest of the rlib, however, as
3310// it may contain static native libraries which must be linked in.
3311//
3312// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3313// their bytecode wasn't included. The object files in those libraries must
3314// still be passed to the linker.
3315//
3316// Note, however, that if we're not doing LTO we can just pass the rlib
3317// blindly to the linker (fast) because it's fine if it's not actually
3318// included as we're at the end of the dependency chain.
3319fn add_static_crate(
3320 cmd: &mut dyn Linker,
3321 sess: &Session,
3322 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3323 rmeta_link_cache: &mut RmetaLinkCache,
3324 crate_info: &CrateInfo,
3325 tmpdir: &Path,
3326 cnum: CrateNum,
3327 bundled_lib_file_names: &FxIndexSet<Symbol>,
3328) {
3329let src = &crate_info.used_crate_source[&cnum];
3330let cratepath = src.rlib.as_ref().unwrap();
33313332let mut link_upstream =
3333 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
33343335if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3336 {
3337link_upstream(cratepath);
3338return;
3339 }
33403341let dst = tmpdir.join(cratepath.file_name().unwrap());
3342let name = cratepath.file_name().unwrap().to_str().unwrap();
3343let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3344let bundled_lib_file_names = bundled_lib_file_names.clone();
33453346sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3347let upstream_rust_objects_already_included =
3348are_upstream_rust_objects_already_included(sess);
3349let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
33503351let mut archive = archive_builder_builder.new_archive_builder(sess);
3352if let Err(error) = archive.add_archive(
3353cratepath,
3354 AddArchiveKind::Rlib(rmeta_link_cache, &|f, entry_kind| {
3355if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3356return true;
3357 }
33583359// If we're performing LTO and this is a rust-generated object
3360 // file, then we don't need the object file as it's part of the
3361 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3362 // though, so we let that object file slide.
3363if upstream_rust_objects_already_included3364 && entry_kind == ArchiveEntryKind::RustObj3365 && is_builtins3366 {
3367return true;
3368 }
33693370// We skip native libraries because:
3371 // 1. This native libraries won't be used from the generated rlib,
3372 // so we can throw them away to avoid the copying work.
3373 // 2. We can't allow it to be a single remaining entry in archive
3374 // as some linkers may complain on that.
3375if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3376return true;
3377 }
33783379false
3380}),
3381 ) {
3382sess.dcx()
3383 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3384 }
3385if archive.build(&dst, None) {
3386link_upstream(&dst);
3387 }
3388 });
3389}
33903391// Same thing as above, but for dynamic crates instead of static crates.
3392fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3393cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3394}
33953396fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3397match lib.cfg {
3398Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3399None => true,
3400 }
3401}
34023403pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3404match sess.lto() {
3405 config::Lto::Fat => true,
3406 config::Lto::Thin => {
3407// If we defer LTO to the linker, we haven't run LTO ourselves, so
3408 // any upstream object files have not been copied yet.
3409!sess.opts.cg.linker_plugin_lto.enabled()
3410 }
3411 config::Lto::No | config::Lto::ThinLocal => false,
3412 }
3413}
34143415/// We need to communicate five things to the linker on Apple/Darwin targets:
3416/// - The architecture.
3417/// - The operating system (and that it's an Apple platform).
3418/// - The environment.
3419/// - The deployment target.
3420/// - The SDK version.
3421fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3422if !sess.target.is_like_darwin {
3423return;
3424 }
3425let LinkerFlavor::Darwin(cc, _) = flavorelse {
3426return;
3427 };
34283429// `sess.target.arch` (`target_arch`) is not detailed enough.
3430let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3431let target_os = &sess.target.os;
3432let target_env = &sess.target.env;
34333434// The architecture name to forward to the linker.
3435 //
3436 // Supported architecture names can be found in the source:
3437 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3438 //
3439 // Intentionally verbose to ensure that the list always matches correctly
3440 // with the list in the source above.
3441let ld64_arch = match llvm_arch {
3442"armv7k" => "armv7k",
3443"armv7s" => "armv7s",
3444"arm64" => "arm64",
3445"arm64e" => "arm64e",
3446"arm64_32" => "arm64_32",
3447// ld64 doesn't understand i686, so fall back to i386 instead.
3448 //
3449 // Same story when linking with cc, since that ends up invoking ld64.
3450"i386" | "i686" => "i386",
3451"x86_64" => "x86_64",
3452"x86_64h" => "x86_64h",
3453_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsupported architecture in Apple target: {0}",
sess.target.llvm_target))bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3454 };
34553456if cc == Cc::No {
3457// From the man page for ld64 (`man ld`):
3458 // > The linker accepts universal (multiple-architecture) input files,
3459 // > but always creates a "thin" (single-architecture), standard
3460 // > Mach-O output file. The architecture for the output file is
3461 // > specified using the -arch option.
3462 //
3463 // The linker has heuristics to determine the desired architecture,
3464 // but to be safe, and to avoid a warning, we set the architecture
3465 // explicitly.
3466cmd.link_args(&["-arch", ld64_arch]);
34673468// Man page says that ld64 supports the following platform names:
3469 // > - macos
3470 // > - ios
3471 // > - tvos
3472 // > - watchos
3473 // > - bridgeos
3474 // > - visionos
3475 // > - xros
3476 // > - mac-catalyst
3477 // > - ios-simulator
3478 // > - tvos-simulator
3479 // > - watchos-simulator
3480 // > - visionos-simulator
3481 // > - xros-simulator
3482 // > - driverkit
3483let platform_name = match (target_os, target_env) {
3484 (os, Env::Unspecified) => os.desc(),
3485 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3486 (Os::IOs, Env::Sim) => "ios-simulator",
3487 (Os::TvOs, Env::Sim) => "tvos-simulator",
3488 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3489 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3490_ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid OS/env combination for Apple target: {0}, {1}",
target_os, target_env))bug!("invalid OS/env combination for Apple target: {target_os}, {target_env}"),
3491 };
34923493let min_version = sess.apple_deployment_target().fmt_full().to_string();
34943495// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3496 // - By dyld to give extra warnings and errors, see e.g.:
3497 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3498 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3499 // - By system frameworks to change certain behaviour. For example, the default value of
3500 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3501 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3502 //
3503 // We do not currently know the actual SDK version though, so we have a few options:
3504 // 1. Use the minimum version supported by rustc.
3505 // 2. Use the same as the deployment target.
3506 // 3. Use an arbitrary recent version.
3507 // 4. Omit the version.
3508 //
3509 // The first option is too low / too conservative, and means that users will not get the
3510 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3511 //
3512 // The second option is similarly conservative, and also wrong since if the user specified a
3513 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3514 // make invalid assumptions about the capabilities of the binary.
3515 //
3516 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3517 // version, and is also wrong for similar reasons as above.
3518 //
3519 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3520 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3521 // it as 0.0, which is again too low/conservative.
3522 //
3523 // Currently, we lie about the SDK version, and choose the second option.
3524 //
3525 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3526 // <https://github.com/rust-lang/rust/issues/129432>
3527let sdk_version = &*min_version;
35283529// From the man page for ld64 (`man ld`):
3530 // > This is set to indicate the platform, oldest supported version of
3531 // > that platform that output is to be used on, and the SDK that the
3532 // > output was built against.
3533 //
3534 // Like with `-arch`, the linker can figure out the platform versions
3535 // itself from the binaries being linked, but to be safe, we specify
3536 // the desired versions here explicitly.
3537cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3538 } else {
3539// cc == Cc::Yes
3540 //
3541 // We'd _like_ to use `-target` everywhere, since that can uniquely
3542 // communicate all the required details except for the SDK version
3543 // (which is read by Clang itself from the SDKROOT), but that doesn't
3544 // work on GCC, and since we don't know whether the `cc` compiler is
3545 // Clang, GCC, or something else, we fall back to other options that
3546 // also work on GCC when compiling for macOS.
3547 //
3548 // Targets other than macOS are ill-supported by GCC (it doesn't even
3549 // support e.g. `-miphoneos-version-min`), so in those cases we can
3550 // fairly safely use `-target`. See also the following, where it is
3551 // made explicit that the recommendation by LLVM developers is to use
3552 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3553if *target_os == Os::MacOs {
3554// `-arch` communicates the architecture.
3555 //
3556 // CC forwards the `-arch` to the linker, so we use the same value
3557 // here intentionally.
3558cmd.cc_args(&["-arch", ld64_arch]);
35593560// The presence of `-mmacosx-version-min` makes CC default to
3561 // macOS, and it sets the deployment target.
3562let version = sess.apple_deployment_target().fmt_full();
3563// Intentionally pass this as a single argument, Clang doesn't
3564 // seem to like it otherwise.
3565cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
35663567// macOS has no environment, so with these two, we've told CC the
3568 // four desired parameters.
3569 //
3570 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3571} else {
3572cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3573 }
3574 }
3575}
35763577fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3578if !sess.target.is_like_darwin {
3579return None;
3580 }
3581let LinkerFlavor::Darwin(cc, _) = flavorelse {
3582return None;
3583 };
35843585// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3586 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3587 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3588 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3589 // instead we invoke `xcrun` manually.
3590 //
3591 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3592 // cause the trampoline binary to skip looking up the SDK itself).
3593let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
35943595if cc == Cc::Yes {
3596// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3597 // - The `--sysroot` flag.
3598 // - The `-isysroot` flag.
3599 // - The `SDKROOT` environment variable.
3600 //
3601 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3602 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3603 // only applies to include header files, but on Apple targets it also applies to libraries
3604 // and frameworks.
3605 //
3606 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3607 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3608 // primarily because that is the same interface that is used when invoking the tool under
3609 // `xcrun -sdk macosx $tool`.
3610 //
3611 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3612 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3613 //
3614 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3615 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3616 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3617 //
3618 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3619 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3620 // ignoring the value we set here, and instead use their built-in sysroot).
3621cmd.cmd().env("SDKROOT", &sdkroot);
3622 } else {
3623// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3624 // read by the linker, so it's really the only option.
3625 //
3626 // This is also what Clang does.
3627cmd.link_arg("-syslibroot");
3628cmd.link_arg(&sdkroot);
3629 }
36303631Some(sdkroot)
3632}
36333634fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3635if let Ok(sdkroot) = env::var("SDKROOT") {
3636let p = PathBuf::from(&sdkroot);
36373638// Ignore invalid SDKs, similar to what clang does:
3639 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3640 //
3641 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3642 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3643 // clearly set for the wrong platform.
3644 //
3645 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3646match &*apple::sdk_name(&sess.target).to_lowercase() {
3647"appletvos"
3648if sdkroot.contains("TVSimulator.platform")
3649 || sdkroot.contains("MacOSX.platform") => {}
3650"appletvsimulator"
3651if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3652"iphoneos"
3653if sdkroot.contains("iPhoneSimulator.platform")
3654 || sdkroot.contains("MacOSX.platform") => {}
3655"iphonesimulator"
3656if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3657 }
3658"macosx"
3659if sdkroot.contains("iPhoneOS.platform")
3660 || sdkroot.contains("iPhoneSimulator.platform")
3661 || sdkroot.contains("AppleTVOS.platform")
3662 || sdkroot.contains("AppleTVSimulator.platform")
3663 || sdkroot.contains("WatchOS.platform")
3664 || sdkroot.contains("WatchSimulator.platform")
3665 || sdkroot.contains("XROS.platform")
3666 || sdkroot.contains("XRSimulator.platform") => {}
3667"watchos"
3668if sdkroot.contains("WatchSimulator.platform")
3669 || sdkroot.contains("MacOSX.platform") => {}
3670"watchsimulator"
3671if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3672"xros"
3673if sdkroot.contains("XRSimulator.platform")
3674 || sdkroot.contains("MacOSX.platform") => {}
3675"xrsimulator"
3676if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3677// Ignore `SDKROOT` if it's not a valid path.
3678_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3679_ => return Some(p),
3680 }
3681 }
36823683 apple::get_sdk_root(sess)
3684}
36853686/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3687/// invoke it:
3688/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3689/// - or any `lld` available to `cc`.
3690fn add_lld_args(
3691 cmd: &mut dyn Linker,
3692 sess: &Session,
3693 flavor: LinkerFlavor,
3694 self_contained_components: LinkSelfContainedComponents,
3695) {
3696{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:3696",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(3696u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("add_lld_args requested, flavor: \'{0:?}\', target self-contained components: {1:?}",
flavor, self_contained_components) as &dyn Value))])
});
} else { ; }
};debug!(
3697"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3698 flavor, self_contained_components,
3699 );
37003701// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3702 // we don't need to do anything.
3703if !(flavor.uses_cc() && flavor.uses_lld()) {
3704return;
3705 }
37063707// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3708 // directories to the tool's search path, depending on a mix between what users can specify on
3709 // the CLI, and what the target spec enables (as it can't disable components):
3710 // - if the self-contained linker is enabled on the CLI or by the target spec,
3711 // - and if the self-contained linker is not disabled on the CLI.
3712let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3713let self_contained_target = self_contained_components.is_linker_enabled();
37143715let self_contained_linker = self_contained_cli || self_contained_target;
3716if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3717let mut linker_path_exists = false;
3718for path in sess.get_tools_search_paths(false) {
3719let linker_path = path.join("gcc-ld");
3720 linker_path_exists |= linker_path.exists();
3721 cmd.cc_arg({
3722let mut arg = OsString::from("-B");
3723 arg.push(linker_path);
3724 arg
3725 });
3726 }
3727if !linker_path_exists {
3728// As a sanity check, we emit an error if none of these paths exist: we want
3729 // self-contained linking and have no linker.
3730sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3731 }
3732 }
37333734// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3735 // `lld` as the linker.
3736 //
3737 // Note that wasm targets skip this step since the only option there anyway
3738 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3739 // this, `wasm-component-ld`, which is overridden if this option is passed.
3740if !sess.target.is_like_wasm {
3741cmd.cc_arg("-fuse-ld=lld");
3742 }
37433744if !flavor.is_gnu() {
3745// Tell clang to use a non-default LLD flavor.
3746 // Gcc doesn't understand the target option, but we currently assume
3747 // that gcc is not used for Apple and Wasm targets (#97402).
3748 //
3749 // Note that we don't want to do that by default on macOS: e.g. passing a
3750 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3751 // shown in issue #101653 and the discussion in PR #101792.
3752 //
3753 // It could be required in some cases of cross-compiling with
3754 // LLD, but this is generally unspecified, and we don't know
3755 // which specific versions of clang, macOS SDK, host and target OS
3756 // combinations impact us here.
3757 //
3758 // So we do a simple first-approximation until we know more of what the
3759 // Apple targets require (and which would be handled prior to hitting this
3760 // LLD codepath anyway), but the expectation is that until then
3761 // this should be manually passed if needed. We specify the target when
3762 // targeting a different linker flavor on macOS, and that's also always
3763 // the case when targeting WASM.
3764if sess.target.linker_flavor != sess.host.linker_flavor {
3765cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3766 }
3767 }
3768}
37693770// gold has been deprecated with binutils 2.44
3771// and is known to behave incorrectly around Rust programs.
3772// There have been reports of being unable to bootstrap with gold:
3773// https://github.com/rust-lang/rust/issues/139425
3774// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3775// emitted with `#[used(linker)]`.
3776fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3777use object::read::elf::{FileHeader, SectionHeader};
3778use object::read::{ReadCache, ReadRef, Result};
3779use object::{Endianness, elf};
37803781fn elf_has_gold_version_note<'a>(
3782 elf: &impl FileHeader,
3783 data: impl ReadRef<'a>,
3784 ) -> Result<bool> {
3785let endian = elf.endian()?;
37863787let section =
3788 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3789if let Some((_, section)) = section3790 && let Some(mut notes) = section.notes(endian, data)?
3791{
3792return Ok(notes.any(|note| {
3793note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3794 }));
3795 }
37963797Ok(false)
3798 }
37993800let data = ReadCache::new(BufReader::new(File::open(path)?));
38013802let was_linked_with_gold = if sess.target.pointer_width == 64 {
3803let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3804 elf_has_gold_version_note(elf, &data)?
3805} else if sess.target.pointer_width == 32 {
3806let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3807 elf_has_gold_version_note(elf, &data)?
3808} else {
3809return Ok(());
3810 };
38113812if was_linked_with_gold {
3813let mut warn =
3814sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3815warn.help("consider using LLD or ld from GNU binutils instead");
3816warn.emit();
3817 }
3818Ok(())
3819}