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::jobserver;
20use rustc_data_structures::memmap::Mmap;
21use rustc_data_structures::temp_dir::MaybeTempDir;
22use rustc_errors::DiagCtxtHandle;
23use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_lint_defs::builtin::{LINKER_INFO, LINKER_MESSAGES};
26use rustc_macros::Diagnostic;
27use rustc_metadata::EncodedMetadata;
28use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
29use rustc_middle::diagnostics::DuplicateEiiImpls;
30use rustc_middle::lint::emit_lint_base;
31use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
32use rustc_middle::middle::dependency_format::Linkage;
33use rustc_middle::middle::exported_symbols::SymbolExportKind;
34use rustc_session::config::{
35self, CFGuard, DebugInfo, InstrumentMcount, LinkerFeaturesCli, LinkerJobs, OutFileName,
36OutputFilenames, OutputType, PrintKind, SplitDwarfKind, Strip,
37};
38use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
39use rustc_session::search_paths::PathKind;
40/// For all the linkers we support, and information they might
41/// need out of the shared crate context before we get rid of it.
42use rustc_session::{Session, filesearch};
43use rustc_span::{Symbol, bug};
44use rustc_structures::{CrateType, NativeLibKind};
45use rustc_target::spec::crt_objects::CrtObjects;
46use rustc_target::spec::{
47Arch, BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
48LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
49RelroLevel, SanitizerSet, SplitDebuginfo,
50};
51use tracing::{debug, info, warn};
5253use super::archive::{
54AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind, ArchiveSymbols,
55};
56use super::command::Command;
57use super::linker::{self, Linker};
58use super::metadata::{MetadataPosition, create_wrapper_file};
59use super::rmeta_link::RmetaLinkCache;
60use super::rpath::{self, RPathConfig};
61use super::{apple, rmeta_link, symbol_export, versioned_llvm_target};
62use crate::base::needs_allocator_shim_for_linking;
63use crate::{
64CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, SymbolExport,
65diagnostics,
66};
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}
7576fn eii_impl_crate_name(crate_info: &CrateInfo, cnum: CrateNum) -> Symbol {
77if cnum == LOCAL_CRATE { crate_info.local_crate_name } else { crate_info.crate_name[&cnum] }
78}
7980fn check_externally_implementable_item_linkage(sess: &Session, crate_info: &CrateInfo) {
81if crate_info.eii_linkage.is_empty() {
82return;
83 }
8485// A crate can request multiple linked outputs with overlapping dependency
86 // formats, so report each underlying conflict once.
87let mut emitted = FxHashSet::default();
8889// This needs the dependency formats selected for the final artifact. The
90 // earlier EII pass still handles missing impls and duplicate explicit impls.
91for dependency_formats in crate_info.dependency_formats.values() {
92for (eii_index, eii) in crate_info.eii_linkage.iter().enumerate() {
93let Some(explicit_impl) = eii.impls.first() else {
94continue;
95 };
96// If the explicit impl is already coming from a dylib, that dylib
97 // has already resolved the default-vs-explicit choice.
98if #[allow(non_exhaustive_omitted_patterns)] match dependency_formats.get(explicit_impl.impl_crate)
{
Some(Linkage::Dynamic | Linkage::IncludedFromDylib) => true,
_ => false,
}matches!(
99 dependency_formats.get(explicit_impl.impl_crate),
100Some(Linkage::Dynamic | Linkage::IncludedFromDylib)
101 ) {
102continue;
103 }
104105let Some(default_impl) = &eii.default_impl else {
106continue;
107 };
108if !#[allow(non_exhaustive_omitted_patterns)] match dependency_formats.get(default_impl.impl_crate)
{
Some(Linkage::Dynamic | Linkage::IncludedFromDylib) => true,
_ => false,
}matches!(
109 dependency_formats.get(default_impl.impl_crate),
110Some(Linkage::Dynamic | Linkage::IncludedFromDylib)
111 ) {
112continue;
113 }
114115if !emitted.insert(eii_index) {
116continue;
117 }
118119 sess.dcx().emit_err(DuplicateEiiImpls {
120 name: eii.name,
121 first_span: explicit_impl.span,
122 first_crate: eii_impl_crate_name(crate_info, explicit_impl.impl_crate),
123 second_span: default_impl.span,
124 second_crate: eii_impl_crate_name(crate_info, default_impl.impl_crate),
125 help: (),
126 additional_crates: None,
127 num_additional_crates: 0,
128 additional_crate_names: String::new(),
129 });
130 }
131 }
132}
133134/// The fallback directories are passed to linker, but not used when rustc does the search,
135/// because in the latter case the set of fallback directories cannot always be determined
136/// consistently at the moment.
137struct NativeLibSearchFallback<'a> {
138 self_contained_components: LinkSelfContainedComponents,
139 apple_sdk_root: Option<&'a Path>,
140}
141142fn walk_native_lib_search_dirs<R>(
143 sess: &Session,
144 fallback: Option<NativeLibSearchFallback<'_>>,
145mut f: impl FnMut(&Path, bool/*is_framework*/) -> ControlFlow<R>,
146) -> ControlFlow<R> {
147// Library search paths explicitly supplied by user (`-L` on the command line).
148for search_path in sess.target_filesearch().cli_search_paths(PathKind::Native) {
149 f(&search_path.dir, false)?;
150 }
151for search_path in sess.target_filesearch().cli_search_paths(PathKind::Framework) {
152// Frameworks are looked up strictly in framework-specific paths.
153if search_path.kind != PathKind::All {
154 f(&search_path.dir, true)?;
155 }
156 }
157158let Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root }) = fallback159else {
160return ControlFlow::Continue(());
161 };
162163// The toolchain ships some native library components and self-contained linking was enabled.
164 // Add the self-contained library directory to search paths.
165if self_contained_components.intersects(
166LinkSelfContainedComponents::LIBC167 | LinkSelfContainedComponents::UNWIND168 | LinkSelfContainedComponents::MINGW,
169 ) {
170 f(&sess.target_tlib_path.dir.join("self-contained"), false)?;
171 }
172173let has_shared_llvm_apple_darwin =
174sess.target.is_like_darwin && sess.target_tlib_path.dir.join("libLLVM.dylib").exists();
175176// Toolchains for some targets may ship `libunwind.a`, but place it into the main sysroot
177 // library directory instead of the self-contained directories.
178 // Sanitizer libraries have the same issue and are also linked by name on Apple targets.
179 // The targets here should be in sync with `copy_third_party_objects` in bootstrap.
180 // On Apple targets, shared LLVM is linked by name, so when `libLLVM.dylib` is
181 // present in the target libdir, add that directory to the linker search path.
182 // FIXME: implement `-Clink-self-contained=+/-unwind,+/-sanitizers`, move the shipped libunwind
183 // and sanitizers to self-contained directory, and stop adding this search path.
184 // FIXME: On AIX this also has the side-effect of making the list of library search paths
185 // non-empty, which is needed or the linker may decide to record the LIBPATH env, if
186 // defined, as the search path instead of appending the default search paths.
187if sess.target.cfg_abi == CfgAbi::Fortanix188 || sess.target.os == Os::Linux189 || sess.target.os == Os::Fuchsia190 || sess.target.is_like_aix
191 || sess.target.is_like_darwin
192 && (!sess.sanitizers().is_empty() || has_shared_llvm_apple_darwin)
193 || sess.target.os == Os::Windows194 && sess.target.env == Env::Gnu195 && sess.target.cfg_abi == CfgAbi::Llvm196 {
197 f(&sess.target_tlib_path.dir, false)?;
198 }
199200// Mac Catalyst uses the macOS SDK, but to link to iOS-specific frameworks
201 // we must have the support library stubs in the library search path (#121430).
202if let Some(sdk_root) = apple_sdk_root203 && sess.target.env == Env::MacAbi204 {
205 f(&sdk_root.join("System/iOSSupport/usr/lib"), false)?;
206 f(&sdk_root.join("System/iOSSupport/System/Library/Frameworks"), true)?;
207 }
208209 ControlFlow::Continue(())
210}
211212pub(super) fn try_find_native_static_library(
213 sess: &Session,
214 name: &str,
215 verbatim: bool,
216) -> Option<PathBuf> {
217let default = sess.staticlib_components(verbatim);
218let formats = if verbatim {
219::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default]))vec![default]220 } else {
221// On Windows, static libraries sometimes show up as libfoo.a and other
222 // times show up as foo.lib
223let unix = ("lib", ".a");
224if default == unix { ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default]))vec![default] } else { ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default, unix]))vec![default, unix] }
225 };
226227walk_native_lib_search_dirs(sess, None, |dir, is_framework| {
228if !is_framework {
229for (prefix, suffix) in &formats {
230let test = dir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"));
231if test.exists() {
232return ControlFlow::Break(test);
233 }
234 }
235 }
236 ControlFlow::Continue(())
237 })
238 .break_value()
239}
240241pub(super) fn try_find_native_dynamic_library(
242 sess: &Session,
243 name: &str,
244 verbatim: bool,
245) -> Option<PathBuf> {
246let default = sess.staticlib_components(verbatim);
247let formats = if verbatim {
248::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default]))vec![default]249 } else {
250// While the official naming convention for MSVC import libraries
251 // is foo.lib, Meson follows the libfoo.dll.a convention to
252 // disambiguate .a for static libraries
253let meson = ("lib", ".dll.a");
254// and MinGW uses .a altogether
255let mingw = ("lib", ".a");
256::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default, meson, mingw]))vec![default, meson, mingw]257 };
258259walk_native_lib_search_dirs(sess, None, |dir, is_framework| {
260if !is_framework {
261for (prefix, suffix) in &formats {
262let test = dir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"));
263if test.exists() {
264return ControlFlow::Break(test);
265 }
266 }
267 }
268 ControlFlow::Continue(())
269 })
270 .break_value()
271}
272273pub(super) fn find_native_static_library(name: &str, verbatim: bool, sess: &Session) -> PathBuf {
274try_find_native_static_library(sess, name, verbatim).unwrap_or_else(|| {
275sess.dcx().emit_fatal(diagnostics::MissingNativeLibrary::new(name, verbatim))
276 })
277}
278279/// If `lib` is a static library that is bundled into the rlib as a packed archive, returns the
280/// file name of that archive. Returns `None` for libraries that are instead unpacked into loose
281/// object files, or not bundled at all.
282fn find_bundled_library(
283 lib: &NativeLib,
284 sess: &Session,
285 crate_types: &[CrateType],
286) -> Option<Symbol> {
287if let NativeLibKind::Static { bundle: Some(true) | None, whole_archive, .. } = lib.kind
288 && crate_types.iter().any(|t| #[allow(non_exhaustive_omitted_patterns)] match t {
&CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(t, &CrateType::Rlib | CrateType::StaticLib))
289 && (sess.opts.unstable_opts.packed_bundled_libs
290 || lib.cfg.is_some()
291 || whole_archive == Some(true))
292 {
293return find_native_static_library(lib.name.as_str(), lib.verbatim, sess)
294 .file_name()
295 .and_then(|s| s.to_str())
296 .map(Symbol::intern);
297 }
298None299}
300301/// Performs the linkage portion of the compilation phase. This will generate all
302/// of the requested outputs for this compilation session.
303pub fn link_binary(
304 sess: &Session,
305 archive_builder_builder: &dyn ArchiveBuilderBuilder,
306 compiled_modules: CompiledModules,
307 crate_info: CrateInfo,
308 metadata: EncodedMetadata,
309 outputs: &OutputFilenames,
310 codegen_backend: &'static str,
311) {
312let _timer = sess.timer("link_binary");
313let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
314let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
315let mut rmeta_link_cache = RmetaLinkCache::default();
316317if outputs.outputs.should_link() {
318sess.time("check_externally_implementable_item_linkage", || {
319check_externally_implementable_item_linkage(sess, &crate_info);
320 });
321sess.dcx().abort_if_errors();
322 }
323324for &crate_type in &crate_info.crate_types {
325// Ignore executable crates if we have -Z no-codegen, as they will error.
326if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
327 && !output_metadata
328 && crate_type == CrateType::Executable
329 {
330continue;
331 }
332333if invalid_output_for_target(sess, crate_type) {
334::rustc_span::macros::bug_impl(None,
format_args!("invalid output type `{0:?}` for target `{1}`", crate_type,
sess.opts.target_triple), Location::caller());bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
335 }
336337 sess.time("link_binary_check_files_are_writeable", || {
338for m in &compiled_modules.modules {
339if let Some(obj) = &m.object {
340 check_file_is_writeable(obj, sess);
341 }
342if let Some(obj) = &m.global_asm_object {
343 check_file_is_writeable(obj, sess);
344 }
345 }
346 });
347348if outputs.outputs.should_link() {
349let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
350let tmpdir = TempDirBuilder::new()
351 .prefix("rustc")
352 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
353 .unwrap_or_else(|error| {
354 sess.dcx().emit_fatal(diagnostics::CreateTempDir { error })
355 });
356let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
357358let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
359let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
360match crate_type {
361 CrateType::Rlib => {
362let _timer = sess.timer("link_rlib");
363{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:363",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(363u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("preparing rlib to {0:?}",
out_filename) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("preparing rlib to {:?}", out_filename);
364 link_rlib(
365 sess,
366 archive_builder_builder,
367&compiled_modules,
368&crate_info,
369&metadata,
370 RlibFlavor::Normal,
371&path,
372 )
373 .build(&out_filename, None);
374 }
375 CrateType::StaticLib => {
376 link_staticlib(
377 sess,
378 archive_builder_builder,
379&mut rmeta_link_cache,
380&compiled_modules,
381&crate_info,
382&metadata,
383&out_filename,
384&path,
385 );
386 }
387_ => {
388 link_natively(
389 sess,
390 archive_builder_builder,
391&mut rmeta_link_cache,
392 crate_type,
393&out_filename,
394&compiled_modules,
395&crate_info,
396&metadata,
397 path.as_ref(),
398 codegen_backend,
399 );
400 }
401 }
402if sess.opts.json_artifact_notifications {
403 sess.dcx().emit_artifact_notification(&out_filename, "link");
404 }
405406if sess.prof.enabled()
407 && let Some(artifact_name) = out_filename.file_name()
408 {
409// Record size for self-profiling
410let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
411412 sess.prof.artifact_size(
413"linked_artifact",
414 artifact_name.to_string_lossy(),
415 file_size,
416 );
417 }
418419if sess.target.binary_format == BinaryFormat::Elf {
420if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
421{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:421",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(421u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("err")
}> =
::tracing::__macro_support::FieldName::new("err");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Error while checking if gold was the linker")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&err)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!(?err, "Error while checking if gold was the linker");
422 }
423 }
424425if output.is_stdout() {
426if output.is_tty() {
427 sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
428 shorthand: OutputType::Exe.shorthand(),
429 });
430 } else if let Err(e) = copy_to_stdout(&out_filename) {
431 sess.dcx().emit_err(diagnostics::CopyPath::new(
432&out_filename,
433 output.as_path(),
434 e,
435 ));
436 }
437 tempfiles_for_stdout_output.push(out_filename);
438 }
439 }
440 }
441442// Remove the temporary object file and metadata if we aren't saving temps.
443sess.time("link_binary_remove_temps", || {
444// If the user requests that temporaries are saved, don't delete any.
445if sess.opts.cg.save_temps {
446return;
447 }
448449let maybe_remove_temps_from_module =
450 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
451if !preserve_objects && let Some(ref obj) = module.object {
452ensure_removed(sess.dcx(), obj);
453 }
454455if !preserve_objects && let Some(ref obj) = module.global_asm_object {
456ensure_removed(sess.dcx(), obj);
457 }
458459if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
460ensure_removed(sess.dcx(), dwo_obj);
461 }
462 };
463464let remove_temps_from_module =
465 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
466467// Otherwise, always remove the allocator module temporaries.
468if let Some(ref allocator_module) = compiled_modules.allocator_module {
469remove_temps_from_module(allocator_module);
470 }
471472// Remove the temporary files if output goes to stdout
473for temp in tempfiles_for_stdout_output {
474 ensure_removed(sess.dcx(), &temp);
475 }
476477// If no requested outputs require linking, then the object temporaries should
478 // be kept.
479if !sess.opts.output_types.should_link() {
480return;
481 }
482483// Potentially keep objects for their debuginfo.
484let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
485{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:485",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(485u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("preserve_objects")
}> =
::tracing::__macro_support::FieldName::new("preserve_objects");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("preserve_dwarf_objects")
}> =
::tracing::__macro_support::FieldName::new("preserve_dwarf_objects");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&preserve_objects)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&preserve_dwarf_objects)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?preserve_objects, ?preserve_dwarf_objects);
486487for module in &compiled_modules.modules {
488 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
489 }
490 });
491}
492493// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
494// crate types must use the same dependency formats.
495pub fn each_linked_rlib(
496 info: &CrateInfo,
497 crate_type: Option<CrateType>,
498 f: &mut dyn FnMut(CrateNum, &Path),
499) -> Result<(), diagnostics::LinkRlibError> {
500let fmts = if let Some(crate_type) = crate_type {
501let Some(fmts) = info.dependency_formats.get(&crate_type) else {
502return Err(diagnostics::LinkRlibError::MissingFormat);
503 };
504505fmts506 } else {
507let mut dep_formats = info.dependency_formats.iter();
508let (ty1, list1) = dep_formats.next().ok_or(diagnostics::LinkRlibError::MissingFormat)?;
509if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
510return Err(diagnostics::LinkRlibError::IncompatibleDependencyFormats {
511 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
512 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
513 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
514 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
515 });
516 }
517list1518 };
519520let used_dep_crates = info.used_crates.iter();
521for &cnum in used_dep_crates {
522match fmts.get(cnum) {
523Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
524Some(_) => {}
525None => return Err(diagnostics::LinkRlibError::MissingFormat),
526 }
527let crate_name = info.crate_name[&cnum];
528let used_crate_source = &info.used_crate_source[&cnum];
529if let Some(path) = &used_crate_source.rlib {
530 f(cnum, path);
531 } else if used_crate_source.rmeta.is_some() {
532return Err(diagnostics::LinkRlibError::OnlyRmetaFound { crate_name });
533 } else {
534return Err(diagnostics::LinkRlibError::NotFound { crate_name });
535 }
536 }
537Ok(())
538}
539540/// Create an 'rlib'.
541///
542/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
543/// The rlib primarily contains the object file of the crate, but it also some of the object files
544/// from native libraries.
545fn link_rlib<'a>(
546 sess: &'a Session,
547 archive_builder_builder: &dyn ArchiveBuilderBuilder,
548 compiled_modules: &CompiledModules,
549 crate_info: &CrateInfo,
550 metadata: &EncodedMetadata,
551 flavor: RlibFlavor,
552 tmpdir: &MaybeTempDir,
553) -> Box<dyn ArchiveBuilder + 'a> {
554let mut ab = archive_builder_builder.new_archive_builder(sess);
555556// Pre-compute the list of Rust object filenames and materialize the rmeta-link
557 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
558 // placed immediately after metadata in the archive, so consumers can find
559 // it without iterating every archive member.
560let rust_object_files: Vec<String> = compiled_modules561 .modules
562 .iter()
563 .filter_map(|m| m.object.as_ref())
564 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
565 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
566 .collect();
567568let native_lib_filenames: Vec<Option<Symbol>> = crate_info569 .used_libraries
570 .iter()
571 .map(|lib| find_bundled_library(lib, sess, &crate_info.crate_types))
572 .collect();
573574let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
575let native_lib_filenames: Vec<Option<String>> =
576native_lib_filenames.iter().map(|f| f.map(|s| s.to_string())).collect();
577let metadata_link = rmeta_link::RmetaLink { rust_object_files, native_lib_filenames };
578let metadata_link_data = metadata_link.encode();
579let (wrapper, _) =
580create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
581Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
582 } else {
583None584 };
585586let trailing_metadata = match flavor {
587 RlibFlavor::Normal => {
588let (metadata, metadata_position) =
589create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
590let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
591match metadata_position {
592 MetadataPosition::First => {
593// Most of the time metadata in rlib files is wrapped in a "dummy" object
594 // file for the target platform so the rlib can be processed entirely by
595 // normal linkers for the platform. Sometimes this is not possible however.
596 // If it is possible however, placing the metadata object first improves
597 // performance of getting metadata from rlibs.
598ab.add_file(&metadata, ArchiveEntryKind::Other);
599// Place the rmeta-link member immediately after metadata so consumers
600 // can find it without iterating the whole archive.
601if let Some(file) = &metadata_link_file {
602ab.add_file(file, ArchiveEntryKind::Other);
603 }
604None605 }
606 MetadataPosition::Last => Some(metadata),
607 }
608 }
609610 RlibFlavor::StaticlibBase => None,
611 };
612613for m in &compiled_modules.modules {
614if let Some(obj) = m.object.as_ref() {
615 ab.add_file(obj, ArchiveEntryKind::RustObj);
616 }
617618if let Some(obj) = m.global_asm_object.as_ref() {
619 ab.add_file(obj, ArchiveEntryKind::RustObj);
620 }
621622if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
623 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
624 }
625 }
626627match flavor {
628 RlibFlavor::Normal => {}
629 RlibFlavor::StaticlibBase => {
630if let Some(m) = &compiled_modules.allocator_module {
631if let Some(obj) = &m.object {
632ab.add_file(obj, ArchiveEntryKind::RustObj);
633 }
634if let Some(obj) = &m.global_asm_object {
635ab.add_file(obj, ArchiveEntryKind::RustObj);
636 }
637 }
638 }
639 }
640641// Used if packed_bundled_libs flag enabled.
642let mut packed_bundled_libs = Vec::new();
643644// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
645 // we may not be configured to actually include a static library if we're
646 // adding it here. That's because later when we consume this rlib we'll
647 // decide whether we actually needed the static library or not.
648 //
649 // To do this "correctly" we'd need to keep track of which libraries added
650 // which object files to the archive. We don't do that here, however. The
651 // #[link(cfg(..))] feature is unstable, though, and only intended to get
652 // liblibc working. In that sense the check below just indicates that if
653 // there are any libraries we want to omit object files for at link time we
654 // just exclude all custom object files.
655 //
656 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
657 // feature then we'll need to figure out how to record what objects were
658 // loaded from the libraries found here and then encode that into the
659 // metadata of the rlib we're generating somehow.
660for (i, lib) in crate_info.used_libraries.iter().enumerate() {
661let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
662continue;
663 };
664if flavor == RlibFlavor::Normal
665 && let Some(filename) = native_lib_filenames[i]
666 {
667let path = find_native_static_library(filename.as_str(), true, sess);
668let src = read(path).unwrap_or_else(|e| {
669 sess.dcx().emit_fatal(diagnostics::ReadFileError { message: e })
670 });
671let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
672let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
673 packed_bundled_libs.push(wrapper_file);
674 } else {
675let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
676 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
677 sess.dcx().emit_fatal(diagnostics::AddNativeLibrary { library_path: path, error })
678 });
679 }
680 }
681682// On Windows, we add the raw-dylib import libraries to the rlibs already.
683 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
684 // Instead, we add all raw-dylibs to the final link on ELF.
685if sess.target.is_like_windows {
686for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
687 sess,
688 archive_builder_builder,
689 crate_info.used_libraries.iter(),
690 tmpdir.as_ref(),
691true,
692 ) {
693 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
694 sess.dcx()
695 .emit_fatal(diagnostics::AddNativeLibrary { library_path: output_path, error });
696 });
697 }
698 }
699700if let Some(trailing_metadata) = trailing_metadata {
701// Note that it is important that we add all of our non-object "magical
702 // files" *after* all of the object files in the archive. The reason for
703 // this is as follows:
704 //
705 // * When performing LTO, this archive will be modified to remove
706 // objects from above. The reason for this is described below.
707 //
708 // * When the system linker looks at an archive, it will attempt to
709 // determine the architecture of the archive in order to see whether its
710 // linkable.
711 //
712 // The algorithm for this detection is: iterate over the files in the
713 // archive. Skip magical SYMDEF names. Interpret the first file as an
714 // object file. Read architecture from the object file.
715 //
716 // * As one can probably see, if "metadata" and "foo.bc" were placed
717 // before all of the objects, then the architecture of this archive would
718 // not be correctly inferred once 'foo.o' is removed.
719 //
720 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
721 // file for the target platform so the rlib can be processed entirely by
722 // normal linkers for the platform. Sometimes this is not possible however.
723 //
724 // Basically, all this means is that this code should not move above the
725 // code above.
726ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
727// Place the rmeta-link member immediately after metadata so consumers can
728 // find it without iterating the whole archive.
729if let Some(file) = &metadata_link_file {
730ab.add_file(file, ArchiveEntryKind::Other);
731 }
732 }
733734// Add all bundled static native library dependencies.
735 // Archives added to the end of .rlib archive, see comment above for the reason.
736for lib in packed_bundled_libs {
737 ab.add_file(&lib, ArchiveEntryKind::Other)
738 }
739740ab741}
742743/// Create a static archive.
744///
745/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
746/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
747/// dependencies as well.
748///
749/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
750/// library dependencies that they're not linked in.
751///
752/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
753/// object file (and also don't prepare the archive with a metadata file).
754fn link_staticlib(
755 sess: &Session,
756 archive_builder_builder: &dyn ArchiveBuilderBuilder,
757 rmeta_link_cache: &mut RmetaLinkCache,
758 compiled_modules: &CompiledModules,
759 crate_info: &CrateInfo,
760 metadata: &EncodedMetadata,
761 out_filename: &Path,
762 tempdir: &MaybeTempDir,
763) {
764{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:764",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(764u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("preparing staticlib to {0:?}",
out_filename) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("preparing staticlib to {:?}", out_filename);
765let mut ab = link_rlib(
766sess,
767archive_builder_builder,
768compiled_modules,
769crate_info,
770metadata,
771 RlibFlavor::StaticlibBase,
772tempdir,
773 );
774let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
775776let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
777let lto = are_upstream_rust_objects_already_included(sess)
778 && !ignored_for_lto(sess, crate_info, cnum);
779780let native_libs = &crate_info.native_libraries[&cnum];
781let bundled_filenames =
782rmeta_link_cache.native_lib_filenames(&sess.target, path, native_libs);
783let relevant_libs: FxIndexSet<_> = native_libs784 .iter()
785 .enumerate()
786 .filter(|(_, lib)| relevant_lib(sess, lib))
787 .filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
788 .collect();
789790let bundled_libs: FxIndexSet<_> = native_libs791 .iter()
792 .enumerate()
793 .filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
794 .collect();
795ab.add_archive(
796path,
797 AddArchiveKind::Rlib(rmeta_link_cache, &|fname: &str, entry_kind| {
798// Ignore metadata and rmeta-link files.
799if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
800return true;
801 }
802803// Don't include Rust objects if LTO is enabled.
804if lto && entry_kind == ArchiveEntryKind::RustObj {
805return true;
806 }
807808// Skip objects for bundled libs.
809if bundled_libs.contains(&Symbol::intern(fname)) {
810return true;
811 }
812813false
814}),
815 )
816 .unwrap();
817818archive_builder_builder819 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
820 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
821822for filename in relevant_libs.iter() {
823let joined = tempdir.as_ref().join(filename.as_str());
824let path = joined.as_path();
825 ab.add_archive(path, AddArchiveKind::Other).unwrap();
826 }
827828all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
829 });
830if let Err(e) = res {
831sess.dcx().emit_fatal(e);
832 }
833834let hide = sess.opts.unstable_opts.staticlib_hide_internal_symbols;
835let rename = sess.opts.unstable_opts.staticlib_rename_internal_symbols;
836837let hide_supported =
838#[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);
839// Rename only rewrites symbol names, so it also works on COFF; hide
840 // needs a visibility concept COFF lacks.
841let rename_supported = #[allow(non_exhaustive_omitted_patterns)] match sess.target.binary_format {
BinaryFormat::Elf | BinaryFormat::MachO | BinaryFormat::Coff => true,
_ => false,
}matches!(
842 sess.target.binary_format,
843 BinaryFormat::Elf | BinaryFormat::MachO | BinaryFormat::Coff
844 );
845846let exported_symbols = if hide || rename {
847if hide && !hide_supported {
848sess.dcx().emit_warn(diagnostics::StaticlibHideInternalSymbolsUnsupported {
849 binary_format: sess.target.archive_format.to_string(),
850 });
851 }
852if rename && !rename_supported {
853sess.dcx().emit_warn(diagnostics::StaticlibRenameInternalSymbolsUnsupported {
854 binary_format: sess.target.archive_format.to_string(),
855 });
856 }
857if (hide && hide_supported) || (rename && rename_supported) {
858crate_info859 .exported_symbols
860 .get(&CrateType::StaticLib)
861 .map(|symbols| symbols.iter().map(|symbol| symbol.name.clone()).collect())
862 } else {
863None864 }
865 } else {
866None867 };
868869let symbols = exported_symbols.map(|exported| ArchiveSymbols {
870exported,
871 rename_suffix: (rename && rename_supported)
872 .then(|| crate_info.symbol_rename_suffix.clone()),
873// A warning was already emitted above if hiding was requested for an
874 // unsupported format; don't also ask the backend to hide there.
875hide: hide && hide_supported,
876 });
877878ab.build(out_filename, symbols);
879880let crates = crate_info.used_crates.iter();
881882let fmts = crate_info883 .dependency_formats
884 .get(&CrateType::StaticLib)
885 .expect("no dependency formats for staticlib");
886887let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
888for &cnum in crates {
889let Some(Linkage::Dynamic) = fmts.get(cnum) else {
890continue;
891 };
892let crate_name = crate_info.crate_name[&cnum];
893let used_crate_source = &crate_info.used_crate_source[&cnum];
894if let Some(path) = &used_crate_source.dylib {
895 all_rust_dylibs.push(&**path);
896 } else if used_crate_source.rmeta.is_some() {
897 sess.dcx().emit_fatal(diagnostics::LinkRlibError::OnlyRmetaFound { crate_name });
898 } else {
899 sess.dcx().emit_fatal(diagnostics::LinkRlibError::NotFound { crate_name });
900 }
901 }
902903all_native_libs.extend_from_slice(&crate_info.used_libraries);
904905for print in &sess.opts.prints {
906if print.kind == PrintKind::NativeStaticLibs {
907 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
908 }
909 }
910}
911912/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
913/// DWARF package.
914fn link_dwarf_object(
915 sess: &Session,
916 compiled_modules: &CompiledModules,
917 crate_info: &CrateInfo,
918 executable_out_filename: &Path,
919) {
920let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
921dwp_out_filename.push(".dwp");
922{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:922",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(922u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dwp_out_filename")
}> =
::tracing::__macro_support::FieldName::new("dwp_out_filename");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("executable_out_filename")
}> =
::tracing::__macro_support::FieldName::new("executable_out_filename");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dwp_out_filename)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&executable_out_filename)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?dwp_out_filename, ?executable_out_filename);
923924#[derive(#[automatically_derived]impl<Relocations: ::core::default::Default>
::core::default::Default for ThorinSession<Relocations> {
#[inline]
fn default() -> Self {
ThorinSession {
arena_data: ::core::default::Default::default(),
arena_mmap: ::core::default::Default::default(),
arena_relocations: ::core::default::Default::default(),
}
}
}Default)]
925struct ThorinSession<Relocations> {
926 arena_data: TypedArena<Vec<u8>>,
927 arena_mmap: TypedArena<Mmap>,
928 arena_relocations: TypedArena<Relocations>,
929 }
930931impl<Relocations> ThorinSession<Relocations> {
932fn alloc_mmap(&self, data: Mmap) -> &Mmap {
933&*self.arena_mmap.alloc(data)
934 }
935 }
936937impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
938fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
939&*self.arena_data.alloc(data)
940 }
941942fn alloc_relocation(&self, data: Relocations) -> &Relocations {
943&*self.arena_relocations.alloc(data)
944 }
945946fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
947let file = File::open(&path)?;
948let mmap = (unsafe { Mmap::map(file) })?;
949Ok(self.alloc_mmap(mmap))
950 }
951 }
952953match sess.time("run_thorin", || -> Result<(), thorin::Error> {
954let thorin_sess = ThorinSession::default();
955let mut package = thorin::DwarfPackage::new(&thorin_sess);
956957// Input objs contain .o/.dwo files from the current crate.
958match sess.opts.unstable_opts.split_dwarf_kind {
959 SplitDwarfKind::Single => {
960for m in &compiled_modules.modules {
961if let Some(input_obj) = &m.object {
962 package.add_input_object(input_obj)?;
963 }
964if let Some(input_obj) = &m.global_asm_object {
965 package.add_input_object(input_obj)?;
966 }
967 }
968 }
969 SplitDwarfKind::Split => {
970for input_obj in
971compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
972 {
973 package.add_input_object(input_obj)?;
974 }
975 }
976 }
977978// Input rlibs contain .o/.dwo files from dependencies.
979let input_rlibs = crate_info980 .used_crate_source
981 .items()
982 .filter_map(|(_, csource)| csource.rlib.as_ref())
983 .into_sorted_stable_ord();
984985for input_rlib in input_rlibs {
986{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:986",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(986u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("input_rlib")
}> =
::tracing::__macro_support::FieldName::new("input_rlib");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&input_rlib)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?input_rlib);
987 package.add_input_object(input_rlib)?;
988 }
989990// Failing to read the referenced objects is expected for dependencies where the path in the
991 // executable will have been cleaned by Cargo, but the referenced objects will be contained
992 // within rlibs provided as inputs.
993 //
994 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
995 // found, but are provided explicitly above.
996 //
997 // Adding an executable is primarily done to make `thorin` check that all the referenced
998 // dwarf objects are found in the end.
999package.add_executable(
1000 executable_out_filename,
1001 thorin::MissingReferencedObjectBehaviour::Skip,
1002 )?;
10031004let output_stream = BufWriter::new(
1005 OpenOptions::new()
1006 .read(true)
1007 .write(true)
1008 .create(true)
1009 .truncate(true)
1010 .open(dwp_out_filename)?,
1011 );
1012let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
1013 package.finish()?.emit(&mut output_stream)?;
1014 output_stream.result()?;
1015 output_stream.into_inner().flush()?;
10161017Ok(())
1018 }) {
1019Ok(()) => {}
1020Err(e) => sess.dcx().emit_fatal(diagnostics::ThorinErrorWrapper(e)),
1021 }
1022}
10231024#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for LinkerOutput {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
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)]
1025#[diag("{$inner}")]
1026/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
1027/// end up with inconsistent languages within the same diagnostic.
1028struct LinkerOutput {
1029 inner: String,
1030}
10311032fn is_msvc_link_exe(sess: &Session) -> bool {
1033let (linker_path, flavor) = linker_and_flavor(sess);
1034sess.target.is_like_msvc
1035 && flavor == LinkerFlavor::Msvc(Lld::No)
1036// Match exactly "link.exe"
1037&& linker_path.to_str() == Some("link.exe")
1038}
10391040fn is_macos_linker(sess: &Session) -> bool {
1041let (_, flavor) = linker_and_flavor(sess);
1042sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(..) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(..))1043}
10441045fn is_windows_gnu_ld(sess: &Session) -> bool {
1046let (_, flavor) = linker_and_flavor(sess);
1047sess.target.is_like_windows
1048 && !sess.target.is_like_msvc
1049 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))1050 && sess.target.options.cfg_abi != CfgAbi::Llvm1051}
10521053fn is_windows_gnu_clang(sess: &Session) -> bool {
1054let (_, flavor) = linker_and_flavor(sess);
1055sess.target.is_like_windows
1056 && !sess.target.is_like_msvc
1057 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))1058 && sess.target.options.cfg_abi == CfgAbi::Llvm1059}
10601061fn report_linker_output(
1062 sess: &Session,
1063 levels: CodegenLintLevelSpecs,
1064 stdout: &[u8],
1065 stderr: &[u8],
1066) {
1067let mut escaped_stderr = escape_string(&stderr);
1068let mut escaped_stdout = escape_string(&stdout);
1069let mut linker_info = String::new();
10701071{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1071",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker stderr:\n{0}",
&escaped_stderr) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker stderr:\n{}", &escaped_stderr);
1072{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1072",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/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::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker stdout:\n{0}",
&escaped_stdout) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &escaped_stdout);
10731074fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
1075let mut output = String::new();
1076if let Ok(str) = str::from_utf8(bytes) {
1077{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1077",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1077u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("line: {0}",
str) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("line: {str}");
1078output = String::with_capacity(str.len());
1079for line in str.lines() {
1080 f(line.trim(), &mut output);
1081 }
1082 }
1083escape_string(output.trim().as_bytes())
1084 }
10851086fn has_lnk_code(line: &str) -> bool {
1087// link.exe diagnostics are structured as `LINK : warning LNK####:` or
1088 // `LINK : fatal error LNK####:`. The code is always followed by a `:`
1089 // that is the second colon in the line, so matching that structure
1090 // instead of scanning for `LNK####` anywhere avoids false positives on
1091 // file names.
1092let Some((code_colon, _)) = line.match_indices(':').nth(1) else {
1093return false;
1094 };
1095let Some(code) = code_colon.checked_sub(7) else {
1096return false;
1097 };
1098let code = &line.as_bytes()[code..code_colon];
1099code.starts_with(b"LNK") && code[3..].iter().all(u8::is_ascii_digit)
1100 }
11011102if is_msvc_link_exe(sess) {
1103{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1103",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1103u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inferred MSVC link.exe")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("inferred MSVC link.exe");
11041105escaped_stdout = for_each(&stdout, |line, output| {
1106// Hide progress messages from link.exe that we don't care about.
1107 // These include localized variants of the English messages (e.g.
1108 // "Creating library ..."), which rustc cannot recognize by text
1109 // without the English language pack.
1110 // See https://github.com/rust-lang/rust/issues/159133
1111 // When incremental linking is enabled and an .ilk exists, but its
1112 // associated .exe is missing, link.exe prints the path of the
1113 // missing .exe followed by:
1114let ilk_but_no_exe =
1115"not found or not built by the last incremental link; performing full link";
1116// LNK6004 is the one code-bearing line that is still informational.
1117if has_lnk_code(line) && !line.ends_with(ilk_but_no_exe) {
1118*output += line;
1119*output += "\r\n"
1120} else {
1121linker_info += line;
1122linker_info += "\r\n";
1123 }
1124 });
1125 } else if is_macos_linker(sess) {
1126{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1126",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1126u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inferred macOS linker")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("inferred macOS linker");
11271128// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
1129let deployment_mismatch = |line: &str| {
1130// ld64 (object files + dylibs) and ld_prime (object files only):
1131(line.starts_with("ld: ")
1132 && line.contains("was built for newer")
1133 && line.contains("than being linked"))
1134// ld_prime (Xcode 15+, dylibs only):
1135|| (line.starts_with("ld: ")
1136 && line.contains("building for")
1137 && line.contains("but linking with")
1138 && line.contains("which was built for newer version"))
1139// lld (ld64.lld / rust-lld):
1140|| line.contains("which is newer than target minimum of")
1141 };
1142// FIXME: This is a real warning we would like to show, but it hits too many crates
1143 // to want to turn it on immediately.
1144let search_path = |line: &str| {
1145line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
1146 };
1147escaped_stderr = for_each(&stderr, |line, output| {
1148// This duplicate library warning is just not helpful at all.
1149if line.starts_with("ld: warning: ignoring duplicate libraries: ")
1150 || deployment_mismatch(line)
1151 || search_path(line)
1152 {
1153linker_info += line;
1154linker_info += "\n";
1155 } else {
1156*output += line;
1157*output += "\n"
1158}
1159 });
1160 } else if is_windows_gnu_ld(sess) {
1161{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1161",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1161u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inferred Windows GNU LD")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("inferred Windows GNU LD");
11621163let mut saw_exclude_symbol = false;
1164// See https://github.com/rust-lang/rust/issues/112368.
1165 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
1166let exclude_symbols = |line: &str| {
1167line.starts_with("Warning: .drectve `-exclude-symbols:")
1168 && line.ends_with("' unrecognized")
1169 };
1170escaped_stderr = for_each(&stderr, |line, output| {
1171if exclude_symbols(line) {
1172saw_exclude_symbol = true;
1173linker_info += line;
1174linker_info += "\n";
1175 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
1176linker_info += line;
1177linker_info += "\n";
1178 } else {
1179*output += line;
1180*output += "\n"
1181}
1182 });
1183 } else if is_windows_gnu_clang(sess) {
1184{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1184",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1184u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("inferred Windows Clang (GNU ABI)")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("inferred Windows Clang (GNU ABI)");
1185escaped_stderr = for_each(&stderr, |line, output| {
1186if line.contains("argument unused during compilation: '-nolibc'") {
1187linker_info += line;
1188linker_info += "\n";
1189 } else {
1190*output += line;
1191*output += "\n"
1192}
1193 });
1194 };
11951196let lint_msg = |msg| {
1197emit_lint_base(
1198sess,
1199LINKER_MESSAGES,
1200levels.linker_messages,
1201None,
1202LinkerOutput { inner: msg },
1203 );
1204 };
1205let lint_info = |msg| {
1206emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
1207 };
12081209if !escaped_stderr.is_empty() {
1210// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
1211escaped_stderr =
1212escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
1213// Windows GNU LD prints uppercase Warning
1214escaped_stderr = escaped_stderr1215 .strip_prefix("Warning: ")
1216 .unwrap_or(&escaped_stderr)
1217 .replace(": warning: ", ": ");
1218lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
1219 }
1220if !escaped_stdout.is_empty() {
1221lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
1222 }
1223if !linker_info.is_empty() {
1224lint_info(linker_info);
1225 }
1226}
12271228/// Create a dynamic library or executable.
1229///
1230/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
1231/// files as well.
1232fn link_natively(
1233 sess: &Session,
1234 archive_builder_builder: &dyn ArchiveBuilderBuilder,
1235 rmeta_link_cache: &mut RmetaLinkCache,
1236 crate_type: CrateType,
1237 out_filename: &Path,
1238 compiled_modules: &CompiledModules,
1239 crate_info: &CrateInfo,
1240 metadata: &EncodedMetadata,
1241 tmpdir: &Path,
1242 codegen_backend: &'static str,
1243) {
1244{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1244",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1244u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("preparing {0:?} to {1:?}",
crate_type, out_filename) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
1245let (linker_path, flavor) = linker_and_flavor(sess);
1246let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
12471248// On AIX, we ship all libraries as .a big_af archive
1249 // the expected format is lib<name>.a(libname.so) for the actual
1250 // dynamic library. So we link to a temporary .so file to be archived
1251 // at the final out_filename location
1252let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
1253let archive_member =
1254should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
1255let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
12561257let (mut cmd, jobserver_tokens) = linker_with_args(
1258&linker_path,
1259flavor,
1260sess,
1261archive_builder_builder,
1262rmeta_link_cache,
1263crate_type,
1264tmpdir,
1265temp_filename,
1266compiled_modules,
1267crate_info,
1268metadata,
1269self_contained_components,
1270codegen_backend,
1271 );
12721273 linker::disable_localization(&mut cmd);
12741275for (k, v) in sess.target.link_env.as_ref() {
1276 cmd.env(k.as_ref(), v.as_ref());
1277 }
1278for k in sess.target.link_env_remove.as_ref() {
1279 cmd.env_remove(k.as_ref());
1280 }
12811282for print in &sess.opts.prints {
1283if print.kind == PrintKind::LinkArgs {
1284let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
1285 print.out.overwrite(&content, sess);
1286 }
1287 }
12881289// May have not found libraries in the right formats.
1290sess.dcx().abort_if_errors();
12911292// Invoke the system linker
1293{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1293",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1293u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1294let unknown_arg_regex =
1295Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
1296let mut prog;
1297loop {
1298prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
1299let Ok(ref output) = progelse {
1300break;
1301 };
1302if output.status.success() {
1303break;
1304 }
1305let mut out = output.stderr.clone();
1306out.extend(&output.stdout);
1307let out = String::from_utf8_lossy(&out);
13081309// Check to see if the link failed with an error message that indicates it
1310 // doesn't recognize the -no-pie option. If so, re-perform the link step
1311 // without it. This is safe because if the linker doesn't support -no-pie
1312 // then it should not default to linking executables as pie. Different
1313 // versions of gcc seem to use different quotes in the error message so
1314 // don't check for them.
1315if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1316 && unknown_arg_regex.is_match(&out)
1317 && out.contains("-no-pie")
1318 && cmd.get_args().iter().any(|e| e == "-no-pie")
1319 {
1320{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1320",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1320u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1321{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1321",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1321u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Linker does not support -no-pie command line option. Retrying without.")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};warn!("Linker does not support -no-pie command line option. Retrying without.");
1322for arg in cmd.take_args() {
1323if arg != "-no-pie" {
1324 cmd.arg(arg);
1325 }
1326 }
1327{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1327",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1327u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1328continue;
1329 }
13301331// Check if linking failed with an error message that indicates the driver didn't recognize
1332 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1333 // to spawn multiple instances on the happy path to do version checking, and ensures things
1334 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1335 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1336if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1337 && unknown_arg_regex.is_match(&out)
1338 && out.contains("-fuse-ld=lld")
1339 && cmd.get_args().iter().any(|e| e == "-fuse-ld=lld")
1340 {
1341{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1341",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1341u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1342{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1342",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1342u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
1343for arg in cmd.take_args() {
1344if arg != "-fuse-ld=lld" {
1345 cmd.arg(arg);
1346 }
1347 }
1348{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1348",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1348u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1349continue;
1350 }
13511352// Check if linking failed with an error message that the linker doesn't recognise the
1353 // cortex-a53 mitigation. We pass `-mfix-cortex-a53-843419` to CC-based linker drivers,
1354 // which forward `--fix-cortex-a53-843419` to the linker itself, but either component may
1355 // not recognise each flag. Notably this was only added to Clang in version 21.
1356if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1357 && unknown_arg_regex.is_match(&out)
1358 && out.contains("fix-cortex-a53-843419")
1359 && cmd.get_args().iter().any(|e| e == "-mfix-cortex-a53-843419")
1360 {
1361{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1361",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1361u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1362{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1362",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1362u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("The linker or linker driver do not support `fix-cortex-a53-843419`. Retrying without it.")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!(
1363"The linker or linker driver do not support `fix-cortex-a53-843419`. Retrying without it."
1364);
1365for arg in cmd.take_args() {
1366if arg != "-mfix-cortex-a53-843419" {
1367 cmd.arg(arg);
1368 }
1369 }
1370{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1370",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1370u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1371continue;
1372 }
13731374// Detect '-static-pie' used with an older version of gcc or clang not supporting it,
1375 // or with glibc that's missing crt objects, e.g. for arches that don't support it.
1376 // Fallback from '-static-pie' to '-static' in either case.
1377let mut static_pie_message = None;
1378if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1379 && cmd.get_args().iter().any(|e| e == "-static-pie")
1380 {
1381if unknown_arg_regex.is_match(&out)
1382 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1383 {
1384static_pie_message =
1385Some("Linker does not support -static-pie command line option.");
1386 } else if Regex::new(r"cannot (find|open) g?rcrt1\.o:").unwrap().is_match(&out) {
1387static_pie_message = Some("C library is missing static-PIE startup objects.");
1388 }
1389 }
1390if let Some(message) = static_pie_message {
1391{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1391",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1391u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1392{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1392",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1392u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} Retrying with -static instead.",
message) as &dyn ::tracing::field::Value))])
});
} else { ; }
};warn!("{message} Retrying with -static instead.");
1393// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1394let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1395let opts = &sess.target;
1396let pre_objects = if self_contained_crt_objects {
1397&opts.pre_link_objects_self_contained
1398 } else {
1399&opts.pre_link_objects
1400 };
1401let post_objects = if self_contained_crt_objects {
1402&opts.post_link_objects_self_contained
1403 } else {
1404&opts.post_link_objects
1405 };
1406let get_objects = |objects: &CrtObjects, kind| {
1407objects1408 .get(&kind)
1409 .into_flat_iter()
1410 .map(|obj| {
1411get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1412 })
1413 .collect::<Vec<_>>()
1414 };
1415let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1416let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1417let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1418let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1419// Assume that we know insertion positions for the replacement arguments from replaced
1420 // arguments, which is true for all supported targets.
1421if !(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());
1422if !(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());
1423for arg in cmd.take_args() {
1424if arg == "-static-pie" {
1425// Replace the output kind.
1426cmd.arg("-static");
1427 } else if pre_objects_static_pie.contains(&arg) {
1428// Replace the pre-link objects (replace the first and remove the rest).
1429cmd.args(mem::take(&mut pre_objects_static));
1430 } else if post_objects_static_pie.contains(&arg) {
1431// Replace the post-link objects (replace the first and remove the rest).
1432cmd.args(mem::take(&mut post_objects_static));
1433 } else {
1434 cmd.arg(arg);
1435 }
1436 }
1437{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1437",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1437u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1438continue;
1439 }
14401441break;
1442 }
14431444// Finished running linker, release the tokens.
1445drop(jobserver_tokens);
14461447match prog {
1448Ok(prog) => {
1449if !prog.status.success() {
1450let mut output = prog.stderr.clone();
1451output.extend_from_slice(&prog.stdout);
1452let escaped_output = escape_linker_output(&output, flavor);
1453let err = diagnostics::LinkingFailed {
1454 linker_path: &linker_path,
1455 exit_status: prog.status,
1456 command: cmd,
1457escaped_output,
1458 verbose: sess.opts.verbose,
1459 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1460 };
1461sess.dcx().emit_err(err);
1462// If MSVC's `link.exe` was expected but the return code
1463 // is not a Microsoft LNK error then suggest a way to fix or
1464 // install the Visual Studio build tools.
1465if let Some(code) = prog.status.code() {
1466// All Microsoft `link.exe` linking ror codes are
1467 // four digit numbers in the range 1000 to 9999 inclusive
1468if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1469let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1470let has_linker =
1471 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1472 .is_some();
14731474sess.dcx().emit_note(diagnostics::LinkExeUnexpectedError);
14751476// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1477 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1478const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1479if code == STATUS_STACK_BUFFER_OVERRUN {
1480sess.dcx().emit_note(diagnostics::LinkExeStatusStackBufferOverrun);
1481 }
14821483if is_vs_installed && has_linker {
1484// the linker is broken
1485sess.dcx().emit_note(diagnostics::RepairVSBuildTools);
1486sess.dcx().emit_note(diagnostics::MissingCppBuildToolComponent);
1487 } else if is_vs_installed {
1488// the linker is not installed
1489sess.dcx().emit_note(diagnostics::SelectCppBuildToolWorkload);
1490 } else {
1491// visual studio is not installed
1492sess.dcx().emit_note(diagnostics::VisualStudioNotInstalled);
1493 }
1494 }
1495 }
14961497sess.dcx().abort_if_errors();
1498 }
14991500{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:1500",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1500u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reporting linker output: flavor={0:?}",
flavor) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("reporting linker output: flavor={flavor:?}");
1501report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1502 }
1503Err(e) => {
1504let linker_not_found = e.kind() == io::ErrorKind::NotFound;
15051506let err = if linker_not_found {
1507sess.dcx().emit_err(diagnostics::LinkerNotFound { linker_path, error: e })
1508 } else {
1509sess.dcx().emit_err(diagnostics::UnableToExeLinker {
1510linker_path,
1511 error: e,
1512 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1513 })
1514 };
15151516if sess.target.is_like_msvc && linker_not_found {
1517sess.dcx().emit_note(diagnostics::MsvcMissingLinker);
1518sess.dcx().emit_note(diagnostics::CheckInstalledVisualStudio);
1519sess.dcx().emit_note(diagnostics::InsufficientVSCodeProduct);
1520 }
1521err.raise_fatal();
1522 }
1523 }
15241525match sess.split_debuginfo() {
1526// If split debug information is disabled or located in individual files
1527 // there's nothing to do here.
1528SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
15291530// If packed split-debuginfo is requested, but the final compilation
1531 // doesn't actually have any debug information, then we skip this step.
1532SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
15331534// On macOS the external `dsymutil` tool is used to create the packed
1535 // debug information. Note that this will read debug information from
1536 // the objects on the filesystem which we'll clean up later.
1537SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1538let prog = Command::new("dsymutil").arg(out_filename).output();
1539match prog {
1540Ok(prog) => {
1541if !prog.status.success() {
1542let mut output = prog.stderr.clone();
1543output.extend_from_slice(&prog.stdout);
1544sess.dcx().emit_warn(diagnostics::ProcessingDymutilFailed {
1545 status: prog.status,
1546 output: escape_string(&output),
1547 });
1548 }
1549 }
1550Err(error) => sess.dcx().emit_fatal(diagnostics::UnableToRunDsymutil { error }),
1551 }
1552 }
15531554// On MSVC packed debug information is produced by the linker itself so
1555 // there's no need to do anything else here.
1556SplitDebuginfo::Packedif sess.target.is_like_windows => {}
15571558// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1559 //
1560 // We cannot rely on the .o paths in the executable because they may have been
1561 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1562 // the .o/.dwo paths explicitly.
1563SplitDebuginfo::Packed => {
1564link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1565 }
1566 }
15671568let strip = sess.opts.cg.strip;
15691570if sess.target.is_like_darwin {
1571let stripcmd = "rust-objcopy";
1572match (strip, crate_type) {
1573 (Strip::Debuginfo, _) => {
1574strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1575 }
15761577// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1578(
1579 Strip::Symbols,
1580 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1581 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1582 (Strip::Symbols, _) => {
1583strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1584 }
1585 (Strip::None, _) => {}
1586 }
1587 }
15881589if sess.target.is_like_solaris {
1590// Many illumos systems will have both the native 'strip' utility and
1591 // the GNU one. Use the native version explicitly and do not rely on
1592 // what's in the path.
1593 //
1594 // If cross-compiling and there is not a native version, then use
1595 // `llvm-strip` and hope.
1596let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1597match strip {
1598// Always preserve the symbol table (-x).
1599Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1600// Strip::Symbols is handled via the --strip-all linker option.
1601Strip::Symbols => {}
1602 Strip::None => {}
1603 }
1604 }
16051606if sess.target.is_like_aix {
1607// `llvm-strip` doesn't work for AIX - their strip must be used.
1608if !sess.host.is_like_aix {
1609sess.dcx().emit_warn(diagnostics::AixStripNotUsed);
1610 }
1611let stripcmd = "/usr/bin/strip";
1612match strip {
1613 Strip::Debuginfo => {
1614// FIXME: AIX's strip utility only offers option to strip line number information.
1615strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1616 }
1617 Strip::Symbols => {
1618// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1619strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1620 }
1621 Strip::None => {}
1622 }
1623 }
16241625if should_archive {
1626let mut ab = archive_builder_builder.new_archive_builder(sess);
1627ab.add_file(temp_filename, ArchiveEntryKind::Other);
1628ab.build(out_filename, None);
1629 }
1630}
16311632fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1633let mut cmd = Command::new(util);
1634cmd.args(options);
16351636let mut new_path = sess.get_tools_search_paths(false);
1637if let Some(path) = env::var_os("PATH") {
1638new_path.extend(env::split_paths(&path));
1639 }
1640cmd.env("PATH", env::join_paths(new_path).unwrap());
16411642let prog = cmd.arg(out_filename).output();
1643match prog {
1644Ok(prog) => {
1645if !prog.status.success() {
1646let mut output = prog.stderr.clone();
1647output.extend_from_slice(&prog.stdout);
1648sess.dcx().emit_warn(diagnostics::StrippingDebugInfoFailed {
1649util,
1650 status: prog.status,
1651 output: escape_string(&output),
1652 });
1653 }
1654 }
1655Err(error) => sess.dcx().emit_fatal(diagnostics::UnableToRun { util, error }),
1656 }
1657}
16581659fn escape_string(s: &[u8]) -> String {
1660match str::from_utf8(s) {
1661Ok(s) => s.to_owned(),
1662Err(_) => ::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()),
1663 }
1664}
16651666#[cfg(not(windows))]
1667fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1668escape_string(s)
1669}
16701671/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1672/// then try to convert the string from the OEM encoding.
1673#[cfg(windows)]
1674fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1675// This only applies to the actual MSVC linker.
1676if flavour != LinkerFlavor::Msvc(Lld::No) {
1677return escape_string(s);
1678 }
1679match str::from_utf8(s) {
1680Ok(s) => return s.to_owned(),
1681Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1682Some(s) => s,
1683// The string is not UTF-8 and isn't valid for the OEM code page
1684None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1685 },
1686 }
1687}
16881689/// Wrappers around the Windows API.
1690#[cfg(windows)]
1691mod win {
1692use windows::Win32::Globalization::{
1693 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1694 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1695 };
16961697/// Get the Windows system OEM code page. This is most notably the code page
1698 /// used for link.exe's output.
1699pub(super) fn oem_code_page() -> u32 {
1700unsafe {
1701let mut cp: u32 = 0;
1702// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1703 // But the API requires us to pass the data as though it's a [u16] string.
1704let len = size_of::<u32>() / size_of::<u16>();
1705let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1706let len_written = GetLocaleInfoEx(
1707 LOCALE_NAME_SYSTEM_DEFAULT,
1708 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1709Some(data),
1710 );
1711if len_written as usize == len { cp } else { CP_OEMCP }
1712 }
1713 }
1714/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1715 /// The string does not need to be null terminated.
1716 ///
1717 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1718 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1719 ///
1720 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1721 /// any invalid bytes for the expected encoding.
1722pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1723// `MultiByteToWideChar` requires a length to be a "positive integer".
1724if s.len() > isize::MAX as usize {
1725return None;
1726 }
1727// Error if the string is not valid for the expected code page.
1728let flags = MB_ERR_INVALID_CHARS;
1729// Call MultiByteToWideChar twice.
1730 // First to calculate the length then to convert the string.
1731let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1732if len > 0 {
1733let mut utf16 = vec![0; len as usize];
1734 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1735if len > 0 {
1736return utf16.get(..len as usize).map(String::from_utf16_lossy);
1737 }
1738 }
1739None
1740}
1741}
17421743fn add_sanitizer_libraries(
1744 sess: &Session,
1745 flavor: LinkerFlavor,
1746 crate_type: CrateType,
1747 linker: &mut dyn Linker,
1748) {
1749if sess.target.is_like_android {
1750// Sanitizer runtime libraries are provided dynamically on Android
1751 // targets.
1752return;
1753 }
17541755if sess.opts.unstable_opts.external_clangrt {
1756// Linking against in-tree sanitizer runtimes is disabled via
1757 // `-Z external-clangrt`
1758return;
1759 }
17601761if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1762return;
1763 }
17641765// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1766 // which should be linked to both executables and dynamic libraries.
1767 // Everywhere else the runtimes are currently distributed as static
1768 // libraries which should be linked to executables only.
1769if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1770 crate_type,
1771 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1772 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1773 {
1774return;
1775 }
17761777let sanitizer = sess.sanitizers();
1778if sanitizer.contains(SanitizerSet::ADDRESS) {
1779link_sanitizer_runtime(sess, flavor, linker, "asan");
1780 }
1781if sanitizer.contains(SanitizerSet::DATAFLOW) {
1782link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1783 }
1784if sanitizer.contains(SanitizerSet::LEAK)
1785 && !sanitizer.contains(SanitizerSet::ADDRESS)
1786 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1787 {
1788link_sanitizer_runtime(sess, flavor, linker, "lsan");
1789 }
1790if sanitizer.contains(SanitizerSet::MEMORY) {
1791link_sanitizer_runtime(sess, flavor, linker, "msan");
1792 }
1793if sanitizer.contains(SanitizerSet::THREAD) {
1794link_sanitizer_runtime(sess, flavor, linker, "tsan");
1795 }
1796if sanitizer.contains(SanitizerSet::HWADDRESS) {
1797link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1798 }
1799if sanitizer.contains(SanitizerSet::SAFESTACK) {
1800link_sanitizer_runtime(sess, flavor, linker, "safestack");
1801 }
1802if sanitizer.contains(SanitizerSet::REALTIME) {
1803link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1804 }
1805if sanitizer.contains(SanitizerSet::CFI)
1806 && (sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false)
1807 || sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false))
1808 {
1809if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1810link_sanitizer_runtime(sess, flavor, linker, "ubsan_minimal");
1811 } else {
1812link_sanitizer_runtime(sess, flavor, linker, "ubsan");
1813 }
1814 }
1815}
18161817fn link_sanitizer_runtime(
1818 sess: &Session,
1819 flavor: LinkerFlavor,
1820 linker: &mut dyn Linker,
1821 name: &str,
1822) {
1823fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1824let path = sess.target_tlib_path.dir.join(filename);
1825if path.exists() {
1826sess.target_tlib_path.dir.to_path_buf()
1827 } else {
1828 filesearch::make_target_lib_path(
1829&sess.opts.sysroot.default,
1830sess.opts.target_triple.tuple(),
1831 )
1832 }
1833 }
18341835let channel =
1836::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();
18371838if sess.target.is_like_darwin {
1839// On Apple platforms, the sanitizer is always built as a dylib, and
1840 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1841 // rpath to the library as well (the rpath should be absolute, see
1842 // PR #41352 for details).
1843let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1844let path = find_sanitizer_runtime(sess, &filename);
1845let rpath = path.to_str().expect("non-utf8 component in path");
1846linker.link_args(&["-rpath", rpath]);
1847linker.link_dylib_by_name(&filename, false, true);
1848 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1849// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1850 // compatible ASAN library.
1851linker.link_arg("/INFERASANLIBS");
1852 } else {
1853let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1854let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1855linker.link_staticlib_by_path(&path, true);
1856 }
1857}
18581859/// Returns a boolean indicating whether the specified crate should be ignored
1860/// during LTO.
1861///
1862/// Crates ignored during LTO are not lumped together in the "massive object
1863/// file" that we create and are linked in their normal rlib states. See
1864/// comments below for what crates do not participate in LTO.
1865///
1866/// It's unusual for a crate to not participate in LTO. Typically only
1867/// compiler-specific and unstable crates have a reason to not participate in
1868/// LTO.
1869pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1870// If our target enables builtin function lowering in LLVM then the
1871 // crates providing these functions don't participate in LTO (e.g.
1872 // no_builtins or compiler builtins crates).
1873!sess.target.no_builtins
1874 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1875}
18761877/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1878pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1879fn infer_from(
1880 sess: &Session,
1881 linker: Option<PathBuf>,
1882 flavor: Option<LinkerFlavor>,
1883 features: LinkerFeaturesCli,
1884 ) -> Option<(PathBuf, LinkerFlavor)> {
1885let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1886match (linker, flavor) {
1887 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1888// only the linker flavor is known; use the default linker for the selected flavor
1889(None, Some(flavor)) => Some((
1890PathBuf::from(match flavor {
1891 LinkerFlavor::Gnu(Cc::Yes, _)
1892 | LinkerFlavor::Darwin(Cc::Yes, _)
1893 | LinkerFlavor::WasmLld(Cc::Yes)
1894 | LinkerFlavor::Unix(Cc::Yes) => {
1895if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1896// On historical Solaris systems, "cc" may have
1897 // been Sun Studio, which is not flag-compatible
1898 // with "gcc". This history casts a long shadow,
1899 // and many modern illumos distributions today
1900 // ship GCC as "gcc" without also making it
1901 // available as "cc".
1902"gcc"
1903} else {
1904"cc"
1905}
1906 }
1907 LinkerFlavor::Gnu(_, Lld::Yes)
1908 | LinkerFlavor::Darwin(_, Lld::Yes)
1909 | LinkerFlavor::WasmLld(..)
1910 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1911 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1912"ld"
1913}
1914 LinkerFlavor::Msvc(..) => "link.exe",
1915 LinkerFlavor::EmCc => {
1916if falsecfg!(windows) {
1917"emcc.bat"
1918} else {
1919"emcc"
1920}
1921 }
1922 LinkerFlavor::Bpf => "bpf-linker",
1923 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1924 }),
1925flavor,
1926 )),
1927 (Some(linker), None) => {
1928let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1929sess.dcx().emit_fatal(diagnostics::LinkerFileStem);
1930 });
1931let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1932let flavor = adjust_flavor_to_features(flavor, features);
1933Some((linker, flavor))
1934 }
1935 (None, None) => None,
1936 }
1937 }
19381939// While linker flavors and linker features are isomorphic (and thus targets don't need to
1940 // define features separately), we use the flavor as the root piece of data and have the
1941 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1942 // both yet.
1943fn adjust_flavor_to_features(
1944 flavor: LinkerFlavor,
1945 features: LinkerFeaturesCli,
1946 ) -> LinkerFlavor {
1947// Note: a linker feature cannot be both enabled and disabled on the CLI.
1948if features.enabled.contains(LinkerFeatures::LLD) {
1949flavor.with_lld_enabled()
1950 } else if features.disabled.contains(LinkerFeatures::LLD) {
1951flavor.with_lld_disabled()
1952 } else {
1953flavor1954 }
1955 }
19561957let features = sess.opts.cg.linker_features;
19581959// linker and linker flavor specified via command line have precedence over what the target
1960 // specification specifies
1961let linker_flavor = match sess.opts.cg.linker_flavor {
1962// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1963Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1964// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1965linker_flavor => {
1966linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1967 }
1968 };
1969if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1970return ret;
1971 }
19721973if let Some(ret) = infer_from(
1974sess,
1975sess.target.linker.as_deref().map(PathBuf::from),
1976Some(sess.target.linker_flavor),
1977features,
1978 ) {
1979return ret;
1980 }
19811982::rustc_span::macros::bug_impl(None,
format_args!("Not enough information provided to determine how to invoke the linker"),
Location::caller());bug!("Not enough information provided to determine how to invoke the linker");
1983}
19841985/// Returns a pair of boolean indicating whether we should preserve the object and
1986/// dwarf object files on the filesystem for their debug information. This is often
1987/// useful with split-dwarf like schemes.
1988fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1989// If the objects don't have debuginfo there's nothing to preserve.
1990if sess.opts.debuginfo == config::DebugInfo::None {
1991return (false, false);
1992 }
19931994match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1995// If there is no split debuginfo then do not preserve objects.
1996(SplitDebuginfo::Off, _) => (false, false),
1997// If there is packed split debuginfo, then the debuginfo in the objects
1998 // has been packaged and the objects can be deleted.
1999(SplitDebuginfo::Packed, _) => (false, false),
2000// If there is unpacked split debuginfo and the current target can not use
2001 // split dwarf, then keep objects.
2002(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
2003// If there is unpacked split debuginfo and the target can use split dwarf, then
2004 // keep the object containing that debuginfo (whether that is an object file or
2005 // dwarf object file depends on the split dwarf kind).
2006(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
2007 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
2008 }
2009}
20102011#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
RlibFlavor {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RlibFlavor {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
2012enum RlibFlavor {
2013 Normal,
2014 StaticlibBase,
2015}
20162017fn print_native_static_libs(
2018 sess: &Session,
2019 out: &OutFileName,
2020 all_native_libs: &[NativeLib],
2021 all_rust_dylibs: &[&Path],
2022) {
2023let mut lib_args: Vec<_> = all_native_libs2024 .iter()
2025 .filter(|l| relevant_lib(sess, l))
2026 .filter_map(|lib| {
2027let name = lib.name;
2028match lib.kind {
2029 NativeLibKind::Static { bundle: Some(false), .. }
2030 | NativeLibKind::Dylib { .. }
2031 | NativeLibKind::Unspecified => {
2032let verbatim = lib.verbatim;
2033if sess.target.is_like_msvc {
2034let (prefix, suffix) = sess.staticlib_components(verbatim);
2035Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
2036 } else if sess.target.linker_flavor.is_gnu() {
2037Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
2038 } else {
2039Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
2040 }
2041 }
2042 NativeLibKind::Framework { .. } => {
2043// ld-only syntax, since there are no frameworks in MSVC
2044Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
2045 }
2046// These are included, no need to print them
2047NativeLibKind::Static { bundle: None | Some(true), .. }
2048 | NativeLibKind::LinkArg2049 | NativeLibKind::WasmImportModule2050 | NativeLibKind::RawDylib { .. } => None,
2051 }
2052 })
2053// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
2054.dedup()
2055 .collect();
2056for path in all_rust_dylibs {
2057// FIXME deduplicate with add_dynamic_crate
20582059 // Just need to tell the linker about where the library lives and
2060 // what its name is
2061let parent = path.parent();
2062if let Some(dir) = parent {
2063let dir = fix_windows_verbatim_for_gcc(dir);
2064if sess.target.is_like_msvc {
2065let mut arg = String::from("/LIBPATH:");
2066 arg.push_str(&dir.display().to_string());
2067 lib_args.push(arg);
2068 } else {
2069 lib_args.push("-L".to_owned());
2070 lib_args.push(dir.display().to_string());
2071 }
2072 }
2073let stem = path.file_stem().unwrap().to_str().unwrap();
2074// Convert library file-stem into a cc -l argument.
2075let lib = if let Some(lib) = stem.strip_prefix("lib")
2076 && !sess.target.is_like_windows
2077 {
2078 lib
2079 } else {
2080 stem
2081 };
2082let path = parent.unwrap_or_else(|| Path::new(""));
2083if sess.target.is_like_msvc {
2084// When producing a dll, the MSVC linker may not actually emit a
2085 // `foo.lib` file if the dll doesn't actually export any symbols, so we
2086 // check to see if the file is there and just omit linking to it if it's
2087 // not present.
2088let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
2089if path.join(&name).exists() {
2090 lib_args.push(name);
2091 }
2092 } else {
2093 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
2094 }
2095 }
20962097match out {
2098 OutFileName::Real(path) => {
2099out.overwrite(&lib_args.join(" "), sess);
2100sess.dcx().emit_note(diagnostics::StaticLibraryNativeArtifactsToFile { path });
2101 }
2102 OutFileName::Stdout => {
2103sess.dcx().emit_note(diagnostics::StaticLibraryNativeArtifacts);
2104// Prefix for greppability
2105 // Note: This must not be translated as tools are allowed to depend on this exact string.
2106sess.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(" ")));
2107 }
2108 }
2109}
21102111fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
2112let file_path = sess.target_tlib_path.dir.join(name);
2113if file_path.exists() {
2114return file_path;
2115 }
2116// Special directory with objects used only in self-contained linkage mode
2117if self_contained {
2118let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
2119if file_path.exists() {
2120return file_path;
2121 }
2122 }
21232124// Note: this is O(n^2), it could be expensive-ish if we lookup many object files for many
2125 // search paths
2126for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
2127let file_path = search_path.dir.join(name);
2128if file_path.exists() {
2129return file_path;
2130 }
2131 }
2132PathBuf::from(name)
2133}
21342135fn exec_linker(
2136 sess: &Session,
2137 cmd: &Command,
2138 out_filename: &Path,
2139 flavor: LinkerFlavor,
2140 tmpdir: &Path,
2141) -> io::Result<Output> {
2142// When attempting to spawn the linker we run a risk of blowing out the
2143 // size limits for spawning a new process with respect to the arguments
2144 // we pass on the command line.
2145 //
2146 // Here we attempt to handle errors from the OS saying "your list of
2147 // arguments is too big" by reinvoking the linker again with an `@`-file
2148 // that contains all the arguments (aka 'response' files).
2149 // The theory is that this is then accepted on all linkers and the linker
2150 // will read all its options out of there instead of looking at the command line.
2151if !cmd.very_likely_to_exceed_some_spawn_limit() {
2152match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
2153Ok(child) => {
2154let output = child.wait_with_output();
2155 flush_linked_file(&output, out_filename)?;
2156return output;
2157 }
2158Err(ref e) if command_line_too_big(e) => {
2159{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:2159",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2159u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("command line to linker was too big: {0}",
e) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("command line to linker was too big: {}", e);
2160 }
2161Err(e) => return Err(e),
2162 }
2163 }
21642165{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:2165",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2165u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("falling back to passing arguments to linker via an @-file")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("falling back to passing arguments to linker via an @-file");
2166let mut cmd2 = cmd.clone();
2167let mut args = String::new();
2168for arg in cmd2.take_args() {
2169 args.push_str(
2170&Escape {
2171 arg: arg.to_str().unwrap(),
2172// Windows-style escaping for @-files is used by
2173 // - all linkers targeting MSVC-like targets, including LLD
2174 // - all LLD flavors running on Windows hosts
2175 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
2176is_like_msvc: sess.target.is_like_msvc
2177 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
2178 }
2179 .to_string(),
2180 );
2181 args.push('\n');
2182 }
2183let file = tmpdir.join("linker-arguments");
2184let bytes = if sess.target.is_like_msvc {
2185let mut out = Vec::with_capacity((1 + args.len()) * 2);
2186// start the stream with a UTF-16 BOM
2187for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
2188// encode in little endian
2189out.push(c as u8);
2190 out.push((c >> 8) as u8);
2191 }
2192out2193 } else {
2194args.into_bytes()
2195 };
2196 fs::write(&file, &bytes)?;
2197cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
2198{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:2198",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2198u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("invoking linker {0:?}",
cmd2) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("invoking linker {:?}", cmd2);
2199let output = cmd2.output();
2200 flush_linked_file(&output, out_filename)?;
2201return output;
22022203#[cfg(not(windows))]
2204fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
2205Ok(())
2206 }
22072208#[cfg(windows)]
2209fn flush_linked_file(
2210 command_output: &io::Result<Output>,
2211 out_filename: &Path,
2212 ) -> io::Result<()> {
2213// On Windows, under high I/O load, output buffers are sometimes not flushed,
2214 // even long after process exit, causing nasty, non-reproducible output bugs.
2215 //
2216 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
2217 //
2218 // А full writeup of the original Chrome bug can be found at
2219 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
22202221if let &Ok(ref out) = command_output {
2222if out.status.success() {
2223if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
2224 of.sync_all()?;
2225 }
2226 }
2227 }
22282229Ok(())
2230 }
22312232#[cfg(unix)]
2233fn command_line_too_big(err: &io::Error) -> bool {
2234err.raw_os_error() == Some(::libc::E2BIG)
2235 }
22362237#[cfg(windows)]
2238fn command_line_too_big(err: &io::Error) -> bool {
2239const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
2240 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
2241 }
22422243#[cfg(not(any(unix, windows)))]
2244fn command_line_too_big(_: &io::Error) -> bool {
2245false
2246}
22472248struct Escape<'a> {
2249 arg: &'a str,
2250 is_like_msvc: bool,
2251 }
22522253impl<'a> fmt::Displayfor Escape<'a> {
2254fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2255if self.is_like_msvc {
2256// This is "documented" at
2257 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
2258 //
2259 // Unfortunately there's not a great specification of the
2260 // syntax I could find online (at least) but some local
2261 // testing showed that this seemed sufficient-ish to catch
2262 // at least a few edge cases.
2263f.write_fmt(format_args!("\""))write!(f, "\"")?;
2264for c in self.arg.chars() {
2265match c {
2266'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
2267 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
2268 }
2269 }
2270f.write_fmt(format_args!("\""))write!(f, "\"")?;
2271 } else {
2272// This is documented at https://linux.die.net/man/1/ld, namely:
2273 //
2274 // > Options in file are separated by whitespace. A whitespace
2275 // > character may be included in an option by surrounding the
2276 // > entire option in either single or double quotes. Any
2277 // > character (including a backslash) may be included by
2278 // > prefixing the character to be included with a backslash.
2279 //
2280 // We put an argument on each line, so all we need to do is
2281 // ensure the line is interpreted as one whole argument.
2282for c in self.arg.chars() {
2283match c {
2284'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
2285 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
2286 }
2287 }
2288 }
2289Ok(())
2290 }
2291 }
2292}
22932294fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
2295let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
2296 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
2297 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
2298 LinkOutputKind::DynamicPicExe2299 }
2300 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
2301 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
2302 LinkOutputKind::StaticPicExe2303 }
2304 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
2305 (_, true, _) => LinkOutputKind::StaticDylib,
2306 (_, false, _) => LinkOutputKind::DynamicDylib,
2307 };
23082309// Adjust the output kind to target capabilities.
2310let opts = &sess.target;
2311let pic_exe_supported = opts.position_independent_executables;
2312let static_pic_exe_supported = opts.static_position_independent_executables;
2313let static_dylib_supported = opts.crt_static_allows_dylibs;
2314match kind {
2315 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
2316 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
2317 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
2318_ => kind,
2319 }
2320}
23212322// Returns true if linker is located within sysroot
2323fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
2324let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
2325linker.with_extension("exe")
2326 } else {
2327linker.to_path_buf()
2328 };
2329for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
2330let full_path = dir.join(&linker_with_extension);
2331// If linker comes from sysroot assume self-contained mode
2332if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
2333return false;
2334 }
2335 }
2336true
2337}
23382339/// Various toolchain components used during linking are used from rustc distribution
2340/// instead of being found somewhere on the host system.
2341/// We only provide such support for a very limited number of targets.
2342fn self_contained_components(
2343 sess: &Session,
2344 crate_type: CrateType,
2345 linker: &Path,
2346) -> LinkSelfContainedComponents {
2347// Turn the backwards compatible bool values for `self_contained` into fully inferred
2348 // `LinkSelfContainedComponents`.
2349let self_contained =
2350if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
2351// Emit an error if the user requested self-contained mode on the CLI but the target
2352 // explicitly refuses it.
2353if sess.target.link_self_contained.is_disabled() {
2354sess.dcx().emit_err(diagnostics::UnsupportedLinkSelfContained);
2355 }
2356self_contained2357 } else {
2358match sess.target.link_self_contained {
2359 LinkSelfContainedDefault::False => false,
2360 LinkSelfContainedDefault::True => true,
23612362 LinkSelfContainedDefault::WithComponents(components) => {
2363// For target specs with explicitly enabled components, we can return them
2364 // directly.
2365return components;
2366 }
23672368// FIXME: Find a better heuristic for "native musl toolchain is available",
2369 // based on host and linker path, for example.
2370 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2371LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2372 LinkSelfContainedDefault::InferredForMingw => {
2373sess.host == sess.target
2374 && sess.target.cfg_abi != CfgAbi::Uwp2375 && detect_self_contained_mingw(sess, linker)
2376 }
2377 }
2378 };
2379if self_contained {
2380LinkSelfContainedComponents::all()
2381 } else {
2382LinkSelfContainedComponents::empty()
2383 }
2384}
23852386/// Add pre-link object files defined by the target spec.
2387fn add_pre_link_objects(
2388 cmd: &mut dyn Linker,
2389 sess: &Session,
2390 flavor: LinkerFlavor,
2391 link_output_kind: LinkOutputKind,
2392 self_contained: bool,
2393) {
2394// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2395 // so Fuchsia has to be special-cased.
2396let opts = &sess.target;
2397let empty = Default::default();
2398let objects = if self_contained {
2399&opts.pre_link_objects_self_contained
2400 } 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, _))) {
2401&opts.pre_link_objects
2402 } else {
2403&empty2404 };
2405for obj in objects.get(&link_output_kind).into_flat_iter() {
2406 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2407 }
2408}
24092410/// Add post-link object files defined by the target spec.
2411fn add_post_link_objects(
2412 cmd: &mut dyn Linker,
2413 sess: &Session,
2414 link_output_kind: LinkOutputKind,
2415 self_contained: bool,
2416) {
2417let objects = if self_contained {
2418&sess.target.post_link_objects_self_contained
2419 } else {
2420&sess.target.post_link_objects
2421 };
2422for obj in objects.get(&link_output_kind).into_flat_iter() {
2423 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2424 }
2425}
24262427/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2428/// FIXME: Determine where exactly these args need to be inserted.
2429fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2430// Emit the CC flag for the A53 mitigation early, as later linker args can override it if
2431 // required with `-mno-fix-cortex-a53-843419`
2432if sess.target.arch == Arch::AArch642433 && !sess.target.is_like_darwin
2434 && sess.target.os != Os::Windows2435 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, ..) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, ..))2436 {
2437cmd.cc_arg("-mfix-cortex-a53-843419");
2438 }
24392440if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2441cmd.verbatim_args(args.iter().map(Deref::deref));
2442 }
24432444cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2445}
24462447/// Add a link script embedded in the target, if applicable.
2448fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2449match (crate_type, &sess.target.link_script) {
2450 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2451if !sess.target.linker_flavor.is_gnu() {
2452sess.dcx().emit_fatal(diagnostics::LinkScriptUnavailable);
2453 }
24542455let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
24562457let path = tmpdir.join(file_name);
2458if let Err(error) = fs::write(&path, script.as_ref()) {
2459sess.dcx().emit_fatal(diagnostics::LinkScriptWriteFailure { path, error });
2460 }
24612462cmd.link_arg("--script").link_arg(path);
2463 }
2464_ => {}
2465 }
2466}
24672468/// Add arbitrary "user defined" args defined from command line.
2469/// FIXME: Determine where exactly these args need to be inserted.
2470fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2471cmd.verbatim_args(&sess.opts.cg.link_args);
2472}
24732474/// Add arbitrary "late link" args defined by the target spec.
2475/// FIXME: Determine where exactly these args need to be inserted.
2476fn add_late_link_args(
2477 cmd: &mut dyn Linker,
2478 sess: &Session,
2479 flavor: LinkerFlavor,
2480 crate_type: CrateType,
2481 crate_info: &CrateInfo,
2482) {
2483let any_dynamic_crate = crate_type == CrateType::Dylib2484 || crate_type == CrateType::Sdylib2485 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2486*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2487 });
2488if any_dynamic_crate {
2489if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2490cmd.verbatim_args(args.iter().map(Deref::deref));
2491 }
2492 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2493cmd.verbatim_args(args.iter().map(Deref::deref));
2494 }
2495if let Some(args) = sess.target.late_link_args.get(&flavor) {
2496cmd.verbatim_args(args.iter().map(Deref::deref));
2497 }
2498}
24992500/// Add arbitrary "post-link" args defined by the target spec.
2501/// FIXME: Determine where exactly these args need to be inserted.
2502fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2503if let Some(args) = sess.target.post_link_args.get(&flavor) {
2504cmd.verbatim_args(args.iter().map(Deref::deref));
2505 }
2506}
25072508/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2509/// the linker.
2510///
2511/// Background: we implement rlibs as static library (archives). Linkers treat archives
2512/// differently from object files: all object files participate in linking, while archives will
2513/// only participate in linking if they can satisfy at least one undefined reference (version
2514/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2515/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2516/// can't keep them either. This causes #47384.
2517///
2518/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2519/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2520/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2521/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2522/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2523/// from removing them, and this is especially problematic for embedded programming where every
2524/// byte counts.
2525///
2526/// This method creates a synthetic object file, which contains undefined references to all symbols
2527/// that are necessary for the linking. They are only present in symbol table but not actually
2528/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2529/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2530///
2531/// There's a few internal crates in the standard library (aka libcore and
2532/// libstd) which actually have a circular dependence upon one another. This
2533/// currently arises through "weak lang items" where libcore requires things
2534/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2535/// circular dependence to work correctly we declare some of these things
2536/// in this synthetic object.
2537fn add_linked_symbol_object(
2538 cmd: &mut dyn Linker,
2539 sess: &Session,
2540 tmpdir: &Path,
2541 crate_type: CrateType,
2542 linked_symbols: &[(String, SymbolExportKind)],
2543 exported_symbols: &[SymbolExport],
2544) {
2545let should_export_symbols = sess.target.is_like_msvc
2546 && !exported_symbols.is_empty()
2547 && (crate_type != CrateType::Executable2548 || sess.opts.unstable_opts.export_executable_symbols);
2549if linked_symbols.is_empty() && !should_export_symbols {
2550return;
2551 }
25522553let Some(mut file) = super::metadata::create_object_file(sess) else {
2554return;
2555 };
25562557if file.format() == object::BinaryFormat::Coff {
2558// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2559 // so add an empty section.
2560file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
25612562// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2563 // default mangler in `object` crate.
2564file.set_mangling(object::write::Mangling::None);
2565 }
25662567if file.format() == object::BinaryFormat::MachO {
2568// Divide up the sections into sub-sections via symbols for dead code stripping.
2569 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2570 // discard on MachO targets.
2571file.set_subsections_via_symbols();
2572 }
25732574// ld64 requires a relocation to load undefined symbols, see below.
2575 // Not strictly needed if linking with lld, but might as well do it there too.
2576let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2577Some(file.add_section(
2578file.segment_name(object::write::StandardSegment::Data).to_vec(),
2579"__data".into(),
2580 object::SectionKind::Data,
2581 ))
2582 } else {
2583None2584 };
25852586for (sym, kind) in linked_symbols.iter() {
2587let symbol = file.add_symbol(object::write::Symbol {
2588 name: sym.clone().into(),
2589 value: 0,
2590 size: 0,
2591 kind: match kind {
2592 SymbolExportKind::Text => object::SymbolKind::Text,
2593 SymbolExportKind::Data => object::SymbolKind::Data,
2594 SymbolExportKind::Tls => object::SymbolKind::Tls,
2595 },
2596 scope: object::SymbolScope::Unknown,
2597 weak: false,
2598 section: object::write::SymbolSection::Undefined,
2599 flags: object::SymbolFlags::None,
2600 });
26012602// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2603 //
2604 // Code-wise, the relevant parts of ld64 are roughly:
2605 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2606 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2607 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2608 //
2609 // 2. Read the archive table of contents (__.SYMDEF file).
2610 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2611 //
2612 // 3. Begin linking by loading "atoms" from input files.
2613 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2614 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2615 //
2616 // a. Directly specified object files (`.o`) are parsed immediately.
2617 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2618 //
2619 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2620 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2621 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2622 //
2623 // - Relocations/fixups are atoms.
2624 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2625 //
2626 // b. Archives are not parsed yet.
2627 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2628 //
2629 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2630 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2631 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2632 //
2633 // All of the steps above are fairly similar to other linkers, except that **it completely
2634 // ignores undefined symbols**.
2635 //
2636 // So to make this trick work on ld64, we need to do something else to load the relevant
2637 // object files. We do this by inserting a relocation (fixup) for each symbol.
2638if let Some(section) = ld64_section_helper {
2639 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2640 .expect("failed adding relocation");
2641 }
2642 }
26432644if should_export_symbols {
2645// Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
2646 // export symbols from a dynamic library. When building a dynamic library,
2647 // however, we're going to want some symbols exported, so this adds a
2648 // `.drectve` section which lists all the symbols using /EXPORT arguments.
2649 //
2650 // The linker will read these arguments from the `.drectve` section and
2651 // export all the symbols from the dynamic library. Note that this is not
2652 // as simple as just exporting all the symbols in the current crate (as
2653 // specified by `codegen.reachable`) but rather we also need to possibly
2654 // export the symbols of upstream crates. Upstream rlibs may be linked
2655 // statically to this dynamic library, in which case they may continue to
2656 // transitively be used and hence need their symbols exported.
2657fn msvc_drectve_export(symbol: &SymbolExport) -> String {
2658let data = if symbol.kind == SymbolExportKind::Data { ",DATA" } else { "" };
26592660if let Some(link_name) = symbol.link_name.as_deref() {
2661// The first name is the decorated symbol used by the import library, while
2662 // EXPORTAS gives the public name written to the DLL export table.
2663::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" /EXPORT:\"{1}\"{2},EXPORTAS,\"{0}\"",
symbol.name, link_name, data))
})format!(" /EXPORT:\"{link_name}\"{data},EXPORTAS,\"{}\"", symbol.name)2664 } else {
2665::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" /EXPORT:\"{0}\"{1}", symbol.name,
data))
})format!(" /EXPORT:\"{}\"{data}", symbol.name)2666 }
2667 }
26682669let drectve = exported_symbols.iter().map(msvc_drectve_export).collect::<String>();
26702671let section = file.add_section(::alloc::vec::Vec::new()vec![], b".drectve".to_vec(), object::SectionKind::Linker);
2672file.append_section_data(section, drectve.as_bytes(), 1);
2673 }
26742675let path = tmpdir.join("symbols.o");
2676let result = std::fs::write(&path, file.write().unwrap());
2677if let Err(error) = result {
2678sess.dcx().emit_fatal(diagnostics::FailedToWrite { path, error });
2679 }
2680cmd.add_object(&path);
2681}
26822683/// Add object files containing code from the current crate.
2684fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2685for m in &compiled_modules.modules {
2686if let Some(obj) = &m.object {
2687 cmd.add_object(obj);
2688 }
2689if let Some(obj) = &m.global_asm_object {
2690 cmd.add_object(obj);
2691 }
2692 }
2693}
26942695/// Add object files for allocator code linked once for the whole crate tree.
2696fn add_local_crate_allocator_objects(
2697 cmd: &mut dyn Linker,
2698 compiled_modules: &CompiledModules,
2699 crate_info: &CrateInfo,
2700 crate_type: CrateType,
2701) {
2702if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2703 && let Some(m) = &compiled_modules.allocator_module
2704 {
2705if let Some(obj) = &m.object {
2706cmd.add_object(obj);
2707 }
2708if let Some(obj) = &m.global_asm_object {
2709cmd.add_object(obj);
2710 }
2711 }
2712}
27132714/// Add object files containing metadata for the current crate.
2715fn add_local_crate_metadata_objects(
2716 cmd: &mut dyn Linker,
2717 sess: &Session,
2718 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2719 crate_type: CrateType,
2720 tmpdir: &Path,
2721 crate_info: &CrateInfo,
2722 metadata: &EncodedMetadata,
2723) {
2724// When linking a dynamic library, we put the metadata into a section of the
2725 // executable. This metadata is in a separate object file from the main
2726 // object file, so we create and link it in here.
2727if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2728let data = archive_builder_builder.create_dylib_metadata_wrapper(
2729sess,
2730&metadata,
2731&crate_info.metadata_symbol,
2732 );
2733let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
27342735cmd.add_object(&obj);
2736 }
2737}
27382739/// Add sysroot and other globally set directories to the directory search list.
2740fn add_library_search_dirs(
2741 cmd: &mut dyn Linker,
2742 sess: &Session,
2743 self_contained_components: LinkSelfContainedComponents,
2744 apple_sdk_root: Option<&Path>,
2745) {
2746if !sess.opts.unstable_opts.link_native_libraries {
2747return;
2748 }
27492750let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2751let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2752if is_framework {
2753cmd.framework_path(dir);
2754 } else {
2755cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2756 }
2757 ControlFlow::<()>::Continue(())
2758 });
2759}
27602761/// Add options making relocation sections in the produced ELF files read-only
2762/// and suppressing lazy binding.
2763fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2764match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2765 RelroLevel::Full => cmd.full_relro(),
2766 RelroLevel::Partial => cmd.partial_relro(),
2767 RelroLevel::Off => cmd.no_relro(),
2768 RelroLevel::None => {}
2769 }
2770}
27712772/// Add library search paths used at runtime by dynamic linkers.
2773fn add_rpath_args(
2774 cmd: &mut dyn Linker,
2775 sess: &Session,
2776 crate_info: &CrateInfo,
2777 out_filename: &Path,
2778) {
2779if !sess.target.has_rpath {
2780return;
2781 }
27822783// FIXME (#2397): At some point we want to rpath our guesses as to
2784 // where extern libraries might live, based on the
2785 // add_lib_search_paths
2786if sess.opts.cg.rpath {
2787let libs = crate_info2788 .used_crates
2789 .iter()
2790 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2791 .collect::<Vec<_>>();
2792let rpath_config = RPathConfig {
2793 libs: &*libs,
2794 out_filename: out_filename.to_path_buf(),
2795 is_like_darwin: sess.target.is_like_darwin,
2796 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2797 };
2798cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2799 }
2800}
28012802fn undecorate_c_symbol<'a>(
2803 name: &'a str,
2804 sess: &Session,
2805 kind: SymbolExportKind,
2806) -> Option<&'a str> {
2807match sess.target.binary_format {
2808 BinaryFormat::MachO => {
2809// Mach-O: strip the leading underscore that all external symbols have.
2810 // The Darwin linker's export_symbols will add it back.
2811name.strip_prefix('_')
2812 }
2813 BinaryFormat::Coff => {
2814// COFF undecoration is shared with `symbol_edit`'s binary-level matching.
2815match symbol_export::coff_machine_for_arch(&sess.target.arch) {
2816Some(machine) => Some(symbol_export::undecorate_coff_symbol(name, machine, kind)),
2817None => Some(name),
2818 }
2819 }
2820// ELF: no decoration
2821_ => Some(name),
2822 }
2823}
28242825fn add_c_staticlib_symbols(
2826 sess: &Session,
2827 lib: &NativeLib,
2828 out: &mut Vec<SymbolExport>,
2829) -> io::Result<()> {
2830let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
28312832let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
28332834let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2835 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28362837for member in archive.members() {
2838let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28392840let data = member
2841 .data(&*archive_map)
2842 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28432844// clang LTO: raw LLVM bitcode
2845if data.starts_with(b"BC\xc0\xde") {
2846return Err(io::Error::new(
2847 io::ErrorKind::InvalidData,
2848"LLVM bitcode object in C static library (LTO not supported)",
2849 ));
2850 }
28512852let object = object::File::parse(&*data)
2853 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28542855// gcc / clang ELF / Mach-O LTO
2856if object.sections().any(|s| {
2857 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2858 }) {
2859return Err(io::Error::new(
2860 io::ErrorKind::InvalidData,
2861"LTO object in C static library is not supported",
2862 ));
2863 }
28642865for symbol in object.symbols() {
2866// The `object` crate returns `Dynamic` for ELF/Mach-O global symbols,
2867 // but always returns `Linkage` for COFF external symbols.
2868 // Accept both for COFF (Windows and UEFI).
2869let scope = symbol.scope();
2870if scope != object::SymbolScope::Dynamic
2871 && !(sess.target.binary_format == BinaryFormat::Coff
2872 && scope == object::SymbolScope::Linkage)
2873 {
2874continue;
2875 }
28762877let name = match symbol.name() {
2878Ok(n) => n,
2879Err(_) => continue,
2880 };
28812882let export_kind = match symbol.kind() {
2883 object::SymbolKind::Text => SymbolExportKind::Text,
2884 object::SymbolKind::Data => SymbolExportKind::Data,
2885_ => continue,
2886 };
28872888let Some(undecorated) = undecorate_c_symbol(name, sess, export_kind) else {
2889continue;
2890 };
2891 out.push(SymbolExport::with_link_name(
2892 undecorated.to_string(),
2893 export_kind,
2894 name.to_string(),
2895 ));
2896 }
2897 }
28982899Ok(())
2900}
29012902/// Produce the linker command line containing linker path and arguments.
2903///
2904/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2905/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2906/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2907/// to the linking process as a whole.
2908/// Order-independent options may still override each other in order-dependent fashion,
2909/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2910fn linker_with_args(
2911 path: &Path,
2912 flavor: LinkerFlavor,
2913 sess: &Session,
2914 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2915 rmeta_link_cache: &mut RmetaLinkCache,
2916 crate_type: CrateType,
2917 tmpdir: &Path,
2918 out_filename: &Path,
2919 compiled_modules: &CompiledModules,
2920 crate_info: &CrateInfo,
2921 metadata: &EncodedMetadata,
2922 self_contained_components: LinkSelfContainedComponents,
2923 codegen_backend: &'static str,
2924) -> (Command, Vec<jobserver::Acquired>) {
2925let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2926let cmd = &mut *super::linker::get_linker(
2927sess,
2928path,
2929flavor,
2930self_contained_components.are_any_components_enabled(),
2931&crate_info.target_cpu,
2932codegen_backend,
2933 );
2934let link_output_kind = link_output_kind(sess, crate_type);
29352936let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
29372938if crate_type == CrateType::Cdylib {
2939let mut seen = FxHashSet::default();
29402941for lib in &crate_info.used_libraries {
2942if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2943 && seen.insert((lib.name, lib.verbatim))
2944 {
2945if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2946 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2947"failed to process C static library `{}`: {}",
2948 lib.name, err
2949 ));
2950 }
2951 }
2952 }
2953 }
29542955// ------------ Early order-dependent options ------------
29562957 // If we're building something like a dynamic library then some platforms
2958 // need to make sure that all symbols are exported correctly from the
2959 // dynamic library.
2960 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2961 // at least on some platforms (e.g. windows-gnu).
2962cmd.export_symbols(tmpdir, crate_type, &export_symbols);
29632964// Can be used for adding custom CRT objects or overriding order-dependent options above.
2965 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2966 // introduce a target spec option for order-independent linker options and migrate built-in
2967 // specs to it.
2968add_pre_link_args(cmd, sess, flavor);
29692970// ------------ Object code and libraries, order-dependent ------------
29712972 // Pre-link CRT objects.
2973add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
29742975add_linked_symbol_object(
2976cmd,
2977sess,
2978tmpdir,
2979crate_type,
2980&crate_info.linked_symbols[&crate_type],
2981&export_symbols,
2982 );
29832984// Sanitizer libraries.
2985add_sanitizer_libraries(sess, flavor, crate_type, cmd);
29862987// Object code from the current crate.
2988 // Take careful note of the ordering of the arguments we pass to the linker
2989 // here. Linkers will assume that things on the left depend on things to the
2990 // right. Things on the right cannot depend on things on the left. This is
2991 // all formally implemented in terms of resolving symbols (libs on the right
2992 // resolve unknown symbols of libs on the left, but not vice versa).
2993 //
2994 // For this reason, we have organized the arguments we pass to the linker as
2995 // such:
2996 //
2997 // 1. The local object that LLVM just generated
2998 // 2. Local native libraries
2999 // 3. Upstream rust libraries
3000 // 4. Upstream native libraries
3001 //
3002 // The rationale behind this ordering is that those items lower down in the
3003 // list can't depend on items higher up in the list. For example nothing can
3004 // depend on what we just generated (e.g., that'd be a circular dependency).
3005 // Upstream rust libraries are not supposed to depend on our local native
3006 // libraries as that would violate the structure of the DAG, in that
3007 // scenario they are required to link to them as well in a shared fashion.
3008 //
3009 // Note that upstream rust libraries may contain native dependencies as
3010 // well, but they also can't depend on what we just started to add to the
3011 // link line. And finally upstream native libraries can't depend on anything
3012 // in this DAG so far because they can only depend on other native libraries
3013 // and such dependencies are also required to be specified.
3014add_local_crate_regular_objects(cmd, compiled_modules);
3015add_local_crate_metadata_objects(
3016cmd,
3017sess,
3018archive_builder_builder,
3019crate_type,
3020tmpdir,
3021crate_info,
3022metadata,
3023 );
3024add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
30253026// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
3027 // at the point at which they are specified on the command line.
3028 // Must be passed before any (dynamic) libraries to have effect on them.
3029 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
3030 // so it will ignore unreferenced ELF sections from relocatable objects.
3031 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
3032 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
3033 // and move this option back to the top.
3034cmd.add_as_needed();
30353036// Local native libraries of all kinds.
3037add_local_native_libraries(
3038cmd,
3039sess,
3040archive_builder_builder,
3041rmeta_link_cache,
3042crate_info,
3043tmpdir,
3044link_output_kind,
3045 );
30463047if sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
config::Offload::Host(_) => true,
_ => false,
}matches!(o, config::Offload::Host(_))) {
3048cmd.link_dylib_by_name("omptarget", false, true);
3049cmd.link_dylib_by_name("omp", false, true);
3050cmd.link_args(["-z", "nostart-stop-gc"]);
3051cmd.link_arg("-rpath");
3052cmd.link_arg(std::path::absolute(&*sess.target_tlib_path.dir).unwrap());
3053 }
30543055// Upstream rust crates and their non-dynamic native libraries.
3056add_upstream_rust_crates(
3057cmd,
3058sess,
3059archive_builder_builder,
3060rmeta_link_cache,
3061crate_info,
3062crate_type,
3063tmpdir,
3064link_output_kind,
3065 );
30663067// Dynamic native libraries from upstream crates.
3068add_upstream_native_libraries(
3069cmd,
3070sess,
3071archive_builder_builder,
3072rmeta_link_cache,
3073crate_info,
3074tmpdir,
3075link_output_kind,
3076 );
30773078// Raw-dylibs from all crates.
3079let raw_dylib_dir = tmpdir.join("raw-dylibs");
3080if sess.target.binary_format == BinaryFormat::Elf {
3081// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
3082 // instead we need to pass them via -l. To find the stub, we need to add
3083 // the directory of the stub to the linker search path.
3084 // We make an extra directory for this to avoid polluting the search path.
3085if let Err(error) = fs::create_dir(&raw_dylib_dir) {
3086sess.dcx().emit_fatal(diagnostics::CreateTempDir { error })
3087 }
3088cmd.include_path(&raw_dylib_dir);
3089 }
30903091// Link with the import library generated for any raw-dylib functions.
3092if sess.target.is_like_windows {
3093for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
3094 sess,
3095 archive_builder_builder,
3096 crate_info.used_libraries.iter(),
3097 tmpdir,
3098true,
3099 ) {
3100 cmd.add_object(&output_path);
3101 }
3102 } else {
3103for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
3104 sess,
3105 crate_info.used_libraries.iter(),
3106&raw_dylib_dir,
3107 ) {
3108// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
3109cmd.link_dylib_by_name(&link_path, true, as_needed);
3110 }
3111 }
3112// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
3113 // they are used within inlined functions or instantiated generic functions. We do this *after*
3114 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
3115 // by the linker.
3116let dependency_linkage = crate_info3117 .dependency_formats
3118 .get(&crate_type)
3119 .expect("failed to find crate type in dependency format list");
31203121// We sort the libraries below
3122#[allow(rustc::potential_query_instability)]
3123let mut native_libraries_from_nonstatics = crate_info3124 .native_libraries
3125 .iter()
3126 .filter_map(|(&cnum, libraries)| {
3127if sess.target.is_like_windows {
3128 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
3129 } else {
3130Some(libraries)
3131 }
3132 })
3133 .flatten()
3134 .collect::<Vec<_>>();
3135native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
31363137if sess.target.is_like_windows {
3138for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
3139 sess,
3140 archive_builder_builder,
3141 native_libraries_from_nonstatics,
3142 tmpdir,
3143false,
3144 ) {
3145 cmd.add_object(&output_path);
3146 }
3147 } else {
3148for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
3149 sess,
3150 native_libraries_from_nonstatics,
3151&raw_dylib_dir,
3152 ) {
3153// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
3154cmd.link_dylib_by_name(&link_path, true, as_needed);
3155 }
3156 }
31573158// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
3159 // command line shorter, reset it to default here before adding more libraries.
3160cmd.reset_per_library_state();
31613162// FIXME: Built-in target specs occasionally use this for linking system libraries,
3163 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
3164 // and remove the option.
3165add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
31663167// ------------ Arbitrary order-independent options ------------
31683169 // Add order-independent options determined by rustc from its compiler options,
3170 // target properties and source code.
3171add_order_independent_options(
3172cmd,
3173sess,
3174link_output_kind,
3175self_contained_components,
3176flavor,
3177crate_type,
3178crate_info,
3179out_filename,
3180tmpdir,
3181 );
31823183// Can be used for arbitrary order-independent options.
3184 // In practice may also be occasionally used for linking native libraries.
3185 // Passed after compiler-generated options to support manual overriding when necessary.
3186add_user_defined_link_args(cmd, sess);
31873188// ------------ Builtin configurable linker scripts ------------
3189 // The user's link args should be able to overwrite symbols in the compiler's
3190 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
3191 // to work correctly, the user needs to be able to specify linker arguments like
3192 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
3193add_link_script(cmd, sess, tmpdir, crate_type);
31943195// ------------ Object code and libraries, order-dependent ------------
31963197 // Post-link CRT objects.
3198add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
31993200// ------------ Late order-dependent options ------------
32013202 // Doesn't really make sense.
3203 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
3204 // Introduce a target spec option for order-independent linker options, migrate built-in specs
3205 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
3206add_post_link_args(cmd, sess, flavor);
32073208// Only LLD supports controlling parallelism at the moment.
3209let mut tokens = Vec::new();
3210if let LinkerJobs::Explicit(limit) = sess.opts.jobs.linker
3211 && flavor.uses_lld()
3212 {
3213// Try obtaining as many jobserver tokens as possible (within the limit) to run parallel
3214 // linking. One token is available implicitly since we are running on the main thread.
3215let client = jobserver::client();
32163217let mut unsupported = false;
3218for _ in 0..limit.get() - 1 {
3219match client.try_acquire() {
3220Ok(Some(token)) => tokens.push(token),
3221Ok(None) => {}
3222Err(e) if e.kind() == io::ErrorKind::Unsupported => {
3223if !tokens.is_empty() {
::core::panicking::panic("assertion failed: tokens.is_empty()")
};assert!(tokens.is_empty());
3224 unsupported = true;
3225break;
3226 }
3227Err(e) => ::rustc_span::macros::bug_impl(None,
format_args!("IO error when acquiring jobserver token: {0}", e),
Location::caller())bug!("IO error when acquiring jobserver token: {e}"),
3228 }
3229 }
32303231let prefix = if sess.target.is_like_windows { "/threads:" } else { "--threads=" };
3232// Error on the side of oversubscription if non-blocking token acquiring is unsupported.
3233 // Linking is typically the last step in a multi-crate project build,
3234 // so the resources should usually be free.
3235let threads = if unsupported { limit.get() } else { 1 + tokens.len() };
3236cmd.link_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix, threads))
})format!("{prefix}{threads}"));
3237 }
32383239 (cmd.take_cmd(), tokens)
3240}
32413242fn add_order_independent_options(
3243 cmd: &mut dyn Linker,
3244 sess: &Session,
3245 link_output_kind: LinkOutputKind,
3246 self_contained_components: LinkSelfContainedComponents,
3247 flavor: LinkerFlavor,
3248 crate_type: CrateType,
3249 crate_info: &CrateInfo,
3250 out_filename: &Path,
3251 tmpdir: &Path,
3252) {
3253// Take care of the flavors and CLI options requesting the `lld` linker.
3254add_lld_args(cmd, sess, flavor, self_contained_components);
32553256add_apple_link_args(cmd, sess, flavor);
32573258let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
32593260if sess.target.os == Os::Fuchsia3261 && crate_type == CrateType::Executable3262 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))3263 {
3264let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
3265cmd.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"));
3266 }
32673268if sess.target.eh_frame_header {
3269cmd.add_eh_frame_header();
3270 }
32713272// Make the binary compatible with data execution prevention schemes.
3273cmd.add_no_exec();
32743275if self_contained_components.is_crt_objects_enabled() {
3276cmd.no_crt_objects();
3277 }
32783279if sess.target.os == Os::Emscripten {
3280cmd.cc_arg("-fwasm-exceptions");
3281 }
32823283if flavor == LinkerFlavor::Llbc {
3284cmd.link_args(&[
3285"--target",
3286&versioned_llvm_target(sess),
3287"--target-cpu",
3288&crate_info.target_cpu,
3289 ]);
3290if crate_info.target_features.len() > 0 {
3291cmd.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(",")));
3292 }
3293 } else if flavor == LinkerFlavor::Bpf {
3294cmd.link_args(&["--cpu", &crate_info.target_cpu]);
3295if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
3296 .into_iter()
3297 .find(|feat| !feat.is_empty())
3298 {
3299cmd.link_args(&["--cpu-features", feat]);
3300 }
3301 }
33023303cmd.linker_plugin_lto();
33043305add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
33063307cmd.output_filename(out_filename);
33083309if crate_type == CrateType::Executable3310 && sess.target.is_like_windows
3311 && let Some(s) = &crate_info.windows_subsystem
3312 {
3313cmd.windows_subsystem(*s);
3314 }
33153316// Try to strip as much out of the generated object by removing unused
3317 // sections if possible. See more comments in linker.rs
3318if !sess.link_dead_code() {
3319// If PGO is enabled sometimes gc_sections will remove the profile data section
3320 // as it appears to be unused. This can then cause the PGO profile file to lose
3321 // some functions. If we are generating a profile we shouldn't strip those metadata
3322 // sections to ensure we have all the data for PGO.
3323let keep_metadata =
3324crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
3325cmd.gc_sections(keep_metadata);
3326 }
33273328cmd.set_output_kind(link_output_kind, crate_type, out_filename);
33293330add_relro_args(cmd, sess);
33313332// Pass optimization flags down to the linker.
3333cmd.optimize();
33343335// Gather the set of NatVis files, if any, and write them out to a temp directory.
3336let natvis_visualizers = collect_natvis_visualizers(
3337tmpdir,
3338sess,
3339&crate_info.local_crate_name,
3340&crate_info.natvis_debugger_visualizers,
3341 );
33423343// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
3344cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
33453346// We want to prevent the compiler from accidentally leaking in any system libraries,
3347 // so by default we tell linkers not to link to any default libraries.
3348if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
3349cmd.no_default_libraries();
3350 }
33513352if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
3353cmd.pgo_gen();
3354 }
33553356if sess.opts.unstable_opts.instrument_mcount != InstrumentMcount::Disabled {
3357cmd.enable_profiling();
3358 }
33593360if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
3361cmd.control_flow_guard();
3362 }
33633364// OBJECT-FILES-NO, AUDIT-ORDER
3365if sess.opts.unstable_opts.ehcont_guard {
3366cmd.ehcont_guard();
3367 }
33683369add_rpath_args(cmd, sess, crate_info, out_filename);
3370}
33713372// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
3373fn collect_natvis_visualizers(
3374 tmpdir: &Path,
3375 sess: &Session,
3376 crate_name: &Symbol,
3377 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
3378) -> Vec<PathBuf> {
3379let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
33803381for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
3382let 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));
33833384match fs::write(&visualizer_out_file, &visualizer.src) {
3385Ok(()) => {
3386 visualizer_paths.push(visualizer_out_file);
3387 }
3388Err(error) => {
3389 sess.dcx().emit_warn(diagnostics::UnableToWriteDebuggerVisualizer {
3390 path: visualizer_out_file,
3391 error,
3392 });
3393 }
3394 };
3395 }
3396visualizer_paths3397}
33983399fn add_native_libs_from_crate(
3400 cmd: &mut dyn Linker,
3401 sess: &Session,
3402 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3403 rmeta_link_cache: &mut RmetaLinkCache,
3404 crate_info: &CrateInfo,
3405 tmpdir: &Path,
3406 bundled_libs: &FxIndexSet<Symbol>,
3407 cnum: CrateNum,
3408 link_static: bool,
3409 link_dynamic: bool,
3410 link_output_kind: LinkOutputKind,
3411) {
3412if !sess.opts.unstable_opts.link_native_libraries {
3413// If `-Zlink-native-libraries=false` is set, then the assumption is that an
3414 // external build system already has the native dependencies defined, and it
3415 // will provide them to the linker itself.
3416return;
3417 }
34183419if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
3420// If rlib contains native libs as archives, unpack them to tmpdir.
3421let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
3422archive_builder_builder3423 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
3424 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
3425 }
34263427let (native_libs, bundled_filenames): (&Vec<NativeLib>, Vec<Option<Symbol>>) = match cnum {
3428// Bundled libraries are only linked by path for upstream crates, so the local crate
3429 // never needs their filenames.
3430LOCAL_CRATE => (&crate_info.used_libraries, Vec::new()),
3431_ => {
3432let native_libs = &crate_info.native_libraries[&cnum];
3433let filenames =
3434if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
3435rmeta_link_cache.native_lib_filenames(&sess.target, rlib_path, native_libs)
3436 } else {
3437Vec::new()
3438 };
3439 (native_libs, filenames)
3440 }
3441 };
34423443let mut last = (None, NativeLibKind::Unspecified, false);
3444for (i, lib) in native_libs.iter().enumerate() {
3445if !relevant_lib(sess, lib) {
3446continue;
3447 }
34483449// Skip if this library is the same as the last.
3450last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
3451continue;
3452 } else {
3453 (Some(lib.name), lib.kind, lib.verbatim)
3454 };
34553456let name = lib.name.as_str();
3457let verbatim = lib.verbatim;
3458match lib.kind {
3459 NativeLibKind::Static { bundle, whole_archive, .. } => {
3460if link_static {
3461let bundle = bundle.unwrap_or(true);
3462let whole_archive = whole_archive == Some(true);
3463if bundle && cnum != LOCAL_CRATE {
3464if let Some(filename) = bundled_filenames.get(i).copied().flatten() {
3465// If rlib contains native libs as archives, they are unpacked to tmpdir.
3466let path = tmpdir.join(filename.as_str());
3467 cmd.link_staticlib_by_path(&path, whole_archive);
3468 }
3469 } else {
3470 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
3471 }
3472 }
3473 }
3474 NativeLibKind::Dylib { as_needed } => {
3475if link_dynamic {
3476 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
3477 }
3478 }
3479 NativeLibKind::Unspecified => {
3480// If we are generating a static binary, prefer static library when the
3481 // link kind is unspecified.
3482if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
3483if link_static {
3484 cmd.link_staticlib_by_name(name, verbatim, false);
3485 }
3486 } else if link_dynamic {
3487 cmd.link_dylib_by_name(name, verbatim, true);
3488 }
3489 }
3490 NativeLibKind::Framework { as_needed } => {
3491if link_dynamic {
3492 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
3493 }
3494 }
3495 NativeLibKind::RawDylib { as_needed: _ } => {
3496// Handled separately in `linker_with_args`.
3497}
3498 NativeLibKind::WasmImportModule => {}
3499 NativeLibKind::LinkArg => {
3500if link_static {
3501if verbatim {
3502 cmd.verbatim_arg(name);
3503 } else {
3504 cmd.link_arg(name);
3505 }
3506 }
3507 }
3508 }
3509 }
3510}
35113512fn add_local_native_libraries(
3513 cmd: &mut dyn Linker,
3514 sess: &Session,
3515 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3516 rmeta_link_cache: &mut RmetaLinkCache,
3517 crate_info: &CrateInfo,
3518 tmpdir: &Path,
3519 link_output_kind: LinkOutputKind,
3520) {
3521// All static and dynamic native library dependencies are linked to the local crate.
3522let link_static = true;
3523let link_dynamic = true;
3524add_native_libs_from_crate(
3525cmd,
3526sess,
3527archive_builder_builder,
3528rmeta_link_cache,
3529crate_info,
3530tmpdir,
3531&Default::default(),
3532LOCAL_CRATE,
3533link_static,
3534link_dynamic,
3535link_output_kind,
3536 );
3537}
35383539fn add_upstream_rust_crates(
3540 cmd: &mut dyn Linker,
3541 sess: &Session,
3542 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3543 rmeta_link_cache: &mut RmetaLinkCache,
3544 crate_info: &CrateInfo,
3545 crate_type: CrateType,
3546 tmpdir: &Path,
3547 link_output_kind: LinkOutputKind,
3548) {
3549// All of the heavy lifting has previously been accomplished by the
3550 // dependency_format module of the compiler. This is just crawling the
3551 // output of that module, adding crates as necessary.
3552 //
3553 // Linking to a rlib involves just passing it to the linker (the linker
3554 // will slurp up the object files inside), and linking to a dynamic library
3555 // involves just passing the right -l flag.
3556let data = crate_info3557 .dependency_formats
3558 .get(&crate_type)
3559 .expect("failed to find crate type in dependency format list");
35603561if sess.target.is_like_aix {
3562// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3563 // the dependency name when outputting a shared library. Thus, `ld` will
3564 // use the full path to shared libraries as the dependency if passed it
3565 // by default unless `noipath` is passed.
3566 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3567cmd.link_or_cc_arg("-bnoipath");
3568 }
35693570for &cnum in &crate_info.used_crates {
3571// We may not pass all crates through to the linker. Some crates may appear statically in
3572 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3573 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3574 // Even if they were already included into a dylib
3575 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3576 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3577 // See the comment in inject_profiler_runtime for why this is the case.
3578let linkage = data[cnum];
3579let link_static_crate = linkage == Linkage::Static
3580 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3581 && (crate_info.compiler_builtins == Some(cnum)
3582 || crate_info.profiler_runtime == Some(cnum));
35833584let mut bundled_libs = Default::default();
3585match linkage {
3586 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3587if link_static_crate {
3588if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
3589 bundled_libs = rmeta_link_cache
3590 .native_lib_filenames(
3591&sess.target,
3592 rlib_path,
3593&crate_info.native_libraries[&cnum],
3594 )
3595 .into_iter()
3596 .flatten()
3597 .collect();
3598 }
3599 add_static_crate(
3600 cmd,
3601 sess,
3602 archive_builder_builder,
3603 rmeta_link_cache,
3604 crate_info,
3605 tmpdir,
3606 cnum,
3607&bundled_libs,
3608 );
3609 }
3610 }
3611 Linkage::Dynamic => {
3612let src = &crate_info.used_crate_source[&cnum];
3613 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3614 }
3615 }
36163617// Static libraries are linked for a subset of linked upstream crates.
3618 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3619 // because the rlib is just an archive.
3620 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3621 // the native library because it is already linked into the dylib, and even if
3622 // inline/const/generic functions from the dylib can refer to symbols from the native
3623 // library, those symbols should be exported and available from the dylib anyway.
3624 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3625let link_static = link_static_crate;
3626// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3627let link_dynamic = false;
3628 add_native_libs_from_crate(
3629 cmd,
3630 sess,
3631 archive_builder_builder,
3632 rmeta_link_cache,
3633 crate_info,
3634 tmpdir,
3635&bundled_libs,
3636 cnum,
3637 link_static,
3638 link_dynamic,
3639 link_output_kind,
3640 );
3641 }
3642}
36433644fn add_upstream_native_libraries(
3645 cmd: &mut dyn Linker,
3646 sess: &Session,
3647 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3648 rmeta_link_cache: &mut RmetaLinkCache,
3649 crate_info: &CrateInfo,
3650 tmpdir: &Path,
3651 link_output_kind: LinkOutputKind,
3652) {
3653for &cnum in &crate_info.used_crates {
3654// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3655 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3656 // are linked together with their respective upstream crates, and in their originally
3657 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3658 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3659let link_static = false;
3660// Dynamic libraries are linked for all linked upstream crates.
3661 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3662 // because the rlib is just an archive.
3663 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3664 // the native library too because inline/const/generic functions from the dylib can refer
3665 // to symbols from the native library, so the native library providing those symbols should
3666 // be available when linking our final binary.
3667let link_dynamic = true;
3668 add_native_libs_from_crate(
3669 cmd,
3670 sess,
3671 archive_builder_builder,
3672 rmeta_link_cache,
3673 crate_info,
3674 tmpdir,
3675&Default::default(),
3676 cnum,
3677 link_static,
3678 link_dynamic,
3679 link_output_kind,
3680 );
3681 }
3682}
36833684// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3685// to be relative to the sysroot directory, which may be a relative path specified by the user.
3686//
3687// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3688// linker command line can be non-deterministic due to the paths including the current working
3689// directory. The linker command line needs to be deterministic since it appears inside the PDB
3690// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3691//
3692// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3693fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3694let sysroot_lib_path = &sess.target_tlib_path.dir;
3695let canonical_sysroot_lib_path =
3696 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.to_path_buf()) };
36973698let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3699if canonical_lib_dir == canonical_sysroot_lib_path {
3700// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3701sysroot_lib_path.to_path_buf()
3702 } else {
3703fix_windows_verbatim_for_gcc(lib_dir)
3704 }
3705}
37063707fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3708if let Some(dir) = path.parent() {
3709let file_name = path.file_name().expect("library path has no file name component");
3710rehome_sysroot_lib_dir(sess, dir).join(file_name)
3711 } else {
3712fix_windows_verbatim_for_gcc(path)
3713 }
3714}
37153716// Adds the static "rlib" versions of all crates to the command line.
3717// There's a bit of magic which happens here specifically related to LTO,
3718// namely that we remove upstream object files.
3719//
3720// When performing LTO, almost(*) all of the bytecode from the upstream
3721// libraries has already been included in our object file output. As a
3722// result we need to remove the object files in the upstream libraries so
3723// the linker doesn't try to include them twice (or whine about duplicate
3724// symbols). We must continue to include the rest of the rlib, however, as
3725// it may contain static native libraries which must be linked in.
3726//
3727// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3728// their bytecode wasn't included. The object files in those libraries must
3729// still be passed to the linker.
3730//
3731// Note, however, that if we're not doing LTO we can just pass the rlib
3732// blindly to the linker (fast) because it's fine if it's not actually
3733// included as we're at the end of the dependency chain.
3734fn add_static_crate(
3735 cmd: &mut dyn Linker,
3736 sess: &Session,
3737 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3738 rmeta_link_cache: &mut RmetaLinkCache,
3739 crate_info: &CrateInfo,
3740 tmpdir: &Path,
3741 cnum: CrateNum,
3742 bundled_lib_file_names: &FxIndexSet<Symbol>,
3743) {
3744let src = &crate_info.used_crate_source[&cnum];
3745let cratepath = src.rlib.as_ref().unwrap();
37463747let mut link_upstream =
3748 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
37493750if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3751 {
3752link_upstream(cratepath);
3753return;
3754 }
37553756let dst = tmpdir.join(cratepath.file_name().unwrap());
3757let name = cratepath.file_name().unwrap().to_str().unwrap();
3758let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3759let bundled_lib_file_names = bundled_lib_file_names.clone();
37603761sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3762let upstream_rust_objects_already_included =
3763are_upstream_rust_objects_already_included(sess);
3764let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
37653766let mut archive = archive_builder_builder.new_archive_builder(sess);
3767if let Err(error) = archive.add_archive(
3768cratepath,
3769 AddArchiveKind::Rlib(rmeta_link_cache, &|f, entry_kind| {
3770if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3771return true;
3772 }
37733774// If we're performing LTO and this is a rust-generated object
3775 // file, then we don't need the object file as it's part of the
3776 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3777 // though, so we let that object file slide.
3778if upstream_rust_objects_already_included3779 && entry_kind == ArchiveEntryKind::RustObj3780 && is_builtins3781 {
3782return true;
3783 }
37843785// We skip native libraries because:
3786 // 1. This native libraries won't be used from the generated rlib,
3787 // so we can throw them away to avoid the copying work.
3788 // 2. We can't allow it to be a single remaining entry in archive
3789 // as some linkers may complain on that.
3790if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3791return true;
3792 }
37933794false
3795}),
3796 ) {
3797sess.dcx().emit_fatal(diagnostics::RlibArchiveBuildFailure {
3798 path: cratepath.clone(),
3799error,
3800 });
3801 }
3802if archive.build(&dst, None) {
3803link_upstream(&dst);
3804 }
3805 });
3806}
38073808// Same thing as above, but for dynamic crates instead of static crates.
3809fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3810cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3811}
38123813fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3814match lib.cfg {
3815Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3816None => true,
3817 }
3818}
38193820pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3821match sess.lto() {
3822 config::Lto::Fat => true,
3823 config::Lto::Thin => {
3824// If we defer LTO to the linker, we haven't run LTO ourselves, so
3825 // any upstream object files have not been copied yet.
3826!sess.opts.cg.linker_plugin_lto.enabled()
3827 }
3828 config::Lto::No | config::Lto::ThinLocal => false,
3829 }
3830}
38313832/// We need to communicate five things to the linker on Apple/Darwin targets:
3833/// - The architecture.
3834/// - The operating system (and that it's an Apple platform).
3835/// - The environment.
3836/// - The deployment target.
3837/// - The SDK version.
3838fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3839if !sess.target.is_like_darwin {
3840return;
3841 }
3842let LinkerFlavor::Darwin(cc, _) = flavorelse {
3843return;
3844 };
38453846// `sess.target.arch` (`target_arch`) is not detailed enough.
3847let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3848let target_os = &sess.target.os;
3849let target_env = &sess.target.env;
38503851// The architecture name to forward to the linker.
3852 //
3853 // Supported architecture names can be found in the source:
3854 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3855 //
3856 // Intentionally verbose to ensure that the list always matches correctly
3857 // with the list in the source above.
3858let ld64_arch = match llvm_arch {
3859"armv7k" => "armv7k",
3860"armv7s" => "armv7s",
3861"arm64" => "arm64",
3862"arm64e" => "arm64e",
3863"arm64_32" => "arm64_32",
3864// ld64 doesn't understand i686, so fall back to i386 instead.
3865 //
3866 // Same story when linking with cc, since that ends up invoking ld64.
3867"i386" | "i686" => "i386",
3868"x86_64" => "x86_64",
3869"x86_64h" => "x86_64h",
3870_ => ::rustc_span::macros::bug_impl(None,
format_args!("unsupported architecture in Apple target: {0}",
sess.target.llvm_target), Location::caller())bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3871 };
38723873if cc == Cc::No {
3874// From the man page for ld64 (`man ld`):
3875 // > The linker accepts universal (multiple-architecture) input files,
3876 // > but always creates a "thin" (single-architecture), standard
3877 // > Mach-O output file. The architecture for the output file is
3878 // > specified using the -arch option.
3879 //
3880 // The linker has heuristics to determine the desired architecture,
3881 // but to be safe, and to avoid a warning, we set the architecture
3882 // explicitly.
3883cmd.link_args(&["-arch", ld64_arch]);
38843885// Man page says that ld64 supports the following platform names:
3886 // > - macos
3887 // > - ios
3888 // > - tvos
3889 // > - watchos
3890 // > - bridgeos
3891 // > - visionos
3892 // > - xros
3893 // > - mac-catalyst
3894 // > - ios-simulator
3895 // > - tvos-simulator
3896 // > - watchos-simulator
3897 // > - visionos-simulator
3898 // > - xros-simulator
3899 // > - driverkit
3900let platform_name = match (target_os, target_env) {
3901 (os, Env::Unspecified) => os.desc(),
3902 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3903 (Os::IOs, Env::Sim) => "ios-simulator",
3904 (Os::TvOs, Env::Sim) => "tvos-simulator",
3905 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3906 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3907_ => ::rustc_span::macros::bug_impl(None,
format_args!("invalid OS/env combination for Apple target: {0}, {1}",
target_os, target_env), Location::caller())bug!("invalid OS/env combination for Apple target: {target_os}, {target_env}"),
3908 };
39093910let min_version = sess.apple_deployment_target().fmt_full().to_string();
39113912// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3913 // - By dyld to give extra warnings and errors, see e.g.:
3914 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3915 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3916 // - By system frameworks to change certain behaviour. For example, the default value of
3917 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3918 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3919 //
3920 // We do not currently know the actual SDK version though, so we have a few options:
3921 // 1. Use the minimum version supported by rustc.
3922 // 2. Use the same as the deployment target.
3923 // 3. Use an arbitrary recent version.
3924 // 4. Omit the version.
3925 //
3926 // The first option is too low / too conservative, and means that users will not get the
3927 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3928 //
3929 // The second option is similarly conservative, and also wrong since if the user specified a
3930 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3931 // make invalid assumptions about the capabilities of the binary.
3932 //
3933 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3934 // version, and is also wrong for similar reasons as above.
3935 //
3936 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3937 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3938 // it as 0.0, which is again too low/conservative.
3939 //
3940 // Currently, we lie about the SDK version, and choose the second option.
3941 //
3942 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3943 // <https://github.com/rust-lang/rust/issues/129432>
3944let sdk_version = &*min_version;
39453946// From the man page for ld64 (`man ld`):
3947 // > This is set to indicate the platform, oldest supported version of
3948 // > that platform that output is to be used on, and the SDK that the
3949 // > output was built against.
3950 //
3951 // Like with `-arch`, the linker can figure out the platform versions
3952 // itself from the binaries being linked, but to be safe, we specify
3953 // the desired versions here explicitly.
3954cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3955 } else {
3956// cc == Cc::Yes
3957 //
3958 // We'd _like_ to use `-target` everywhere, since that can uniquely
3959 // communicate all the required details except for the SDK version
3960 // (which is read by Clang itself from the SDKROOT), but that doesn't
3961 // work on GCC, and since we don't know whether the `cc` compiler is
3962 // Clang, GCC, or something else, we fall back to other options that
3963 // also work on GCC when compiling for macOS.
3964 //
3965 // Targets other than macOS are ill-supported by GCC (it doesn't even
3966 // support e.g. `-miphoneos-version-min`), so in those cases we can
3967 // fairly safely use `-target`. See also the following, where it is
3968 // made explicit that the recommendation by LLVM developers is to use
3969 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3970if *target_os == Os::MacOs {
3971// `-arch` communicates the architecture.
3972 //
3973 // CC forwards the `-arch` to the linker, so we use the same value
3974 // here intentionally.
3975cmd.cc_args(&["-arch", ld64_arch]);
39763977// The presence of `-mmacosx-version-min` makes CC default to
3978 // macOS, and it sets the deployment target.
3979let version = sess.apple_deployment_target().fmt_full();
3980// Intentionally pass this as a single argument, Clang doesn't
3981 // seem to like it otherwise.
3982cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
39833984// macOS has no environment, so with these two, we've told CC the
3985 // four desired parameters.
3986 //
3987 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3988} else {
3989cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3990 }
3991 }
3992}
39933994fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3995if !sess.target.is_like_darwin {
3996return None;
3997 }
3998let LinkerFlavor::Darwin(cc, _) = flavorelse {
3999return None;
4000 };
40014002// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
4003 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
4004 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
4005 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
4006 // instead we invoke `xcrun` manually.
4007 //
4008 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
4009 // cause the trampoline binary to skip looking up the SDK itself).
4010let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
40114012if cc == Cc::Yes {
4013// There are a few options to pass the SDK root when linking with a C/C++ compiler:
4014 // - The `--sysroot` flag.
4015 // - The `-isysroot` flag.
4016 // - The `SDKROOT` environment variable.
4017 //
4018 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
4019 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
4020 // only applies to include header files, but on Apple targets it also applies to libraries
4021 // and frameworks.
4022 //
4023 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
4024 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
4025 // primarily because that is the same interface that is used when invoking the tool under
4026 // `xcrun -sdk macosx $tool`.
4027 //
4028 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
4029 // clearly in the tool in question, since they also don't support being run under `xcrun`.
4030 //
4031 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
4032 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
4033 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
4034 //
4035 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
4036 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
4037 // ignoring the value we set here, and instead use their built-in sysroot).
4038cmd.cmd().env("SDKROOT", &sdkroot);
4039 } else {
4040// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
4041 // read by the linker, so it's really the only option.
4042 //
4043 // This is also what Clang does.
4044cmd.link_arg("-syslibroot");
4045cmd.link_arg(&sdkroot);
4046 }
40474048Some(sdkroot)
4049}
40504051fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
4052if let Ok(sdkroot) = env::var("SDKROOT") {
4053let p = PathBuf::from(&sdkroot);
40544055// Ignore invalid SDKs, similar to what clang does:
4056 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
4057 //
4058 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
4059 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
4060 // clearly set for the wrong platform.
4061 //
4062 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
4063match &*apple::sdk_name(&sess.target).to_lowercase() {
4064"appletvos"
4065if sdkroot.contains("TVSimulator.platform")
4066 || sdkroot.contains("MacOSX.platform") => {}
4067"appletvsimulator"
4068if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
4069"iphoneos"
4070if sdkroot.contains("iPhoneSimulator.platform")
4071 || sdkroot.contains("MacOSX.platform") => {}
4072"iphonesimulator"
4073if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
4074 }
4075"macosx"
4076if sdkroot.contains("iPhoneOS.platform")
4077 || sdkroot.contains("iPhoneSimulator.platform")
4078 || sdkroot.contains("AppleTVOS.platform")
4079 || sdkroot.contains("AppleTVSimulator.platform")
4080 || sdkroot.contains("WatchOS.platform")
4081 || sdkroot.contains("WatchSimulator.platform")
4082 || sdkroot.contains("XROS.platform")
4083 || sdkroot.contains("XRSimulator.platform") => {}
4084"watchos"
4085if sdkroot.contains("WatchSimulator.platform")
4086 || sdkroot.contains("MacOSX.platform") => {}
4087"watchsimulator"
4088if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
4089"xros"
4090if sdkroot.contains("XRSimulator.platform")
4091 || sdkroot.contains("MacOSX.platform") => {}
4092"xrsimulator"
4093if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
4094// Ignore `SDKROOT` if it's not a valid path.
4095_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
4096_ => return Some(p),
4097 }
4098 }
40994100 apple::get_sdk_root(sess)
4101}
41024103/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
4104/// invoke it:
4105/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
4106/// - or any `lld` available to `cc`.
4107fn add_lld_args(
4108 cmd: &mut dyn Linker,
4109 sess: &Session,
4110 flavor: LinkerFlavor,
4111 self_contained_components: LinkSelfContainedComponents,
4112) {
4113{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs:4113",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(4113u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_lld_args requested, flavor: \'{0:?}\', target self-contained components: {1:?}",
flavor, self_contained_components) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
4114"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
4115 flavor, self_contained_components,
4116 );
41174118// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
4119 // we don't need to do anything.
4120if !(flavor.uses_cc() && flavor.uses_lld()) {
4121return;
4122 }
41234124// 1. Implement the "self-contained" part of this feature by adding rustc distribution
4125 // directories to the tool's search path, depending on a mix between what users can specify on
4126 // the CLI, and what the target spec enables (as it can't disable components):
4127 // - if the self-contained linker is enabled on the CLI or by the target spec,
4128 // - and if the self-contained linker is not disabled on the CLI.
4129let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
4130let self_contained_target = self_contained_components.is_linker_enabled();
41314132let self_contained_linker = self_contained_cli || self_contained_target;
4133if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
4134let mut linker_path_exists = false;
4135for path in sess.get_tools_search_paths(false) {
4136let linker_path = path.join("gcc-ld");
4137 linker_path_exists |= linker_path.exists();
4138 cmd.cc_arg({
4139let mut arg = OsString::from("-B");
4140 arg.push(linker_path);
4141 arg
4142 });
4143 }
4144if !linker_path_exists {
4145// As a sanity check, we emit an error if none of these paths exist: we want
4146 // self-contained linking and have no linker.
4147sess.dcx().emit_fatal(diagnostics::SelfContainedLinkerMissing);
4148 }
4149 }
41504151// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
4152 // `lld` as the linker.
4153 //
4154 // Note that wasm targets skip this step since the only option there anyway
4155 // is to use LLD but component-producing targets rely on a wrapper around
4156 // this, `wasm-component-ld`, which is overridden if this option is passed.
4157if !sess.target.is_like_wasm {
4158cmd.cc_arg("-fuse-ld=lld");
4159 }
41604161if !flavor.is_gnu() {
4162// Tell clang to use a non-default LLD flavor.
4163 // Gcc doesn't understand the target option, but we currently assume
4164 // that gcc is not used for Apple and Wasm targets (#97402).
4165 //
4166 // Note that we don't want to do that by default on macOS: e.g. passing a
4167 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
4168 // shown in issue #101653 and the discussion in PR #101792.
4169 //
4170 // It could be required in some cases of cross-compiling with
4171 // LLD, but this is generally unspecified, and we don't know
4172 // which specific versions of clang, macOS SDK, host and target OS
4173 // combinations impact us here.
4174 //
4175 // So we do a simple first-approximation until we know more of what the
4176 // Apple targets require (and which would be handled prior to hitting this
4177 // LLD codepath anyway), but the expectation is that until then
4178 // this should be manually passed if needed. We specify the target when
4179 // targeting a different linker flavor on macOS, and that's also always
4180 // the case when targeting WASM.
4181if sess.target.linker_flavor != sess.host.linker_flavor {
4182cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
4183 }
4184 }
4185}
41864187// gold has been deprecated with binutils 2.44
4188// and is known to behave incorrectly around Rust programs.
4189// There have been reports of being unable to bootstrap with gold:
4190// https://github.com/rust-lang/rust/issues/139425
4191// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
4192// emitted with `#[used(linker)]`.
4193fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
4194use object::read::elf::{FileHeader, SectionHeader};
4195use object::read::{ReadCache, ReadRef, Result};
4196use object::{Endianness, elf};
41974198fn elf_has_gold_version_note<'a>(
4199 elf: &impl FileHeader,
4200 data: impl ReadRef<'a>,
4201 ) -> Result<bool> {
4202let endian = elf.endian()?;
42034204let section =
4205 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
4206if let Some((_, section)) = section4207 && let Some(mut notes) = section.notes(endian, data)?
4208{
4209return Ok(notes.any(|note| {
4210note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
4211 }));
4212 }
42134214Ok(false)
4215 }
42164217let data = ReadCache::new(BufReader::new(File::open(path)?));
42184219let was_linked_with_gold = if sess.target.pointer_width == 64 {
4220let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
4221 elf_has_gold_version_note(elf, &data)?
4222} else if sess.target.pointer_width == 32 {
4223let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
4224 elf_has_gold_version_note(elf, &data)?
4225} else {
4226return Ok(());
4227 };
42284229if was_linked_with_gold {
4230let mut warn =
4231sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
4232warn.help("consider using LLD or ld from GNU binutils instead");
4233warn.emit();
4234 }
4235Ok(())
4236}