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, JobsMode, LinkerFeaturesCli, LinkerJobs,
36OutFileName, OutputFilenames, PrintKind, SplitDwarfKind, Strip,
37};
38use rustc_session::output::{
39OutputType, check_file_is_writeable, invalid_output_for_target, out_filename,
40};
41use rustc_session::search_paths::PathKind;
42/// For all the linkers we support, and information they might
43/// need out of the shared crate context before we get rid of it.
44use rustc_session::{Session, filesearch};
45use rustc_span::{Symbol, bug};
46use rustc_structures::{CrateType, NativeLibKind};
47use rustc_target::spec::crt_objects::CrtObjects;
48use rustc_target::spec::{
49Arch, BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
50LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
51RelroLevel, SanitizerSet, SplitDebuginfo,
52};
53use tracing::{debug, info, warn};
5455use super::archive::{
56AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind, ArchiveSymbols,
57};
58use super::command::Command;
59use super::linker::{self, Linker};
60use super::metadata::{MetadataPosition, create_wrapper_file};
61use super::rmeta_link::RmetaLinkCache;
62use super::rpath::{self, RPathConfig};
63use super::{apple, rmeta_link, symbol_export, versioned_llvm_target};
64use crate::base::needs_allocator_shim_for_linking;
65use crate::{
66CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, SymbolExport,
67diagnostics,
68};
6970pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
71if let Err(e) = fs::remove_file(path) {
72if e.kind() != io::ErrorKind::NotFound {
73dcx.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));
74 }
75 }
76}
7778fn eii_impl_crate_name(crate_info: &CrateInfo, cnum: CrateNum) -> Symbol {
79if cnum == LOCAL_CRATE { crate_info.local_crate_name } else { crate_info.crate_name[&cnum] }
80}
8182fn check_externally_implementable_item_linkage(sess: &Session, crate_info: &CrateInfo) {
83if crate_info.eii_linkage.is_empty() {
84return;
85 }
8687// A crate can request multiple linked outputs with overlapping dependency
88 // formats, so report each underlying conflict once.
89let mut emitted = FxHashSet::default();
9091// This needs the dependency formats selected for the final artifact. The
92 // earlier EII pass still handles missing impls and duplicate explicit impls.
93for dependency_formats in crate_info.dependency_formats.values() {
94for (eii_index, eii) in crate_info.eii_linkage.iter().enumerate() {
95let Some(explicit_impl) = eii.impls.first() else {
96continue;
97 };
98// If the explicit impl is already coming from a dylib, that dylib
99 // has already resolved the default-vs-explicit choice.
100if #[allow(non_exhaustive_omitted_patterns)] match dependency_formats.get(explicit_impl.impl_crate)
{
Some(Linkage::Dynamic | Linkage::IncludedFromDylib) => true,
_ => false,
}matches!(
101 dependency_formats.get(explicit_impl.impl_crate),
102Some(Linkage::Dynamic | Linkage::IncludedFromDylib)
103 ) {
104continue;
105 }
106107let Some(default_impl) = &eii.default_impl else {
108continue;
109 };
110if !#[allow(non_exhaustive_omitted_patterns)] match dependency_formats.get(default_impl.impl_crate)
{
Some(Linkage::Dynamic | Linkage::IncludedFromDylib) => true,
_ => false,
}matches!(
111 dependency_formats.get(default_impl.impl_crate),
112Some(Linkage::Dynamic | Linkage::IncludedFromDylib)
113 ) {
114continue;
115 }
116117if !emitted.insert(eii_index) {
118continue;
119 }
120121 sess.dcx().emit_err(DuplicateEiiImpls {
122 name: eii.name,
123 first_span: explicit_impl.span,
124 first_crate: eii_impl_crate_name(crate_info, explicit_impl.impl_crate),
125 second_span: default_impl.span,
126 second_crate: eii_impl_crate_name(crate_info, default_impl.impl_crate),
127 help: (),
128 additional_crates: None,
129 num_additional_crates: 0,
130 additional_crate_names: String::new(),
131 });
132 }
133 }
134}
135136/// The fallback directories are passed to linker, but not used when rustc does the search,
137/// because in the latter case the set of fallback directories cannot always be determined
138/// consistently at the moment.
139struct NativeLibSearchFallback<'a> {
140 self_contained_components: LinkSelfContainedComponents,
141 apple_sdk_root: Option<&'a Path>,
142}
143144fn walk_native_lib_search_dirs<R>(
145 sess: &Session,
146 fallback: Option<NativeLibSearchFallback<'_>>,
147mut f: impl FnMut(&Path, bool/*is_framework*/) -> ControlFlow<R>,
148) -> ControlFlow<R> {
149// Library search paths explicitly supplied by user (`-L` on the command line).
150for search_path in sess.target_filesearch().cli_search_paths(PathKind::Native) {
151 f(&search_path.dir, false)?;
152 }
153for search_path in sess.target_filesearch().cli_search_paths(PathKind::Framework) {
154// Frameworks are looked up strictly in framework-specific paths.
155if search_path.kind != PathKind::All {
156 f(&search_path.dir, true)?;
157 }
158 }
159160let Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root }) = fallback161else {
162return ControlFlow::Continue(());
163 };
164165// The toolchain ships some native library components and self-contained linking was enabled.
166 // Add the self-contained library directory to search paths.
167if self_contained_components.intersects(
168LinkSelfContainedComponents::LIBC169 | LinkSelfContainedComponents::UNWIND170 | LinkSelfContainedComponents::MINGW,
171 ) {
172 f(&sess.target_tlib_path.dir.join("self-contained"), false)?;
173 }
174175let has_shared_llvm_apple_darwin =
176sess.target.is_like_darwin && sess.target_tlib_path.dir.join("libLLVM.dylib").exists();
177178// Toolchains for some targets may ship `libunwind.a`, but place it into the main sysroot
179 // library directory instead of the self-contained directories.
180 // Sanitizer libraries have the same issue and are also linked by name on Apple targets.
181 // The targets here should be in sync with `copy_third_party_objects` in bootstrap.
182 // On Apple targets, shared LLVM is linked by name, so when `libLLVM.dylib` is
183 // present in the target libdir, add that directory to the linker search path.
184 // FIXME: implement `-Clink-self-contained=+/-unwind,+/-sanitizers`, move the shipped libunwind
185 // and sanitizers to self-contained directory, and stop adding this search path.
186 // FIXME: On AIX this also has the side-effect of making the list of library search paths
187 // non-empty, which is needed or the linker may decide to record the LIBPATH env, if
188 // defined, as the search path instead of appending the default search paths.
189if sess.target.cfg_abi == CfgAbi::Fortanix190 || sess.target.os == Os::Linux191 || sess.target.os == Os::Fuchsia192 || sess.target.is_like_aix
193 || sess.target.is_like_darwin
194 && (!sess.sanitizers().is_empty() || has_shared_llvm_apple_darwin)
195 || sess.target.os == Os::Windows196 && sess.target.env == Env::Gnu197 && sess.target.cfg_abi == CfgAbi::Llvm198 {
199 f(&sess.target_tlib_path.dir, false)?;
200 }
201202// Mac Catalyst uses the macOS SDK, but to link to iOS-specific frameworks
203 // we must have the support library stubs in the library search path (#121430).
204if let Some(sdk_root) = apple_sdk_root205 && sess.target.env == Env::MacAbi206 {
207 f(&sdk_root.join("System/iOSSupport/usr/lib"), false)?;
208 f(&sdk_root.join("System/iOSSupport/System/Library/Frameworks"), true)?;
209 }
210211 ControlFlow::Continue(())
212}
213214pub(super) fn try_find_native_static_library(
215 sess: &Session,
216 name: &str,
217 verbatim: bool,
218) -> Option<PathBuf> {
219let default = sess.staticlib_components(verbatim);
220let formats = if verbatim {
221::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default]))vec![default]222 } else {
223// On Windows, static libraries sometimes show up as libfoo.a and other
224 // times show up as foo.lib
225let unix = ("lib", ".a");
226if 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] }
227 };
228229walk_native_lib_search_dirs(sess, None, |dir, is_framework| {
230if !is_framework {
231for (prefix, suffix) in &formats {
232let test = dir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"));
233if test.exists() {
234return ControlFlow::Break(test);
235 }
236 }
237 }
238 ControlFlow::Continue(())
239 })
240 .break_value()
241}
242243pub(super) fn try_find_native_dynamic_library(
244 sess: &Session,
245 name: &str,
246 verbatim: bool,
247) -> Option<PathBuf> {
248let default = sess.staticlib_components(verbatim);
249let formats = if verbatim {
250::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[default]))vec![default]251 } else {
252// While the official naming convention for MSVC import libraries
253 // is foo.lib, Meson follows the libfoo.dll.a convention to
254 // disambiguate .a for static libraries
255let meson = ("lib", ".dll.a");
256// and MinGW uses .a altogether
257let mingw = ("lib", ".a");
258::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]259 };
260261walk_native_lib_search_dirs(sess, None, |dir, is_framework| {
262if !is_framework {
263for (prefix, suffix) in &formats {
264let test = dir.join(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"));
265if test.exists() {
266return ControlFlow::Break(test);
267 }
268 }
269 }
270 ControlFlow::Continue(())
271 })
272 .break_value()
273}
274275pub(super) fn find_native_static_library(name: &str, verbatim: bool, sess: &Session) -> PathBuf {
276try_find_native_static_library(sess, name, verbatim).unwrap_or_else(|| {
277sess.dcx().emit_fatal(diagnostics::MissingNativeLibrary::new(name, verbatim))
278 })
279}
280281/// If `lib` is a static library that is bundled into the rlib as a packed archive, returns the
282/// file name of that archive. Returns `None` for libraries that are instead unpacked into loose
283/// object files, or not bundled at all.
284fn find_bundled_library(
285 lib: &NativeLib,
286 sess: &Session,
287 crate_types: &[CrateType],
288) -> Option<Symbol> {
289if let NativeLibKind::Static { bundle: Some(true) | None, whole_archive, .. } = lib.kind
290 && crate_types.iter().any(|t| #[allow(non_exhaustive_omitted_patterns)] match t {
&CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(t, &CrateType::Rlib | CrateType::StaticLib))
291 && (sess.opts.unstable_opts.packed_bundled_libs
292 || lib.cfg.is_some()
293 || whole_archive == Some(true))
294 {
295return find_native_static_library(lib.name.as_str(), lib.verbatim, sess)
296 .file_name()
297 .and_then(|s| s.to_str())
298 .map(Symbol::intern);
299 }
300None301}
302303/// Performs the linkage portion of the compilation phase. This will generate all
304/// of the requested outputs for this compilation session.
305pub fn link_binary(
306 sess: &Session,
307 archive_builder_builder: &dyn ArchiveBuilderBuilder,
308 compiled_modules: CompiledModules,
309 crate_info: CrateInfo,
310 metadata: EncodedMetadata,
311 outputs: &OutputFilenames,
312 codegen_backend: &'static str,
313) {
314let _timer = sess.timer("link_binary");
315let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
316let mut rmeta_link_cache = RmetaLinkCache::default();
317318sess.time("check_externally_implementable_item_linkage", || {
319check_externally_implementable_item_linkage(sess, &crate_info);
320 });
321322sess.dcx().abort_if_errors();
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 && crate_type == CrateType::Executable {
327continue;
328 }
329330if invalid_output_for_target(sess, crate_type) {
331::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);
332 }
333334 sess.time("link_binary_check_files_are_writeable", || {
335for m in &compiled_modules.modules {
336if let Some(obj) = &m.object {
337 check_file_is_writeable(obj, sess);
338 }
339if let Some(obj) = &m.global_asm_object {
340 check_file_is_writeable(obj, sess);
341 }
342 }
343 });
344345if outputs.outputs.should_link() {
346let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
347let tmpdir = TempDirBuilder::new()
348 .prefix("rustc")
349 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
350 .unwrap_or_else(|error| {
351 sess.dcx().emit_fatal(diagnostics::CreateTempDir { error })
352 });
353let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
354355let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
356let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
357match crate_type {
358 CrateType::Rlib => {
359let _timer = sess.timer("link_rlib");
360{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:360",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(360u32),
::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);
361 link_rlib(
362 sess,
363 archive_builder_builder,
364&compiled_modules,
365&crate_info,
366&metadata,
367 RlibFlavor::Normal,
368&path,
369 )
370 .build(&out_filename, None);
371 }
372 CrateType::StaticLib => {
373 link_staticlib(
374 sess,
375 archive_builder_builder,
376&mut rmeta_link_cache,
377&compiled_modules,
378&crate_info,
379&metadata,
380&out_filename,
381&path,
382 );
383 }
384_ => {
385 link_natively(
386 sess,
387 archive_builder_builder,
388&mut rmeta_link_cache,
389 crate_type,
390&out_filename,
391&compiled_modules,
392&crate_info,
393&metadata,
394 path.as_ref(),
395 outputs,
396 codegen_backend,
397 );
398 }
399 }
400if sess.opts.json_artifact_notifications {
401 sess.dcx().emit_artifact_notification(&out_filename, "link");
402 }
403404if sess.prof.enabled()
405 && let Some(artifact_name) = out_filename.file_name()
406 {
407// Record size for self-profiling
408let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
409410 sess.prof.artifact_size(
411"linked_artifact",
412 artifact_name.to_string_lossy(),
413 file_size,
414 );
415 }
416417if sess.target.binary_format == BinaryFormat::Elf {
418if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
419{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:419",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(419u32),
::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");
420 }
421 }
422423if output.is_stdout() {
424if output.is_tty() {
425 sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
426 shorthand: OutputType::Exe.shorthand(),
427 });
428 } else if let Err(e) = copy_to_stdout(&out_filename) {
429 sess.dcx().emit_err(diagnostics::CopyPath::new(
430&out_filename,
431 output.as_path(),
432 e,
433 ));
434 }
435 tempfiles_for_stdout_output.push(out_filename);
436 }
437 }
438 }
439440// Remove the temporary object file and metadata if we aren't saving temps.
441sess.time("link_binary_remove_temps", || {
442// If the user requests that temporaries are saved, don't delete any.
443if sess.opts.cg.save_temps {
444return;
445 }
446447let maybe_remove_temps_from_module =
448 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
449if !preserve_objects && let Some(ref obj) = module.object {
450ensure_removed(sess.dcx(), obj);
451 }
452453if !preserve_objects && let Some(ref obj) = module.global_asm_object {
454ensure_removed(sess.dcx(), obj);
455 }
456457if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
458ensure_removed(sess.dcx(), dwo_obj);
459 }
460 };
461462let remove_temps_from_module =
463 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
464465// Otherwise, always remove the allocator module temporaries.
466if let Some(ref allocator_module) = compiled_modules.allocator_module {
467remove_temps_from_module(allocator_module);
468 }
469470// Remove the temporary files if output goes to stdout
471for temp in tempfiles_for_stdout_output {
472 ensure_removed(sess.dcx(), &temp);
473 }
474475// If no requested outputs require linking, then the object temporaries should
476 // be kept.
477if !sess.opts.output_types.should_link() {
478return;
479 }
480481// Potentially keep objects for their debuginfo.
482let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
483{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:483",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(483u32),
::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);
484485for module in &compiled_modules.modules {
486 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
487 }
488 });
489}
490491// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
492// crate types must use the same dependency formats.
493pub fn each_linked_rlib(
494 info: &CrateInfo,
495 crate_type: Option<CrateType>,
496 f: &mut dyn FnMut(CrateNum, &Path),
497) -> Result<(), diagnostics::LinkRlibError> {
498let fmts = if let Some(crate_type) = crate_type {
499let Some(fmts) = info.dependency_formats.get(&crate_type) else {
500return Err(diagnostics::LinkRlibError::MissingFormat);
501 };
502503fmts504 } else {
505let mut dep_formats = info.dependency_formats.iter();
506let (ty1, list1) = dep_formats.next().ok_or(diagnostics::LinkRlibError::MissingFormat)?;
507if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
508return Err(diagnostics::LinkRlibError::IncompatibleDependencyFormats {
509 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
510 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
511 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
512 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
513 });
514 }
515list1516 };
517518let used_dep_crates = info.used_crates.iter();
519for &cnum in used_dep_crates {
520match fmts.get(cnum) {
521Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
522Some(_) => {}
523None => return Err(diagnostics::LinkRlibError::MissingFormat),
524 }
525let crate_name = info.crate_name[&cnum];
526let used_crate_source = &info.used_crate_source[&cnum];
527if let Some(path) = &used_crate_source.rlib {
528 f(cnum, path);
529 } else if used_crate_source.rmeta.is_some() {
530return Err(diagnostics::LinkRlibError::OnlyRmetaFound { crate_name });
531 } else {
532return Err(diagnostics::LinkRlibError::NotFound { crate_name });
533 }
534 }
535Ok(())
536}
537538/// Create an 'rlib'.
539///
540/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
541/// The rlib primarily contains the object file of the crate, but it also some of the object files
542/// from native libraries.
543fn link_rlib<'a>(
544 sess: &'a Session,
545 archive_builder_builder: &dyn ArchiveBuilderBuilder,
546 compiled_modules: &CompiledModules,
547 crate_info: &CrateInfo,
548 metadata: &EncodedMetadata,
549 flavor: RlibFlavor,
550 tmpdir: &MaybeTempDir,
551) -> Box<dyn ArchiveBuilder + 'a> {
552let mut ab = archive_builder_builder.new_archive_builder(sess);
553554// Pre-compute the list of Rust object filenames and materialize the rmeta-link
555 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
556 // placed immediately after metadata in the archive, so consumers can find
557 // it without iterating every archive member.
558let rust_object_files: Vec<String> = compiled_modules559 .modules
560 .iter()
561 .filter_map(|m| m.object.as_ref())
562 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
563 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
564 .collect();
565566let native_lib_filenames: Vec<Option<Symbol>> = crate_info567 .used_libraries
568 .iter()
569 .map(|lib| find_bundled_library(lib, sess, &crate_info.crate_types))
570 .collect();
571572let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
573let native_lib_filenames: Vec<Option<String>> =
574native_lib_filenames.iter().map(|f| f.map(|s| s.to_string())).collect();
575let metadata_link = rmeta_link::RmetaLink { rust_object_files, native_lib_filenames };
576let metadata_link_data = metadata_link.encode();
577let (wrapper, _) =
578create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
579Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
580 } else {
581None582 };
583584let trailing_metadata = match flavor {
585 RlibFlavor::Normal => {
586let (metadata, metadata_position) =
587create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
588let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
589match metadata_position {
590 MetadataPosition::First => {
591// Most of the time metadata in rlib files is wrapped in a "dummy" object
592 // file for the target platform so the rlib can be processed entirely by
593 // normal linkers for the platform. Sometimes this is not possible however.
594 // If it is possible however, placing the metadata object first improves
595 // performance of getting metadata from rlibs.
596ab.add_file(&metadata, ArchiveEntryKind::Other);
597// Place the rmeta-link member immediately after metadata so consumers
598 // can find it without iterating the whole archive.
599if let Some(file) = &metadata_link_file {
600ab.add_file(file, ArchiveEntryKind::Other);
601 }
602None603 }
604 MetadataPosition::Last => Some(metadata),
605 }
606 }
607608 RlibFlavor::StaticlibBase => None,
609 };
610611for m in &compiled_modules.modules {
612if let Some(obj) = m.object.as_ref() {
613 ab.add_file(obj, ArchiveEntryKind::RustObj);
614 }
615616if let Some(obj) = m.global_asm_object.as_ref() {
617 ab.add_file(obj, ArchiveEntryKind::RustObj);
618 }
619620if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
621 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
622 }
623 }
624625match flavor {
626 RlibFlavor::Normal => {}
627 RlibFlavor::StaticlibBase => {
628if let Some(m) = &compiled_modules.allocator_module {
629if let Some(obj) = &m.object {
630ab.add_file(obj, ArchiveEntryKind::RustObj);
631 }
632if let Some(obj) = &m.global_asm_object {
633ab.add_file(obj, ArchiveEntryKind::RustObj);
634 }
635 }
636 }
637 }
638639// Used if packed_bundled_libs flag enabled.
640let mut packed_bundled_libs = Vec::new();
641642// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
643 // we may not be configured to actually include a static library if we're
644 // adding it here. That's because later when we consume this rlib we'll
645 // decide whether we actually needed the static library or not.
646 //
647 // To do this "correctly" we'd need to keep track of which libraries added
648 // which object files to the archive. We don't do that here, however. The
649 // #[link(cfg(..))] feature is unstable, though, and only intended to get
650 // liblibc working. In that sense the check below just indicates that if
651 // there are any libraries we want to omit object files for at link time we
652 // just exclude all custom object files.
653 //
654 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
655 // feature then we'll need to figure out how to record what objects were
656 // loaded from the libraries found here and then encode that into the
657 // metadata of the rlib we're generating somehow.
658for (i, lib) in crate_info.used_libraries.iter().enumerate() {
659let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
660continue;
661 };
662if flavor == RlibFlavor::Normal
663 && let Some(filename) = native_lib_filenames[i]
664 {
665let path = find_native_static_library(filename.as_str(), true, sess);
666let src = read(path).unwrap_or_else(|e| {
667 sess.dcx().emit_fatal(diagnostics::ReadFileError { message: e })
668 });
669let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
670let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
671 packed_bundled_libs.push(wrapper_file);
672 } else {
673let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
674 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
675 sess.dcx().emit_fatal(diagnostics::AddNativeLibrary { library_path: path, error })
676 });
677 }
678 }
679680// On Windows, we add the raw-dylib import libraries to the rlibs already.
681 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
682 // Instead, we add all raw-dylibs to the final link on ELF.
683if sess.target.is_like_windows {
684for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
685 sess,
686 archive_builder_builder,
687 crate_info.used_libraries.iter(),
688 tmpdir.as_ref(),
689true,
690 ) {
691 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
692 sess.dcx()
693 .emit_fatal(diagnostics::AddNativeLibrary { library_path: output_path, error });
694 });
695 }
696 }
697698if let Some(trailing_metadata) = trailing_metadata {
699// Note that it is important that we add all of our non-object "magical
700 // files" *after* all of the object files in the archive. The reason for
701 // this is as follows:
702 //
703 // * When performing LTO, this archive will be modified to remove
704 // objects from above. The reason for this is described below.
705 //
706 // * When the system linker looks at an archive, it will attempt to
707 // determine the architecture of the archive in order to see whether its
708 // linkable.
709 //
710 // The algorithm for this detection is: iterate over the files in the
711 // archive. Skip magical SYMDEF names. Interpret the first file as an
712 // object file. Read architecture from the object file.
713 //
714 // * As one can probably see, if "metadata" and "foo.bc" were placed
715 // before all of the objects, then the architecture of this archive would
716 // not be correctly inferred once 'foo.o' is removed.
717 //
718 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
719 // file for the target platform so the rlib can be processed entirely by
720 // normal linkers for the platform. Sometimes this is not possible however.
721 //
722 // Basically, all this means is that this code should not move above the
723 // code above.
724ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
725// Place the rmeta-link member immediately after metadata so consumers can
726 // find it without iterating the whole archive.
727if let Some(file) = &metadata_link_file {
728ab.add_file(file, ArchiveEntryKind::Other);
729 }
730 }
731732// Add all bundled static native library dependencies.
733 // Archives added to the end of .rlib archive, see comment above for the reason.
734for lib in packed_bundled_libs {
735 ab.add_file(&lib, ArchiveEntryKind::Other)
736 }
737738ab739}
740741/// Create a static archive.
742///
743/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
744/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
745/// dependencies as well.
746///
747/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
748/// library dependencies that they're not linked in.
749///
750/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
751/// object file (and also don't prepare the archive with a metadata file).
752fn link_staticlib(
753 sess: &Session,
754 archive_builder_builder: &dyn ArchiveBuilderBuilder,
755 rmeta_link_cache: &mut RmetaLinkCache,
756 compiled_modules: &CompiledModules,
757 crate_info: &CrateInfo,
758 metadata: &EncodedMetadata,
759 out_filename: &Path,
760 tempdir: &MaybeTempDir,
761) {
762{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:762",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(762u32),
::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);
763let mut ab = link_rlib(
764sess,
765archive_builder_builder,
766compiled_modules,
767crate_info,
768metadata,
769 RlibFlavor::StaticlibBase,
770tempdir,
771 );
772let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
773774let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
775let lto = are_upstream_rust_objects_already_included(sess)
776 && !ignored_for_lto(sess, crate_info, cnum);
777778let native_libs = &crate_info.native_libraries[&cnum];
779let bundled_filenames =
780rmeta_link_cache.native_lib_filenames(&sess.target, path, native_libs);
781let relevant_libs: FxIndexSet<_> = native_libs782 .iter()
783 .enumerate()
784 .filter(|(_, lib)| relevant_lib(sess, lib))
785 .filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
786 .collect();
787788let bundled_libs: FxIndexSet<_> = native_libs789 .iter()
790 .enumerate()
791 .filter_map(|(i, _)| bundled_filenames.get(i).copied().flatten())
792 .collect();
793ab.add_archive(
794path,
795 AddArchiveKind::Rlib(rmeta_link_cache, &|fname: &str, entry_kind| {
796// Ignore metadata and rmeta-link files.
797if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
798return true;
799 }
800801// Don't include Rust objects if LTO is enabled.
802if lto && entry_kind == ArchiveEntryKind::RustObj {
803return true;
804 }
805806// Skip objects for bundled libs.
807if bundled_libs.contains(&Symbol::intern(fname)) {
808return true;
809 }
810811false
812}),
813 )
814 .unwrap();
815816archive_builder_builder817 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
818 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
819820for filename in relevant_libs.iter() {
821let joined = tempdir.as_ref().join(filename.as_str());
822let path = joined.as_path();
823 ab.add_archive(path, AddArchiveKind::Other).unwrap();
824 }
825826all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
827 });
828if let Err(e) = res {
829sess.dcx().emit_fatal(e);
830 }
831832let hide = sess.opts.unstable_opts.staticlib_hide_internal_symbols;
833let rename = sess.opts.unstable_opts.staticlib_rename_internal_symbols;
834835let hide_supported =
836#[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);
837// Rename only rewrites symbol names, so it also works on COFF; hide
838 // needs a visibility concept COFF lacks.
839let rename_supported = #[allow(non_exhaustive_omitted_patterns)] match sess.target.binary_format {
BinaryFormat::Elf | BinaryFormat::MachO | BinaryFormat::Coff => true,
_ => false,
}matches!(
840 sess.target.binary_format,
841 BinaryFormat::Elf | BinaryFormat::MachO | BinaryFormat::Coff
842 );
843844let exported_symbols = if hide || rename {
845if hide && !hide_supported {
846sess.dcx().emit_warn(diagnostics::StaticlibHideInternalSymbolsUnsupported {
847 binary_format: sess.target.archive_format.to_string(),
848 });
849 }
850if rename && !rename_supported {
851sess.dcx().emit_warn(diagnostics::StaticlibRenameInternalSymbolsUnsupported {
852 binary_format: sess.target.archive_format.to_string(),
853 });
854 }
855if (hide && hide_supported) || (rename && rename_supported) {
856crate_info857 .exported_symbols
858 .get(&CrateType::StaticLib)
859 .map(|symbols| symbols.iter().map(|symbol| symbol.name.clone()).collect())
860 } else {
861None862 }
863 } else {
864None865 };
866867let symbols = exported_symbols.map(|exported| ArchiveSymbols {
868exported,
869 rename_suffix: (rename && rename_supported)
870 .then(|| crate_info.symbol_rename_suffix.clone()),
871// A warning was already emitted above if hiding was requested for an
872 // unsupported format; don't also ask the backend to hide there.
873hide: hide && hide_supported,
874 });
875876ab.build(out_filename, symbols);
877878let crates = crate_info.used_crates.iter();
879880let fmts = crate_info881 .dependency_formats
882 .get(&CrateType::StaticLib)
883 .expect("no dependency formats for staticlib");
884885let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
886for &cnum in crates {
887let Some(Linkage::Dynamic) = fmts.get(cnum) else {
888continue;
889 };
890let crate_name = crate_info.crate_name[&cnum];
891let used_crate_source = &crate_info.used_crate_source[&cnum];
892if let Some(path) = &used_crate_source.dylib {
893 all_rust_dylibs.push(&**path);
894 } else if used_crate_source.rmeta.is_some() {
895 sess.dcx().emit_fatal(diagnostics::LinkRlibError::OnlyRmetaFound { crate_name });
896 } else {
897 sess.dcx().emit_fatal(diagnostics::LinkRlibError::NotFound { crate_name });
898 }
899 }
900901all_native_libs.extend_from_slice(&crate_info.used_libraries);
902903for print in &sess.opts.prints {
904if print.kind == PrintKind::NativeStaticLibs {
905 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
906 }
907 }
908}
909910/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
911/// DWARF package.
912fn link_dwarf_object(
913 sess: &Session,
914 compiled_modules: &CompiledModules,
915 crate_info: &CrateInfo,
916 executable_out_filename: &Path,
917) {
918let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
919dwp_out_filename.push(".dwp");
920{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:920",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(920u32),
::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);
921922#[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)]
923struct ThorinSession<Relocations> {
924 arena_data: TypedArena<Vec<u8>>,
925 arena_mmap: TypedArena<Mmap>,
926 arena_relocations: TypedArena<Relocations>,
927 }
928929impl<Relocations> ThorinSession<Relocations> {
930fn alloc_mmap(&self, data: Mmap) -> &Mmap {
931&*self.arena_mmap.alloc(data)
932 }
933 }
934935impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
936fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
937&*self.arena_data.alloc(data)
938 }
939940fn alloc_relocation(&self, data: Relocations) -> &Relocations {
941&*self.arena_relocations.alloc(data)
942 }
943944fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
945let file = File::open(&path)?;
946let mmap = (unsafe { Mmap::map(file) })?;
947Ok(self.alloc_mmap(mmap))
948 }
949 }
950951match sess.time("run_thorin", || -> Result<(), thorin::Error> {
952let thorin_sess = ThorinSession::default();
953let mut package = thorin::DwarfPackage::new(&thorin_sess);
954955// Input objs contain .o/.dwo files from the current crate.
956match sess.opts.unstable_opts.split_dwarf_kind {
957 SplitDwarfKind::Single => {
958for m in &compiled_modules.modules {
959if let Some(input_obj) = &m.object {
960 package.add_input_object(input_obj)?;
961 }
962if let Some(input_obj) = &m.global_asm_object {
963 package.add_input_object(input_obj)?;
964 }
965 }
966 }
967 SplitDwarfKind::Split => {
968for input_obj in
969compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
970 {
971 package.add_input_object(input_obj)?;
972 }
973 }
974 }
975976// Input rlibs contain .o/.dwo files from dependencies.
977let input_rlibs = crate_info978 .used_crate_source
979 .items()
980 .filter_map(|(_, csource)| csource.rlib.as_ref())
981 .into_sorted_stable_ord();
982983for input_rlib in input_rlibs {
984{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:984",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(984u32),
::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);
985 package.add_input_object(input_rlib)?;
986 }
987988// Failing to read the referenced objects is expected for dependencies where the path in the
989 // executable will have been cleaned by Cargo, but the referenced objects will be contained
990 // within rlibs provided as inputs.
991 //
992 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
993 // found, but are provided explicitly above.
994 //
995 // Adding an executable is primarily done to make `thorin` check that all the referenced
996 // dwarf objects are found in the end.
997package.add_executable(
998 executable_out_filename,
999 thorin::MissingReferencedObjectBehaviour::Skip,
1000 )?;
10011002let output_stream = BufWriter::new(
1003 OpenOptions::new()
1004 .read(true)
1005 .write(true)
1006 .create(true)
1007 .truncate(true)
1008 .open(dwp_out_filename)?,
1009 );
1010let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
1011 package.finish()?.emit(&mut output_stream)?;
1012 output_stream.result()?;
1013 output_stream.into_inner().flush()?;
10141015Ok(())
1016 }) {
1017Ok(()) => {}
1018Err(e) => sess.dcx().emit_fatal(diagnostics::ThorinErrorWrapper(e)),
1019 }
1020}
10211022#[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)]
1023#[diag("{$inner}")]
1024/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
1025/// end up with inconsistent languages within the same diagnostic.
1026struct LinkerOutput {
1027 inner: String,
1028}
10291030fn is_msvc_link_exe(sess: &Session) -> bool {
1031let (linker_path, flavor) = linker_and_flavor(sess);
1032sess.target.is_like_msvc
1033 && flavor == LinkerFlavor::Msvc(Lld::No)
1034// Match exactly "link.exe"
1035&& linker_path.to_str() == Some("link.exe")
1036}
10371038fn is_macos_linker(sess: &Session) -> bool {
1039let (_, flavor) = linker_and_flavor(sess);
1040sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(..) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(..))1041}
10421043fn is_windows_gnu_ld(sess: &Session) -> bool {
1044let (_, flavor) = linker_and_flavor(sess);
1045sess.target.is_like_windows
1046 && !sess.target.is_like_msvc
1047 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))1048 && sess.target.options.cfg_abi != CfgAbi::Llvm1049}
10501051fn is_windows_gnu_clang(sess: &Session) -> bool {
1052let (_, flavor) = linker_and_flavor(sess);
1053sess.target.is_like_windows
1054 && !sess.target.is_like_msvc
1055 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))1056 && sess.target.options.cfg_abi == CfgAbi::Llvm1057}
10581059fn report_linker_output(
1060 sess: &Session,
1061 levels: CodegenLintLevelSpecs,
1062 stdout: &[u8],
1063 stderr: &[u8],
1064) {
1065let mut escaped_stderr = escape_string(&stderr);
1066let mut escaped_stdout = escape_string(&stdout);
1067let mut linker_info = String::new();
10681069{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1069",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1069u32),
::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);
1070{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1070",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1070u32),
::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);
10711072fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
1073let mut output = String::new();
1074if let Ok(str) = str::from_utf8(bytes) {
1075{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1075",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1075u32),
::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}");
1076output = String::with_capacity(str.len());
1077for line in str.lines() {
1078 f(line.trim(), &mut output);
1079 }
1080 }
1081escape_string(output.trim().as_bytes())
1082 }
10831084fn has_lnk_code(line: &str) -> bool {
1085// link.exe diagnostics are structured as `LINK : warning LNK####:` or
1086 // `LINK : fatal error LNK####:`. The code is always followed by a `:`
1087 // that is the second colon in the line, so matching that structure
1088 // instead of scanning for `LNK####` anywhere avoids false positives on
1089 // file names.
1090let Some((code_colon, _)) = line.match_indices(':').nth(1) else {
1091return false;
1092 };
1093let Some(code) = code_colon.checked_sub(7) else {
1094return false;
1095 };
1096let code = &line.as_bytes()[code..code_colon];
1097code.starts_with(b"LNK") && code[3..].iter().all(u8::is_ascii_digit)
1098 }
10991100if is_msvc_link_exe(sess) {
1101{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1101",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1101u32),
::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");
11021103escaped_stdout = for_each(&stdout, |line, output| {
1104// Hide progress messages from link.exe that we don't care about.
1105 // These include localized variants of the English messages (e.g.
1106 // "Creating library ..."), which rustc cannot recognize by text
1107 // without the English language pack.
1108 // See https://github.com/rust-lang/rust/issues/159133
1109 // When incremental linking is enabled and an .ilk exists, but its
1110 // associated .exe is missing, link.exe prints the path of the
1111 // missing .exe followed by:
1112let ilk_but_no_exe =
1113"not found or not built by the last incremental link; performing full link";
1114// LNK6004 is the one code-bearing line that is still informational.
1115if has_lnk_code(line) && !line.ends_with(ilk_but_no_exe) {
1116*output += line;
1117*output += "\r\n"
1118} else {
1119linker_info += line;
1120linker_info += "\r\n";
1121 }
1122 });
1123 } else if is_macos_linker(sess) {
1124{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1124",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1124u32),
::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");
11251126// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
1127let deployment_mismatch = |line: &str| {
1128// ld64 (object files + dylibs) and ld_prime (object files only):
1129(line.starts_with("ld: ")
1130 && line.contains("was built for newer")
1131 && line.contains("than being linked"))
1132// ld_prime (Xcode 15+, dylibs only):
1133|| (line.starts_with("ld: ")
1134 && line.contains("building for")
1135 && line.contains("but linking with")
1136 && line.contains("which was built for newer version"))
1137// lld (ld64.lld / rust-lld):
1138|| line.contains("which is newer than target minimum of")
1139 };
1140// FIXME: This is a real warning we would like to show, but it hits too many crates
1141 // to want to turn it on immediately.
1142let search_path = |line: &str| {
1143line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
1144 };
1145escaped_stderr = for_each(&stderr, |line, output| {
1146// This duplicate library warning is just not helpful at all.
1147if line.starts_with("ld: warning: ignoring duplicate libraries: ")
1148 || deployment_mismatch(line)
1149 || search_path(line)
1150 {
1151linker_info += line;
1152linker_info += "\n";
1153 } else {
1154*output += line;
1155*output += "\n"
1156}
1157 });
1158 } else if is_windows_gnu_ld(sess) {
1159{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1159",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1159u32),
::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");
11601161let mut saw_exclude_symbol = false;
1162// See https://github.com/rust-lang/rust/issues/112368.
1163 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
1164let exclude_symbols = |line: &str| {
1165line.starts_with("Warning: .drectve `-exclude-symbols:")
1166 && line.ends_with("' unrecognized")
1167 };
1168escaped_stderr = for_each(&stderr, |line, output| {
1169if exclude_symbols(line) {
1170saw_exclude_symbol = true;
1171linker_info += line;
1172linker_info += "\n";
1173 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
1174linker_info += line;
1175linker_info += "\n";
1176 } else {
1177*output += line;
1178*output += "\n"
1179}
1180 });
1181 } else if is_windows_gnu_clang(sess) {
1182{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1182",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1182u32),
::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)");
1183escaped_stderr = for_each(&stderr, |line, output| {
1184if line.contains("argument unused during compilation: '-nolibc'") {
1185linker_info += line;
1186linker_info += "\n";
1187 } else {
1188*output += line;
1189*output += "\n"
1190}
1191 });
1192 };
11931194let lint_msg = |msg| {
1195emit_lint_base(
1196sess,
1197LINKER_MESSAGES,
1198levels.linker_messages,
1199None,
1200LinkerOutput { inner: msg },
1201 );
1202 };
1203let lint_info = |msg| {
1204emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
1205 };
12061207if !escaped_stderr.is_empty() {
1208// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
1209escaped_stderr =
1210escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
1211// Windows GNU LD prints uppercase Warning
1212escaped_stderr = escaped_stderr1213 .strip_prefix("Warning: ")
1214 .unwrap_or(&escaped_stderr)
1215 .replace(": warning: ", ": ");
1216lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
1217 }
1218if !escaped_stdout.is_empty() {
1219lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
1220 }
1221if !linker_info.is_empty() {
1222lint_info(linker_info);
1223 }
1224}
12251226/// Create a dynamic library or executable.
1227///
1228/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
1229/// files as well.
1230fn link_natively(
1231 sess: &Session,
1232 archive_builder_builder: &dyn ArchiveBuilderBuilder,
1233 rmeta_link_cache: &mut RmetaLinkCache,
1234 crate_type: CrateType,
1235 out_filename: &Path,
1236 compiled_modules: &CompiledModules,
1237 crate_info: &CrateInfo,
1238 metadata: &EncodedMetadata,
1239 tmpdir: &Path,
1240 outputs: &OutputFilenames,
1241 codegen_backend: &'static str,
1242) {
1243{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1243",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1243u32),
::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);
1244let (linker_path, flavor) = linker_and_flavor(sess);
1245let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
12461247// On AIX, we ship all libraries as .a big_af archive
1248 // the expected format is lib<name>.a(libname.so) for the actual
1249 // dynamic library. So we link to a temporary .so file to be archived
1250 // at the final out_filename location
1251let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
1252let archive_member =
1253should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
1254let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
12551256// Follow the same naming convention as regular codegen objects.
1257let metadata_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_metadata");
1258let symbols_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_symbols");
12591260// Clean up the generated linker inputs even if linking fails.
1261let _cleanup = rustc_data_structures::defer(|| {
1262if !sess.opts.cg.save_temps {
1263ensure_removed(sess.dcx(), &metadata_object);
1264ensure_removed(sess.dcx(), &symbols_object);
1265 }
1266 });
12671268let (mut cmd, jobserver_tokens) = linker_with_args(
1269&linker_path,
1270flavor,
1271sess,
1272archive_builder_builder,
1273rmeta_link_cache,
1274crate_type,
1275tmpdir,
1276&metadata_object,
1277&symbols_object,
1278temp_filename,
1279compiled_modules,
1280crate_info,
1281metadata,
1282self_contained_components,
1283codegen_backend,
1284 );
12851286 linker::disable_localization(&mut cmd);
12871288for (k, v) in sess.target.link_env.as_ref() {
1289 cmd.env(k.as_ref(), v.as_ref());
1290 }
1291for k in sess.target.link_env_remove.as_ref() {
1292 cmd.env_remove(k.as_ref());
1293 }
12941295for print in &sess.opts.prints {
1296if print.kind == PrintKind::LinkArgs {
1297let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
1298 print.out.overwrite(&content, sess);
1299 }
1300 }
13011302// May have not found libraries in the right formats.
1303sess.dcx().abort_if_errors();
13041305// Invoke the system linker
1306{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1306",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1306u32),
::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:?}");
1307let unknown_arg_regex =
1308Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
1309let mut prog;
1310loop {
1311prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
1312let Ok(ref output) = progelse {
1313break;
1314 };
1315if output.status.success() {
1316break;
1317 }
1318let mut out = output.stderr.clone();
1319out.extend(&output.stdout);
1320let out = String::from_utf8_lossy(&out);
13211322// Check to see if the link failed with an error message that indicates it
1323 // doesn't recognize the -no-pie option. If so, re-perform the link step
1324 // without it. This is safe because if the linker doesn't support -no-pie
1325 // then it should not default to linking executables as pie. Different
1326 // versions of gcc seem to use different quotes in the error message so
1327 // don't check for them.
1328if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1329 && unknown_arg_regex.is_match(&out)
1330 && out.contains("-no-pie")
1331 && cmd.get_args().iter().any(|e| e == "-no-pie")
1332 {
1333{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1333",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1333u32),
::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);
1334{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1334",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1334u32),
::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.");
1335for arg in cmd.take_args() {
1336if arg != "-no-pie" {
1337 cmd.arg(arg);
1338 }
1339 }
1340{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1340",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1340u32),
::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:?}");
1341continue;
1342 }
13431344// Check if linking failed with an error message that indicates the driver didn't recognize
1345 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1346 // to spawn multiple instances on the happy path to do version checking, and ensures things
1347 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1348 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1349if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1350 && unknown_arg_regex.is_match(&out)
1351 && out.contains("-fuse-ld=lld")
1352 && cmd.get_args().iter().any(|e| e == "-fuse-ld=lld")
1353 {
1354{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1354",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1354u32),
::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);
1355{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1355",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1355u32),
::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.");
1356for arg in cmd.take_args() {
1357if arg != "-fuse-ld=lld" {
1358 cmd.arg(arg);
1359 }
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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/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!("{0:?}",
cmd) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{cmd:?}");
1362continue;
1363 }
13641365// Check if linking failed with an error message that the linker doesn't recognise the
1366 // cortex-a53 mitigation. We pass `-mfix-cortex-a53-843419` to CC-based linker drivers,
1367 // which forward `--fix-cortex-a53-843419` to the linker itself, but either component may
1368 // not recognise each flag. Notably this was only added to Clang in version 21.
1369if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1370 && unknown_arg_regex.is_match(&out)
1371 && out.contains("fix-cortex-a53-843419")
1372 && cmd.get_args().iter().any(|e| e == "-mfix-cortex-a53-843419")
1373 {
1374{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1374",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1374u32),
::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);
1375{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1375",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1375u32),
::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!(
1376"The linker or linker driver do not support `fix-cortex-a53-843419`. Retrying without it."
1377);
1378for arg in cmd.take_args() {
1379if arg != "-mfix-cortex-a53-843419" {
1380 cmd.arg(arg);
1381 }
1382 }
1383{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1383",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1383u32),
::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:?}");
1384continue;
1385 }
13861387// Detect '-static-pie' used with an older version of gcc or clang not supporting it,
1388 // or with glibc that's missing crt objects, e.g. for arches that don't support it.
1389 // Fallback from '-static-pie' to '-static' in either case.
1390let mut static_pie_message = None;
1391if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1392 && cmd.get_args().iter().any(|e| e == "-static-pie")
1393 {
1394if unknown_arg_regex.is_match(&out)
1395 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1396 {
1397static_pie_message =
1398Some("Linker does not support -static-pie command line option.");
1399 } else if Regex::new(r"cannot (find|open) g?rcrt1\.o:").unwrap().is_match(&out) {
1400static_pie_message = Some("C library is missing static-PIE startup objects.");
1401 }
1402 }
1403if let Some(message) = static_pie_message {
1404{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1404",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1404u32),
::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);
1405{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1405",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1405u32),
::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.");
1406// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1407let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1408let opts = &sess.target;
1409let pre_objects = if self_contained_crt_objects {
1410&opts.pre_link_objects_self_contained
1411 } else {
1412&opts.pre_link_objects
1413 };
1414let post_objects = if self_contained_crt_objects {
1415&opts.post_link_objects_self_contained
1416 } else {
1417&opts.post_link_objects
1418 };
1419let get_objects = |objects: &CrtObjects, kind| {
1420objects1421 .get(&kind)
1422 .into_flat_iter()
1423 .map(|obj| {
1424get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1425 })
1426 .collect::<Vec<_>>()
1427 };
1428let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1429let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1430let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1431let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1432// Assume that we know insertion positions for the replacement arguments from replaced
1433 // arguments, which is true for all supported targets.
1434if !(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());
1435if !(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());
1436for arg in cmd.take_args() {
1437if arg == "-static-pie" {
1438// Replace the output kind.
1439cmd.arg("-static");
1440 } else if pre_objects_static_pie.contains(&arg) {
1441// Replace the pre-link objects (replace the first and remove the rest).
1442cmd.args(mem::take(&mut pre_objects_static));
1443 } else if post_objects_static_pie.contains(&arg) {
1444// Replace the post-link objects (replace the first and remove the rest).
1445cmd.args(mem::take(&mut post_objects_static));
1446 } else {
1447 cmd.arg(arg);
1448 }
1449 }
1450{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1450",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1450u32),
::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:?}");
1451continue;
1452 }
14531454break;
1455 }
14561457// Finished running linker, release the tokens.
1458drop(jobserver_tokens);
14591460match prog {
1461Ok(prog) => {
1462if !prog.status.success() {
1463let mut output = prog.stderr.clone();
1464output.extend_from_slice(&prog.stdout);
1465let escaped_output = escape_linker_output(&output, flavor);
1466let err = diagnostics::LinkingFailed {
1467 linker_path: &linker_path,
1468 exit_status: prog.status,
1469 command: cmd,
1470escaped_output,
1471 verbose: sess.opts.verbose,
1472 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1473 };
1474sess.dcx().emit_err(err);
1475// If MSVC's `link.exe` was expected but the return code
1476 // is not a Microsoft LNK error then suggest a way to fix or
1477 // install the Visual Studio build tools.
1478if let Some(code) = prog.status.code() {
1479// All Microsoft `link.exe` linking ror codes are
1480 // four digit numbers in the range 1000 to 9999 inclusive
1481if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1482let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1483let has_linker =
1484 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1485 .is_some();
14861487sess.dcx().emit_note(diagnostics::LinkExeUnexpectedError);
14881489// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1490 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1491const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1492if code == STATUS_STACK_BUFFER_OVERRUN {
1493sess.dcx().emit_note(diagnostics::LinkExeStatusStackBufferOverrun);
1494 }
14951496if is_vs_installed && has_linker {
1497// the linker is broken
1498sess.dcx().emit_note(diagnostics::RepairVSBuildTools);
1499sess.dcx().emit_note(diagnostics::MissingCppBuildToolComponent);
1500 } else if is_vs_installed {
1501// the linker is not installed
1502sess.dcx().emit_note(diagnostics::SelectCppBuildToolWorkload);
1503 } else {
1504// visual studio is not installed
1505sess.dcx().emit_note(diagnostics::VisualStudioNotInstalled);
1506 }
1507 }
1508 }
15091510sess.dcx().abort_if_errors();
1511 }
15121513{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:1513",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1513u32),
::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:?}");
1514report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1515 }
1516Err(e) => {
1517let linker_not_found = e.kind() == io::ErrorKind::NotFound;
15181519let err = if linker_not_found {
1520sess.dcx().emit_err(diagnostics::LinkerNotFound { linker_path, error: e })
1521 } else {
1522sess.dcx().emit_err(diagnostics::UnableToExeLinker {
1523linker_path,
1524 error: e,
1525 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1526 })
1527 };
15281529if sess.target.is_like_msvc && linker_not_found {
1530sess.dcx().emit_note(diagnostics::MsvcMissingLinker);
1531sess.dcx().emit_note(diagnostics::CheckInstalledVisualStudio);
1532sess.dcx().emit_note(diagnostics::InsufficientVSCodeProduct);
1533 }
1534err.raise_fatal();
1535 }
1536 }
15371538match sess.split_debuginfo() {
1539// If split debug information is disabled or located in individual files
1540 // there's nothing to do here.
1541SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
15421543// If packed split-debuginfo is requested, but the final compilation
1544 // doesn't actually have any debug information, then we skip this step.
1545SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
15461547// On macOS the external `dsymutil` tool is used to create the packed
1548 // debug information. Note that this will read debug information from
1549 // the objects on the filesystem which we'll clean up later.
1550SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1551let prog = Command::new("dsymutil").arg(out_filename).output();
1552match prog {
1553Ok(prog) => {
1554if !prog.status.success() {
1555let mut output = prog.stderr.clone();
1556output.extend_from_slice(&prog.stdout);
1557sess.dcx().emit_warn(diagnostics::ProcessingDymutilFailed {
1558 status: prog.status,
1559 output: escape_string(&output),
1560 });
1561 }
1562 }
1563Err(error) => sess.dcx().emit_fatal(diagnostics::UnableToRunDsymutil { error }),
1564 }
1565 }
15661567// On MSVC packed debug information is produced by the linker itself so
1568 // there's no need to do anything else here.
1569SplitDebuginfo::Packedif sess.target.is_like_windows => {}
15701571// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1572 //
1573 // We cannot rely on the .o paths in the executable because they may have been
1574 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1575 // the .o/.dwo paths explicitly.
1576SplitDebuginfo::Packed => {
1577link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1578 }
1579 }
15801581let strip = sess.opts.cg.strip;
15821583if sess.target.is_like_darwin {
1584let stripcmd = "rust-objcopy";
1585match (strip, crate_type) {
1586 (Strip::Debuginfo, _) => {
1587strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1588 }
15891590// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1591(
1592 Strip::Symbols,
1593 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1594 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1595 (Strip::Symbols, _) => {
1596strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1597 }
1598 (Strip::None, _) => {}
1599 }
1600 }
16011602if sess.target.is_like_solaris {
1603// Many illumos systems will have both the native 'strip' utility and
1604 // the GNU one. Use the native version explicitly and do not rely on
1605 // what's in the path.
1606 //
1607 // If cross-compiling and there is not a native version, then use
1608 // `llvm-strip` and hope.
1609let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1610match strip {
1611// Always preserve the symbol table (-x).
1612Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1613// Strip::Symbols is handled via the --strip-all linker option.
1614Strip::Symbols => {}
1615 Strip::None => {}
1616 }
1617 }
16181619if sess.target.is_like_aix {
1620// `llvm-strip` doesn't work for AIX - their strip must be used.
1621if !sess.host.is_like_aix {
1622sess.dcx().emit_warn(diagnostics::AixStripNotUsed);
1623 }
1624let stripcmd = "/usr/bin/strip";
1625match strip {
1626 Strip::Debuginfo => {
1627// FIXME: AIX's strip utility only offers option to strip line number information.
1628strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1629 }
1630 Strip::Symbols => {
1631// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1632strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1633 }
1634 Strip::None => {}
1635 }
1636 }
16371638if should_archive {
1639let mut ab = archive_builder_builder.new_archive_builder(sess);
1640ab.add_file(temp_filename, ArchiveEntryKind::Other);
1641ab.build(out_filename, None);
1642 }
1643}
16441645fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1646let mut cmd = Command::new(util);
1647cmd.args(options);
16481649let mut new_path = sess.get_tools_search_paths(false);
1650if let Some(path) = env::var_os("PATH") {
1651new_path.extend(env::split_paths(&path));
1652 }
1653cmd.env("PATH", env::join_paths(new_path).unwrap());
16541655let prog = cmd.arg(out_filename).output();
1656match prog {
1657Ok(prog) => {
1658if !prog.status.success() {
1659let mut output = prog.stderr.clone();
1660output.extend_from_slice(&prog.stdout);
1661sess.dcx().emit_warn(diagnostics::StrippingDebugInfoFailed {
1662util,
1663 status: prog.status,
1664 output: escape_string(&output),
1665 });
1666 }
1667 }
1668Err(error) => sess.dcx().emit_fatal(diagnostics::UnableToRun { util, error }),
1669 }
1670}
16711672fn escape_string(s: &[u8]) -> String {
1673match str::from_utf8(s) {
1674Ok(s) => s.to_owned(),
1675Err(_) => ::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()),
1676 }
1677}
16781679#[cfg(not(windows))]
1680fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1681escape_string(s)
1682}
16831684/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1685/// then try to convert the string from the OEM encoding.
1686#[cfg(windows)]
1687fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1688// This only applies to the actual MSVC linker.
1689if flavour != LinkerFlavor::Msvc(Lld::No) {
1690return escape_string(s);
1691 }
1692match str::from_utf8(s) {
1693Ok(s) => return s.to_owned(),
1694Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1695Some(s) => s,
1696// The string is not UTF-8 and isn't valid for the OEM code page
1697None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1698 },
1699 }
1700}
17011702/// Wrappers around the Windows API.
1703#[cfg(windows)]
1704mod win {
1705use windows::Win32::Globalization::{
1706 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1707 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1708 };
17091710/// Get the Windows system OEM code page. This is most notably the code page
1711 /// used for link.exe's output.
1712pub(super) fn oem_code_page() -> u32 {
1713unsafe {
1714let mut cp: u32 = 0;
1715// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1716 // But the API requires us to pass the data as though it's a [u16] string.
1717let len = size_of::<u32>() / size_of::<u16>();
1718let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1719let len_written = GetLocaleInfoEx(
1720 LOCALE_NAME_SYSTEM_DEFAULT,
1721 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1722Some(data),
1723 );
1724if len_written as usize == len { cp } else { CP_OEMCP }
1725 }
1726 }
1727/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1728 /// The string does not need to be null terminated.
1729 ///
1730 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1731 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1732 ///
1733 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1734 /// any invalid bytes for the expected encoding.
1735pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1736// `MultiByteToWideChar` requires a length to be a "positive integer".
1737if s.len() > isize::MAX as usize {
1738return None;
1739 }
1740// Error if the string is not valid for the expected code page.
1741let flags = MB_ERR_INVALID_CHARS;
1742// Call MultiByteToWideChar twice.
1743 // First to calculate the length then to convert the string.
1744let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1745if len > 0 {
1746let mut utf16 = vec![0; len as usize];
1747 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1748if len > 0 {
1749return utf16.get(..len as usize).map(String::from_utf16_lossy);
1750 }
1751 }
1752None
1753}
1754}
17551756fn add_sanitizer_libraries(
1757 sess: &Session,
1758 flavor: LinkerFlavor,
1759 crate_type: CrateType,
1760 linker: &mut dyn Linker,
1761) {
1762if sess.target.is_like_android {
1763// Sanitizer runtime libraries are provided dynamically on Android
1764 // targets.
1765return;
1766 }
17671768if sess.opts.unstable_opts.external_clangrt {
1769// Linking against in-tree sanitizer runtimes is disabled via
1770 // `-Z external-clangrt`
1771return;
1772 }
17731774if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1775return;
1776 }
17771778// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1779 // which should be linked to both executables and dynamic libraries.
1780 // Everywhere else the runtimes are currently distributed as static
1781 // libraries which should be linked to executables only.
1782if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1783 crate_type,
1784 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1785 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1786 {
1787return;
1788 }
17891790let sanitizer = sess.sanitizers();
1791if sanitizer.contains(SanitizerSet::ADDRESS) {
1792link_sanitizer_runtime(sess, flavor, linker, "asan");
1793 }
1794if sanitizer.contains(SanitizerSet::DATAFLOW) {
1795link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1796 }
1797if sanitizer.contains(SanitizerSet::LEAK)
1798 && !sanitizer.contains(SanitizerSet::ADDRESS)
1799 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1800 {
1801link_sanitizer_runtime(sess, flavor, linker, "lsan");
1802 }
1803if sanitizer.contains(SanitizerSet::MEMORY) {
1804link_sanitizer_runtime(sess, flavor, linker, "msan");
1805 }
1806if sanitizer.contains(SanitizerSet::THREAD) {
1807link_sanitizer_runtime(sess, flavor, linker, "tsan");
1808 }
1809if sanitizer.contains(SanitizerSet::HWADDRESS) {
1810link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1811 }
1812if sanitizer.contains(SanitizerSet::SAFESTACK) {
1813link_sanitizer_runtime(sess, flavor, linker, "safestack");
1814 }
1815if sanitizer.contains(SanitizerSet::REALTIME) {
1816link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1817 }
1818if sanitizer.contains(SanitizerSet::CFI)
1819 && (sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false)
1820 || sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false))
1821 {
1822if sess.is_sanitizer_cfi_minimal_runtime_enabled() {
1823link_sanitizer_runtime(sess, flavor, linker, "ubsan_minimal");
1824 } else {
1825link_sanitizer_runtime(sess, flavor, linker, "ubsan");
1826 }
1827 }
1828}
18291830fn link_sanitizer_runtime(
1831 sess: &Session,
1832 flavor: LinkerFlavor,
1833 linker: &mut dyn Linker,
1834 name: &str,
1835) {
1836fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1837let path = sess.target_tlib_path.dir.join(filename);
1838if path.exists() {
1839sess.target_tlib_path.dir.to_path_buf()
1840 } else {
1841 filesearch::make_target_lib_path(
1842&sess.opts.sysroot.default,
1843sess.opts.target_triple.tuple(),
1844 )
1845 }
1846 }
18471848let channel =
1849::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();
18501851if sess.target.is_like_darwin {
1852// On Apple platforms, the sanitizer is always built as a dylib, and
1853 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1854 // rpath to the library as well (the rpath should be absolute, see
1855 // PR #41352 for details).
1856let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1857let path = find_sanitizer_runtime(sess, &filename);
1858let rpath = path.to_str().expect("non-utf8 component in path");
1859linker.link_args(&["-rpath", rpath]);
1860linker.link_dylib_by_name(&filename, false, true);
1861 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1862// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1863 // compatible ASAN library.
1864linker.link_arg("/INFERASANLIBS");
1865 } else {
1866let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1867let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1868linker.link_staticlib_by_path(&path, true);
1869 }
1870}
18711872/// Returns a boolean indicating whether the specified crate should be ignored
1873/// during LTO.
1874///
1875/// Crates ignored during LTO are not lumped together in the "massive object
1876/// file" that we create and are linked in their normal rlib states. See
1877/// comments below for what crates do not participate in LTO.
1878///
1879/// It's unusual for a crate to not participate in LTO. Typically only
1880/// compiler-specific and unstable crates have a reason to not participate in
1881/// LTO.
1882pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1883// If our target enables builtin function lowering in LLVM then the
1884 // crates providing these functions don't participate in LTO (e.g.
1885 // no_builtins or compiler builtins crates).
1886!sess.target.no_builtins
1887 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1888}
18891890/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1891pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1892fn infer_from(
1893 sess: &Session,
1894 linker: Option<PathBuf>,
1895 flavor: Option<LinkerFlavor>,
1896 features: LinkerFeaturesCli,
1897 ) -> Option<(PathBuf, LinkerFlavor)> {
1898let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1899match (linker, flavor) {
1900 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1901// only the linker flavor is known; use the default linker for the selected flavor
1902(None, Some(flavor)) => Some((
1903PathBuf::from(match flavor {
1904 LinkerFlavor::Gnu(Cc::Yes, _)
1905 | LinkerFlavor::Darwin(Cc::Yes, _)
1906 | LinkerFlavor::WasmLld(Cc::Yes)
1907 | LinkerFlavor::Unix(Cc::Yes) => {
1908if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1909// On historical Solaris systems, "cc" may have
1910 // been Sun Studio, which is not flag-compatible
1911 // with "gcc". This history casts a long shadow,
1912 // and many modern illumos distributions today
1913 // ship GCC as "gcc" without also making it
1914 // available as "cc".
1915"gcc"
1916} else {
1917"cc"
1918}
1919 }
1920 LinkerFlavor::Gnu(_, Lld::Yes)
1921 | LinkerFlavor::Darwin(_, Lld::Yes)
1922 | LinkerFlavor::WasmLld(..)
1923 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1924 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1925"ld"
1926}
1927 LinkerFlavor::Msvc(..) => "link.exe",
1928 LinkerFlavor::EmCc => {
1929if falsecfg!(windows) {
1930"emcc.bat"
1931} else {
1932"emcc"
1933}
1934 }
1935 LinkerFlavor::Bpf => "bpf-linker",
1936 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1937 }),
1938flavor,
1939 )),
1940 (Some(linker), None) => {
1941let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1942sess.dcx().emit_fatal(diagnostics::LinkerFileStem);
1943 });
1944let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1945let flavor = adjust_flavor_to_features(flavor, features);
1946Some((linker, flavor))
1947 }
1948 (None, None) => None,
1949 }
1950 }
19511952// While linker flavors and linker features are isomorphic (and thus targets don't need to
1953 // define features separately), we use the flavor as the root piece of data and have the
1954 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1955 // both yet.
1956fn adjust_flavor_to_features(
1957 flavor: LinkerFlavor,
1958 features: LinkerFeaturesCli,
1959 ) -> LinkerFlavor {
1960// Note: a linker feature cannot be both enabled and disabled on the CLI.
1961if features.enabled.contains(LinkerFeatures::LLD) {
1962flavor.with_lld_enabled()
1963 } else if features.disabled.contains(LinkerFeatures::LLD) {
1964flavor.with_lld_disabled()
1965 } else {
1966flavor1967 }
1968 }
19691970let features = sess.opts.cg.linker_features;
19711972// linker and linker flavor specified via command line have precedence over what the target
1973 // specification specifies
1974let linker_flavor = match sess.opts.cg.linker_flavor {
1975// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1976Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1977// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1978linker_flavor => {
1979linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1980 }
1981 };
1982if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1983return ret;
1984 }
19851986if let Some(ret) = infer_from(
1987sess,
1988sess.target.linker.as_deref().map(PathBuf::from),
1989Some(sess.target.linker_flavor),
1990features,
1991 ) {
1992return ret;
1993 }
19941995::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");
1996}
19971998/// Returns a pair of boolean indicating whether we should preserve the object and
1999/// dwarf object files on the filesystem for their debug information. This is often
2000/// useful with split-dwarf like schemes.
2001fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
2002// If the objects don't have debuginfo there's nothing to preserve.
2003if sess.opts.debuginfo == config::DebugInfo::None {
2004return (false, false);
2005 }
20062007match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
2008// If there is no split debuginfo then do not preserve objects.
2009(SplitDebuginfo::Off, _) => (false, false),
2010// If there is packed split debuginfo, then the debuginfo in the objects
2011 // has been packaged and the objects can be deleted.
2012(SplitDebuginfo::Packed, _) => (false, false),
2013// If there is unpacked split debuginfo and the current target can not use
2014 // split dwarf, then keep objects.
2015(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
2016// If there is unpacked split debuginfo and the target can use split dwarf, then
2017 // keep the object containing that debuginfo (whether that is an object file or
2018 // dwarf object file depends on the split dwarf kind).
2019(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
2020 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
2021 }
2022}
20232024#[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)]
2025enum RlibFlavor {
2026 Normal,
2027 StaticlibBase,
2028}
20292030fn print_native_static_libs(
2031 sess: &Session,
2032 out: &OutFileName,
2033 all_native_libs: &[NativeLib],
2034 all_rust_dylibs: &[&Path],
2035) {
2036let mut lib_args: Vec<_> = all_native_libs2037 .iter()
2038 .filter(|l| relevant_lib(sess, l))
2039 .filter_map(|lib| {
2040let name = lib.name;
2041match lib.kind {
2042 NativeLibKind::Static { bundle: Some(false), .. }
2043 | NativeLibKind::Dylib { .. }
2044 | NativeLibKind::Unspecified => {
2045let verbatim = lib.verbatim;
2046if sess.target.is_like_msvc {
2047let (prefix, suffix) = sess.staticlib_components(verbatim);
2048Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
2049 } else if sess.target.linker_flavor.is_gnu() {
2050Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
2051 } else {
2052Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
2053 }
2054 }
2055 NativeLibKind::Framework { .. } => {
2056// ld-only syntax, since there are no frameworks in MSVC
2057Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
2058 }
2059// These are included, no need to print them
2060NativeLibKind::Static { bundle: None | Some(true), .. }
2061 | NativeLibKind::LinkArg2062 | NativeLibKind::WasmImportModule2063 | NativeLibKind::RawDylib { .. } => None,
2064 }
2065 })
2066// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
2067.dedup()
2068 .collect();
2069for path in all_rust_dylibs {
2070// FIXME deduplicate with add_dynamic_crate
20712072 // Just need to tell the linker about where the library lives and
2073 // what its name is
2074let parent = path.parent();
2075if let Some(dir) = parent {
2076let dir = fix_windows_verbatim_for_gcc(dir);
2077if sess.target.is_like_msvc {
2078let mut arg = String::from("/LIBPATH:");
2079 arg.push_str(&dir.display().to_string());
2080 lib_args.push(arg);
2081 } else {
2082 lib_args.push("-L".to_owned());
2083 lib_args.push(dir.display().to_string());
2084 }
2085 }
2086let stem = path.file_stem().unwrap().to_str().unwrap();
2087// Convert library file-stem into a cc -l argument.
2088let lib = if let Some(lib) = stem.strip_prefix("lib")
2089 && !sess.target.is_like_windows
2090 {
2091 lib
2092 } else {
2093 stem
2094 };
2095let path = parent.unwrap_or_else(|| Path::new(""));
2096if sess.target.is_like_msvc {
2097// When producing a dll, the MSVC linker may not actually emit a
2098 // `foo.lib` file if the dll doesn't actually export any symbols, so we
2099 // check to see if the file is there and just omit linking to it if it's
2100 // not present.
2101let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
2102if path.join(&name).exists() {
2103 lib_args.push(name);
2104 }
2105 } else {
2106 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
2107 }
2108 }
21092110match out {
2111 OutFileName::Real(path) => {
2112out.overwrite(&lib_args.join(" "), sess);
2113sess.dcx().emit_note(diagnostics::StaticLibraryNativeArtifactsToFile { path });
2114 }
2115 OutFileName::Stdout => {
2116sess.dcx().emit_note(diagnostics::StaticLibraryNativeArtifacts);
2117// Prefix for greppability
2118 // Note: This must not be translated as tools are allowed to depend on this exact string.
2119sess.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(" ")));
2120 }
2121 }
2122}
21232124fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
2125let file_path = sess.target_tlib_path.dir.join(name);
2126if file_path.exists() {
2127return file_path;
2128 }
2129// Special directory with objects used only in self-contained linkage mode
2130if self_contained {
2131let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
2132if file_path.exists() {
2133return file_path;
2134 }
2135 }
21362137// Note: this is O(n^2), it could be expensive-ish if we lookup many object files for many
2138 // search paths
2139for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
2140let file_path = search_path.dir.join(name);
2141if file_path.exists() {
2142return file_path;
2143 }
2144 }
2145PathBuf::from(name)
2146}
21472148fn exec_linker(
2149 sess: &Session,
2150 cmd: &Command,
2151 out_filename: &Path,
2152 flavor: LinkerFlavor,
2153 tmpdir: &Path,
2154) -> io::Result<Output> {
2155// When attempting to spawn the linker we run a risk of blowing out the
2156 // size limits for spawning a new process with respect to the arguments
2157 // we pass on the command line.
2158 //
2159 // Here we attempt to handle errors from the OS saying "your list of
2160 // arguments is too big" by reinvoking the linker again with an `@`-file
2161 // that contains all the arguments (aka 'response' files).
2162 // The theory is that this is then accepted on all linkers and the linker
2163 // will read all its options out of there instead of looking at the command line.
2164if !cmd.very_likely_to_exceed_some_spawn_limit() {
2165match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
2166Ok(child) => {
2167let output = child.wait_with_output();
2168 flush_linked_file(&output, out_filename)?;
2169return output;
2170 }
2171Err(ref e) if command_line_too_big(e) => {
2172{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:2172",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2172u32),
::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);
2173 }
2174Err(e) => return Err(e),
2175 }
2176 }
21772178{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:2178",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2178u32),
::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");
2179let mut cmd2 = cmd.clone();
2180let mut args = String::new();
2181for arg in cmd2.take_args() {
2182 args.push_str(
2183&Escape {
2184 arg: arg.to_str().unwrap(),
2185// Windows-style escaping for @-files is used by
2186 // - all linkers targeting MSVC-like targets, including LLD
2187 // - all LLD flavors running on Windows hosts
2188 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
2189is_like_msvc: sess.target.is_like_msvc
2190 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
2191 }
2192 .to_string(),
2193 );
2194 args.push('\n');
2195 }
2196let file = tmpdir.join("linker-arguments");
2197let bytes = if sess.target.is_like_msvc {
2198let mut out = Vec::with_capacity((1 + args.len()) * 2);
2199// start the stream with a UTF-16 BOM
2200for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
2201// encode in little endian
2202out.push(c as u8);
2203 out.push((c >> 8) as u8);
2204 }
2205out2206 } else {
2207args.into_bytes()
2208 };
2209 fs::write(&file, &bytes)?;
2210cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
2211{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:2211",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(2211u32),
::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);
2212let output = cmd2.output();
2213 flush_linked_file(&output, out_filename)?;
2214return output;
22152216#[cfg(not(windows))]
2217fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
2218Ok(())
2219 }
22202221#[cfg(windows)]
2222fn flush_linked_file(
2223 command_output: &io::Result<Output>,
2224 out_filename: &Path,
2225 ) -> io::Result<()> {
2226// On Windows, under high I/O load, output buffers are sometimes not flushed,
2227 // even long after process exit, causing nasty, non-reproducible output bugs.
2228 //
2229 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
2230 //
2231 // А full writeup of the original Chrome bug can be found at
2232 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
22332234if let &Ok(ref out) = command_output {
2235if out.status.success() {
2236if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
2237 of.sync_all()?;
2238 }
2239 }
2240 }
22412242Ok(())
2243 }
22442245#[cfg(unix)]
2246fn command_line_too_big(err: &io::Error) -> bool {
2247err.raw_os_error() == Some(::libc::E2BIG)
2248 }
22492250#[cfg(windows)]
2251fn command_line_too_big(err: &io::Error) -> bool {
2252const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
2253 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
2254 }
22552256#[cfg(not(any(unix, windows)))]
2257fn command_line_too_big(_: &io::Error) -> bool {
2258false
2259}
22602261struct Escape<'a> {
2262 arg: &'a str,
2263 is_like_msvc: bool,
2264 }
22652266impl<'a> fmt::Displayfor Escape<'a> {
2267fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2268if self.is_like_msvc {
2269// This is "documented" at
2270 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
2271 //
2272 // Unfortunately there's not a great specification of the
2273 // syntax I could find online (at least) but some local
2274 // testing showed that this seemed sufficient-ish to catch
2275 // at least a few edge cases.
2276f.write_fmt(format_args!("\""))write!(f, "\"")?;
2277for c in self.arg.chars() {
2278match c {
2279'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
2280 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
2281 }
2282 }
2283f.write_fmt(format_args!("\""))write!(f, "\"")?;
2284 } else {
2285// This is documented at https://linux.die.net/man/1/ld, namely:
2286 //
2287 // > Options in file are separated by whitespace. A whitespace
2288 // > character may be included in an option by surrounding the
2289 // > entire option in either single or double quotes. Any
2290 // > character (including a backslash) may be included by
2291 // > prefixing the character to be included with a backslash.
2292 //
2293 // We put an argument on each line, so all we need to do is
2294 // ensure the line is interpreted as one whole argument.
2295for c in self.arg.chars() {
2296match c {
2297'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
2298 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
2299 }
2300 }
2301 }
2302Ok(())
2303 }
2304 }
2305}
23062307fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
2308let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
2309 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
2310 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
2311 LinkOutputKind::DynamicPicExe2312 }
2313 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
2314 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
2315 LinkOutputKind::StaticPicExe2316 }
2317 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
2318 (_, true, _) => LinkOutputKind::StaticDylib,
2319 (_, false, _) => LinkOutputKind::DynamicDylib,
2320 };
23212322// Adjust the output kind to target capabilities.
2323let opts = &sess.target;
2324let pic_exe_supported = opts.position_independent_executables;
2325let static_pic_exe_supported = opts.static_position_independent_executables;
2326let static_dylib_supported = opts.crt_static_allows_dylibs;
2327match kind {
2328 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
2329 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
2330 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
2331_ => kind,
2332 }
2333}
23342335// Returns true if linker is located within sysroot
2336fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
2337let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
2338linker.with_extension("exe")
2339 } else {
2340linker.to_path_buf()
2341 };
2342for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
2343let full_path = dir.join(&linker_with_extension);
2344// If linker comes from sysroot assume self-contained mode
2345if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
2346return false;
2347 }
2348 }
2349true
2350}
23512352/// Various toolchain components used during linking are used from rustc distribution
2353/// instead of being found somewhere on the host system.
2354/// We only provide such support for a very limited number of targets.
2355fn self_contained_components(
2356 sess: &Session,
2357 crate_type: CrateType,
2358 linker: &Path,
2359) -> LinkSelfContainedComponents {
2360// Turn the backwards compatible bool values for `self_contained` into fully inferred
2361 // `LinkSelfContainedComponents`.
2362let self_contained =
2363if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
2364// Emit an error if the user requested self-contained mode on the CLI but the target
2365 // explicitly refuses it.
2366if sess.target.link_self_contained.is_disabled() {
2367sess.dcx().emit_err(diagnostics::UnsupportedLinkSelfContained);
2368 }
2369self_contained2370 } else {
2371match sess.target.link_self_contained {
2372 LinkSelfContainedDefault::False => false,
2373 LinkSelfContainedDefault::True => true,
23742375 LinkSelfContainedDefault::WithComponents(components) => {
2376// For target specs with explicitly enabled components, we can return them
2377 // directly.
2378return components;
2379 }
23802381// FIXME: Find a better heuristic for "native musl toolchain is available",
2382 // based on host and linker path, for example.
2383 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2384LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2385 LinkSelfContainedDefault::InferredForMingw => {
2386sess.host == sess.target
2387 && sess.target.cfg_abi != CfgAbi::Uwp2388 && detect_self_contained_mingw(sess, linker)
2389 }
2390 }
2391 };
2392if self_contained {
2393LinkSelfContainedComponents::all()
2394 } else {
2395LinkSelfContainedComponents::empty()
2396 }
2397}
23982399/// Add pre-link object files defined by the target spec.
2400fn add_pre_link_objects(
2401 cmd: &mut dyn Linker,
2402 sess: &Session,
2403 flavor: LinkerFlavor,
2404 link_output_kind: LinkOutputKind,
2405 self_contained: bool,
2406) {
2407// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2408 // so Fuchsia has to be special-cased.
2409let opts = &sess.target;
2410let empty = Default::default();
2411let objects = if self_contained {
2412&opts.pre_link_objects_self_contained
2413 } 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, _))) {
2414&opts.pre_link_objects
2415 } else {
2416&empty2417 };
2418for obj in objects.get(&link_output_kind).into_flat_iter() {
2419 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2420 }
2421}
24222423/// Add post-link object files defined by the target spec.
2424fn add_post_link_objects(
2425 cmd: &mut dyn Linker,
2426 sess: &Session,
2427 link_output_kind: LinkOutputKind,
2428 self_contained: bool,
2429) {
2430let objects = if self_contained {
2431&sess.target.post_link_objects_self_contained
2432 } else {
2433&sess.target.post_link_objects
2434 };
2435for obj in objects.get(&link_output_kind).into_flat_iter() {
2436 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2437 }
2438}
24392440/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2441/// FIXME: Determine where exactly these args need to be inserted.
2442fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2443// Emit the CC flag for the A53 mitigation early, as later linker args can override it if
2444 // required with `-mno-fix-cortex-a53-843419`
2445if sess.target.arch == Arch::AArch642446 && !sess.target.is_like_darwin
2447 && sess.target.os != Os::Windows2448 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, ..) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, ..))2449 {
2450cmd.cc_arg("-mfix-cortex-a53-843419");
2451 }
24522453if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2454cmd.verbatim_args(args.iter().map(Deref::deref));
2455 }
24562457cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2458}
24592460/// Add a link script embedded in the target, if applicable.
2461fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2462match (crate_type, &sess.target.link_script) {
2463 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2464if !sess.target.linker_flavor.is_gnu() {
2465sess.dcx().emit_fatal(diagnostics::LinkScriptUnavailable);
2466 }
24672468let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
24692470let path = tmpdir.join(file_name);
2471if let Err(error) = fs::write(&path, script.as_ref()) {
2472sess.dcx().emit_fatal(diagnostics::LinkScriptWriteFailure { path, error });
2473 }
24742475cmd.link_arg("--script").link_arg(path);
2476 }
2477_ => {}
2478 }
2479}
24802481/// Add arbitrary "user defined" args defined from command line.
2482/// FIXME: Determine where exactly these args need to be inserted.
2483fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2484cmd.verbatim_args(&sess.opts.cg.link_args);
2485}
24862487/// Add arbitrary "late link" args defined by the target spec.
2488/// FIXME: Determine where exactly these args need to be inserted.
2489fn add_late_link_args(
2490 cmd: &mut dyn Linker,
2491 sess: &Session,
2492 flavor: LinkerFlavor,
2493 crate_type: CrateType,
2494 crate_info: &CrateInfo,
2495) {
2496let any_dynamic_crate = crate_type == CrateType::Dylib2497 || crate_type == CrateType::Sdylib2498 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2499*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2500 });
2501if any_dynamic_crate {
2502if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2503cmd.verbatim_args(args.iter().map(Deref::deref));
2504 }
2505 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2506cmd.verbatim_args(args.iter().map(Deref::deref));
2507 }
2508if let Some(args) = sess.target.late_link_args.get(&flavor) {
2509cmd.verbatim_args(args.iter().map(Deref::deref));
2510 }
2511}
25122513/// Add arbitrary "post-link" args defined by the target spec.
2514/// FIXME: Determine where exactly these args need to be inserted.
2515fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2516if let Some(args) = sess.target.post_link_args.get(&flavor) {
2517cmd.verbatim_args(args.iter().map(Deref::deref));
2518 }
2519}
25202521/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2522/// the linker.
2523///
2524/// Background: we implement rlibs as static library (archives). Linkers treat archives
2525/// differently from object files: all object files participate in linking, while archives will
2526/// only participate in linking if they can satisfy at least one undefined reference (version
2527/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2528/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2529/// can't keep them either. This causes #47384.
2530///
2531/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2532/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2533/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2534/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2535/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2536/// from removing them, and this is especially problematic for embedded programming where every
2537/// byte counts.
2538///
2539/// This method creates a synthetic object file, which contains undefined references to all symbols
2540/// that are necessary for the linking. They are only present in symbol table but not actually
2541/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2542/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2543///
2544/// There's a few internal crates in the standard library (aka libcore and
2545/// libstd) which actually have a circular dependence upon one another. This
2546/// currently arises through "weak lang items" where libcore requires things
2547/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2548/// circular dependence to work correctly we declare some of these things
2549/// in this synthetic object.
2550fn add_linked_symbol_object(
2551 cmd: &mut dyn Linker,
2552 sess: &Session,
2553 symbols_path: &Path,
2554 crate_type: CrateType,
2555 linked_symbols: &[(String, SymbolExportKind)],
2556 exported_symbols: &[SymbolExport],
2557) {
2558let should_export_symbols = sess.target.is_like_msvc
2559 && !exported_symbols.is_empty()
2560 && (crate_type != CrateType::Executable2561 || sess.opts.unstable_opts.export_executable_symbols);
2562if linked_symbols.is_empty() && !should_export_symbols {
2563return;
2564 }
25652566let Some(mut file) = super::metadata::create_object_file(sess) else {
2567return;
2568 };
25692570if file.format() == object::BinaryFormat::Coff {
2571// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2572 // so add an empty section.
2573file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
25742575// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2576 // default mangler in `object` crate.
2577file.set_mangling(object::write::Mangling::None);
2578 }
25792580if file.format() == object::BinaryFormat::MachO {
2581// Divide up the sections into sub-sections via symbols for dead code stripping.
2582 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2583 // discard on MachO targets.
2584file.set_subsections_via_symbols();
2585 }
25862587// ld64 requires a relocation to load undefined symbols, see below.
2588 // Not strictly needed if linking with lld, but might as well do it there too.
2589let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2590Some(file.add_section(
2591file.segment_name(object::write::StandardSegment::Data).to_vec(),
2592"__data".into(),
2593 object::SectionKind::Data,
2594 ))
2595 } else {
2596None2597 };
25982599for (sym, kind) in linked_symbols.iter() {
2600let symbol = file.add_symbol(object::write::Symbol {
2601 name: sym.clone().into(),
2602 value: 0,
2603 size: 0,
2604 kind: match kind {
2605 SymbolExportKind::Text => object::SymbolKind::Text,
2606 SymbolExportKind::Data => object::SymbolKind::Data,
2607 SymbolExportKind::Tls => object::SymbolKind::Tls,
2608 },
2609 scope: object::SymbolScope::Unknown,
2610 weak: false,
2611 section: object::write::SymbolSection::Undefined,
2612 flags: object::SymbolFlags::None,
2613 });
26142615// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2616 //
2617 // Code-wise, the relevant parts of ld64 are roughly:
2618 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2619 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2620 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2621 //
2622 // 2. Read the archive table of contents (__.SYMDEF file).
2623 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2624 //
2625 // 3. Begin linking by loading "atoms" from input files.
2626 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2627 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2628 //
2629 // a. Directly specified object files (`.o`) are parsed immediately.
2630 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2631 //
2632 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2633 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2634 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2635 //
2636 // - Relocations/fixups are atoms.
2637 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2638 //
2639 // b. Archives are not parsed yet.
2640 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2641 //
2642 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2643 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2644 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2645 //
2646 // All of the steps above are fairly similar to other linkers, except that **it completely
2647 // ignores undefined symbols**.
2648 //
2649 // So to make this trick work on ld64, we need to do something else to load the relevant
2650 // object files. We do this by inserting a relocation (fixup) for each symbol.
2651if let Some(section) = ld64_section_helper {
2652 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2653 .expect("failed adding relocation");
2654 }
2655 }
26562657if should_export_symbols {
2658// Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
2659 // export symbols from a dynamic library. When building a dynamic library,
2660 // however, we're going to want some symbols exported, so this adds a
2661 // `.drectve` section which lists all the symbols using /EXPORT arguments.
2662 //
2663 // The linker will read these arguments from the `.drectve` section and
2664 // export all the symbols from the dynamic library. Note that this is not
2665 // as simple as just exporting all the symbols in the current crate (as
2666 // specified by `codegen.reachable`) but rather we also need to possibly
2667 // export the symbols of upstream crates. Upstream rlibs may be linked
2668 // statically to this dynamic library, in which case they may continue to
2669 // transitively be used and hence need their symbols exported.
2670fn msvc_drectve_export(symbol: &SymbolExport) -> String {
2671let data = if symbol.kind == SymbolExportKind::Data { ",DATA" } else { "" };
26722673if let Some(link_name) = symbol.link_name.as_deref() {
2674// The first name is the decorated symbol used by the import library, while
2675 // EXPORTAS gives the public name written to the DLL export table.
2676::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)2677 } else {
2678::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" /EXPORT:\"{0}\"{1}", symbol.name,
data))
})format!(" /EXPORT:\"{}\"{data}", symbol.name)2679 }
2680 }
26812682let drectve = exported_symbols.iter().map(msvc_drectve_export).collect::<String>();
26832684let section = file.add_section(::alloc::vec::Vec::new()vec![], b".drectve".to_vec(), object::SectionKind::Linker);
2685file.append_section_data(section, drectve.as_bytes(), 1);
2686 }
26872688 fs::write(symbols_path, file.write().unwrap()).unwrap_or_else(|error| {
2689sess.dcx()
2690 .emit_fatal(diagnostics::FailedToWrite { path: symbols_path.to_path_buf(), error })
2691 });
2692cmd.add_object(symbols_path);
2693}
26942695/// Add object files containing code from the current crate.
2696fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2697for m in &compiled_modules.modules {
2698if let Some(obj) = &m.object {
2699 cmd.add_object(obj);
2700 }
2701if let Some(obj) = &m.global_asm_object {
2702 cmd.add_object(obj);
2703 }
2704 }
2705}
27062707/// Add object files for allocator code linked once for the whole crate tree.
2708fn add_local_crate_allocator_objects(
2709 cmd: &mut dyn Linker,
2710 compiled_modules: &CompiledModules,
2711 crate_info: &CrateInfo,
2712 crate_type: CrateType,
2713) {
2714if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2715 && let Some(m) = &compiled_modules.allocator_module
2716 {
2717if let Some(obj) = &m.object {
2718cmd.add_object(obj);
2719 }
2720if let Some(obj) = &m.global_asm_object {
2721cmd.add_object(obj);
2722 }
2723 }
2724}
27252726/// Add object files containing metadata for the current crate.
2727fn add_local_crate_metadata_objects(
2728 cmd: &mut dyn Linker,
2729 sess: &Session,
2730 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2731 crate_type: CrateType,
2732 metadata_path: &Path,
2733 crate_info: &CrateInfo,
2734 metadata: &EncodedMetadata,
2735) {
2736// When linking a dynamic library, we put the metadata into a section of the
2737 // executable. This metadata is in a separate object file from the main
2738 // object file, so we create and link it in here.
2739if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2740let data = archive_builder_builder.create_dylib_metadata_wrapper(
2741sess,
2742&metadata,
2743&crate_info.metadata_symbol,
2744 );
2745 fs::write(metadata_path, data).unwrap_or_else(|error| {
2746sess.dcx()
2747 .emit_fatal(diagnostics::FailedToWrite { path: metadata_path.to_path_buf(), error })
2748 });
2749cmd.add_object(metadata_path);
2750 }
2751}
27522753/// Add sysroot and other globally set directories to the directory search list.
2754fn add_library_search_dirs(
2755 cmd: &mut dyn Linker,
2756 sess: &Session,
2757 self_contained_components: LinkSelfContainedComponents,
2758 apple_sdk_root: Option<&Path>,
2759) {
2760if !sess.opts.unstable_opts.link_native_libraries {
2761return;
2762 }
27632764let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2765let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2766if is_framework {
2767cmd.framework_path(dir);
2768 } else {
2769cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2770 }
2771 ControlFlow::<()>::Continue(())
2772 });
2773}
27742775/// Add options making relocation sections in the produced ELF files read-only
2776/// and suppressing lazy binding.
2777fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2778match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2779 RelroLevel::Full => cmd.full_relro(),
2780 RelroLevel::Partial => cmd.partial_relro(),
2781 RelroLevel::Off => cmd.no_relro(),
2782 RelroLevel::None => {}
2783 }
2784}
27852786/// Add library search paths used at runtime by dynamic linkers.
2787fn add_rpath_args(
2788 cmd: &mut dyn Linker,
2789 sess: &Session,
2790 crate_info: &CrateInfo,
2791 out_filename: &Path,
2792) {
2793if !sess.target.has_rpath {
2794return;
2795 }
27962797// FIXME (#2397): At some point we want to rpath our guesses as to
2798 // where extern libraries might live, based on the
2799 // add_lib_search_paths
2800if sess.opts.cg.rpath {
2801let libs = crate_info2802 .used_crates
2803 .iter()
2804 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2805 .collect::<Vec<_>>();
2806let rpath_config = RPathConfig {
2807 libs: &*libs,
2808 out_filename: out_filename.to_path_buf(),
2809 is_like_darwin: sess.target.is_like_darwin,
2810 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2811 };
2812cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2813 }
2814}
28152816fn undecorate_c_symbol<'a>(
2817 name: &'a str,
2818 sess: &Session,
2819 kind: SymbolExportKind,
2820) -> Option<&'a str> {
2821match sess.target.binary_format {
2822 BinaryFormat::MachO => {
2823// Mach-O: strip the leading underscore that all external symbols have.
2824 // The Darwin linker's export_symbols will add it back.
2825name.strip_prefix('_')
2826 }
2827 BinaryFormat::Coff => {
2828// COFF undecoration is shared with `symbol_edit`'s binary-level matching.
2829match symbol_export::coff_machine_for_arch(&sess.target.arch) {
2830Some(machine) => Some(symbol_export::undecorate_coff_symbol(name, machine, kind)),
2831None => Some(name),
2832 }
2833 }
2834// ELF: no decoration
2835_ => Some(name),
2836 }
2837}
28382839fn add_c_staticlib_symbols(
2840 sess: &Session,
2841 lib: &NativeLib,
2842 out: &mut Vec<SymbolExport>,
2843) -> io::Result<()> {
2844let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
28452846let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
28472848let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2849 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28502851for member in archive.members() {
2852let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28532854let data = member
2855 .data(&*archive_map)
2856 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28572858// clang LTO: raw LLVM bitcode
2859if data.starts_with(b"BC\xc0\xde") {
2860return Err(io::Error::new(
2861 io::ErrorKind::InvalidData,
2862"LLVM bitcode object in C static library (LTO not supported)",
2863 ));
2864 }
28652866let object = object::File::parse(&*data)
2867 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
28682869// gcc / clang ELF / Mach-O LTO
2870if object.sections().any(|s| {
2871 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2872 }) {
2873return Err(io::Error::new(
2874 io::ErrorKind::InvalidData,
2875"LTO object in C static library is not supported",
2876 ));
2877 }
28782879for symbol in object.symbols() {
2880// The `object` crate returns `Dynamic` for ELF/Mach-O global symbols,
2881 // but always returns `Linkage` for COFF external symbols.
2882 // Accept both for COFF (Windows and UEFI).
2883let scope = symbol.scope();
2884if scope != object::SymbolScope::Dynamic
2885 && !(sess.target.binary_format == BinaryFormat::Coff
2886 && scope == object::SymbolScope::Linkage)
2887 {
2888continue;
2889 }
28902891let name = match symbol.name() {
2892Ok(n) => n,
2893Err(_) => continue,
2894 };
28952896let export_kind = match symbol.kind() {
2897 object::SymbolKind::Text => SymbolExportKind::Text,
2898 object::SymbolKind::Data => SymbolExportKind::Data,
2899_ => continue,
2900 };
29012902let Some(undecorated) = undecorate_c_symbol(name, sess, export_kind) else {
2903continue;
2904 };
2905 out.push(SymbolExport::with_link_name(
2906 undecorated.to_string(),
2907 export_kind,
2908 name.to_string(),
2909 ));
2910 }
2911 }
29122913Ok(())
2914}
29152916/// Produce the linker command line containing linker path and arguments.
2917///
2918/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2919/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2920/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2921/// to the linking process as a whole.
2922/// Order-independent options may still override each other in order-dependent fashion,
2923/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2924fn linker_with_args(
2925 path: &Path,
2926 flavor: LinkerFlavor,
2927 sess: &Session,
2928 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2929 rmeta_link_cache: &mut RmetaLinkCache,
2930 crate_type: CrateType,
2931 tmpdir: &Path,
2932 metadata_object: &Path,
2933 symbols_object: &Path,
2934 out_filename: &Path,
2935 compiled_modules: &CompiledModules,
2936 crate_info: &CrateInfo,
2937 metadata: &EncodedMetadata,
2938 self_contained_components: LinkSelfContainedComponents,
2939 codegen_backend: &'static str,
2940) -> (Command, Vec<jobserver::Acquired>) {
2941let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2942let cmd = &mut *super::linker::get_linker(
2943sess,
2944path,
2945flavor,
2946self_contained_components.are_any_components_enabled(),
2947&crate_info.target_cpu,
2948codegen_backend,
2949 );
2950let link_output_kind = link_output_kind(sess, crate_type);
29512952let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
29532954if crate_type == CrateType::Cdylib {
2955let mut seen = FxHashSet::default();
29562957for lib in &crate_info.used_libraries {
2958if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2959 && seen.insert((lib.name, lib.verbatim))
2960 {
2961if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2962 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2963"failed to process C static library `{}`: {}",
2964 lib.name, err
2965 ));
2966 }
2967 }
2968 }
2969 }
29702971// ------------ Early order-dependent options ------------
29722973 // If we're building something like a dynamic library then some platforms
2974 // need to make sure that all symbols are exported correctly from the
2975 // dynamic library.
2976 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2977 // at least on some platforms (e.g. windows-gnu).
2978cmd.export_symbols(tmpdir, crate_type, &export_symbols);
29792980// Can be used for adding custom CRT objects or overriding order-dependent options above.
2981 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2982 // introduce a target spec option for order-independent linker options and migrate built-in
2983 // specs to it.
2984add_pre_link_args(cmd, sess, flavor);
29852986// ------------ Object code and libraries, order-dependent ------------
29872988 // Pre-link CRT objects.
2989add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
29902991add_linked_symbol_object(
2992cmd,
2993sess,
2994symbols_object,
2995crate_type,
2996&crate_info.linked_symbols[&crate_type],
2997&export_symbols,
2998 );
29993000// Sanitizer libraries.
3001add_sanitizer_libraries(sess, flavor, crate_type, cmd);
30023003// Object code from the current crate.
3004 // Take careful note of the ordering of the arguments we pass to the linker
3005 // here. Linkers will assume that things on the left depend on things to the
3006 // right. Things on the right cannot depend on things on the left. This is
3007 // all formally implemented in terms of resolving symbols (libs on the right
3008 // resolve unknown symbols of libs on the left, but not vice versa).
3009 //
3010 // For this reason, we have organized the arguments we pass to the linker as
3011 // such:
3012 //
3013 // 1. The local object that LLVM just generated
3014 // 2. Local native libraries
3015 // 3. Upstream rust libraries
3016 // 4. Upstream native libraries
3017 //
3018 // The rationale behind this ordering is that those items lower down in the
3019 // list can't depend on items higher up in the list. For example nothing can
3020 // depend on what we just generated (e.g., that'd be a circular dependency).
3021 // Upstream rust libraries are not supposed to depend on our local native
3022 // libraries as that would violate the structure of the DAG, in that
3023 // scenario they are required to link to them as well in a shared fashion.
3024 //
3025 // Note that upstream rust libraries may contain native dependencies as
3026 // well, but they also can't depend on what we just started to add to the
3027 // link line. And finally upstream native libraries can't depend on anything
3028 // in this DAG so far because they can only depend on other native libraries
3029 // and such dependencies are also required to be specified.
3030add_local_crate_regular_objects(cmd, compiled_modules);
3031add_local_crate_metadata_objects(
3032cmd,
3033sess,
3034archive_builder_builder,
3035crate_type,
3036metadata_object,
3037crate_info,
3038metadata,
3039 );
3040add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
30413042// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
3043 // at the point at which they are specified on the command line.
3044 // Must be passed before any (dynamic) libraries to have effect on them.
3045 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
3046 // so it will ignore unreferenced ELF sections from relocatable objects.
3047 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
3048 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
3049 // and move this option back to the top.
3050cmd.add_as_needed();
30513052// Local native libraries of all kinds.
3053add_local_native_libraries(
3054cmd,
3055sess,
3056archive_builder_builder,
3057rmeta_link_cache,
3058crate_info,
3059tmpdir,
3060link_output_kind,
3061 );
30623063if 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(_))) {
3064cmd.link_dylib_by_name("omptarget", false, true);
3065cmd.link_dylib_by_name("omp", false, true);
3066cmd.link_args(["-z", "nostart-stop-gc"]);
3067cmd.link_arg("-rpath");
3068cmd.link_arg(std::path::absolute(&*sess.target_tlib_path.dir).unwrap());
3069 }
30703071// Upstream rust crates and their non-dynamic native libraries.
3072add_upstream_rust_crates(
3073cmd,
3074sess,
3075archive_builder_builder,
3076rmeta_link_cache,
3077crate_info,
3078crate_type,
3079tmpdir,
3080link_output_kind,
3081 );
30823083// Dynamic native libraries from upstream crates.
3084add_upstream_native_libraries(
3085cmd,
3086sess,
3087archive_builder_builder,
3088rmeta_link_cache,
3089crate_info,
3090tmpdir,
3091link_output_kind,
3092 );
30933094// Raw-dylibs from all crates.
3095let raw_dylib_dir = tmpdir.join("raw-dylibs");
3096if sess.target.binary_format == BinaryFormat::Elf {
3097// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
3098 // instead we need to pass them via -l. To find the stub, we need to add
3099 // the directory of the stub to the linker search path.
3100 // We make an extra directory for this to avoid polluting the search path.
3101if let Err(error) = fs::create_dir(&raw_dylib_dir) {
3102sess.dcx().emit_fatal(diagnostics::CreateTempDir { error })
3103 }
3104cmd.include_path(&raw_dylib_dir);
3105 }
31063107// Link with the import library generated for any raw-dylib functions.
3108if sess.target.is_like_windows {
3109for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
3110 sess,
3111 archive_builder_builder,
3112 crate_info.used_libraries.iter(),
3113 tmpdir,
3114true,
3115 ) {
3116 cmd.add_object(&output_path);
3117 }
3118 } else {
3119for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
3120 sess,
3121 crate_info.used_libraries.iter(),
3122&raw_dylib_dir,
3123 ) {
3124// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
3125cmd.link_dylib_by_name(&link_path, true, as_needed);
3126 }
3127 }
3128// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
3129 // they are used within inlined functions or instantiated generic functions. We do this *after*
3130 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
3131 // by the linker.
3132let dependency_linkage = crate_info3133 .dependency_formats
3134 .get(&crate_type)
3135 .expect("failed to find crate type in dependency format list");
31363137// We sort the libraries below
3138#[allow(rustc::potential_query_instability)]
3139let mut native_libraries_from_nonstatics = crate_info3140 .native_libraries
3141 .iter()
3142 .filter_map(|(&cnum, libraries)| {
3143if sess.target.is_like_windows {
3144 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
3145 } else {
3146Some(libraries)
3147 }
3148 })
3149 .flatten()
3150 .collect::<Vec<_>>();
3151native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
31523153if sess.target.is_like_windows {
3154for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
3155 sess,
3156 archive_builder_builder,
3157 native_libraries_from_nonstatics,
3158 tmpdir,
3159false,
3160 ) {
3161 cmd.add_object(&output_path);
3162 }
3163 } else {
3164for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
3165 sess,
3166 native_libraries_from_nonstatics,
3167&raw_dylib_dir,
3168 ) {
3169// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
3170cmd.link_dylib_by_name(&link_path, true, as_needed);
3171 }
3172 }
31733174// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
3175 // command line shorter, reset it to default here before adding more libraries.
3176cmd.reset_per_library_state();
31773178// FIXME: Built-in target specs occasionally use this for linking system libraries,
3179 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
3180 // and remove the option.
3181add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
31823183// ------------ Arbitrary order-independent options ------------
31843185 // Add order-independent options determined by rustc from its compiler options,
3186 // target properties and source code.
3187add_order_independent_options(
3188cmd,
3189sess,
3190link_output_kind,
3191self_contained_components,
3192flavor,
3193crate_type,
3194crate_info,
3195out_filename,
3196tmpdir,
3197 );
31983199// Can be used for arbitrary order-independent options.
3200 // In practice may also be occasionally used for linking native libraries.
3201 // Passed after compiler-generated options to support manual overriding when necessary.
3202add_user_defined_link_args(cmd, sess);
32033204// ------------ Builtin configurable linker scripts ------------
3205 // The user's link args should be able to overwrite symbols in the compiler's
3206 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
3207 // to work correctly, the user needs to be able to specify linker arguments like
3208 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
3209add_link_script(cmd, sess, tmpdir, crate_type);
32103211// ------------ Object code and libraries, order-dependent ------------
32123213 // Post-link CRT objects.
3214add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
32153216// ------------ Late order-dependent options ------------
32173218 // Doesn't really make sense.
3219 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
3220 // Introduce a target spec option for order-independent linker options, migrate built-in specs
3221 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
3222add_post_link_args(cmd, sess, flavor);
32233224// Only LLD supports controlling parallelism at the moment.
3225let mut tokens = Vec::new();
3226if let LinkerJobs::Explicit(mode) = sess.opts.jobs.linker
3227 && flavor.uses_lld()
3228 {
3229let threads = if let JobsMode::Parallel(limit) = mode {
3230// Try obtaining as many jobserver tokens as possible (within the limit) to run parallel
3231 // linking. One token is available implicitly since we are running on the main thread.
3232let client = jobserver::client();
32333234let mut unsupported = false;
3235for _ in 0..limit.get() - 1 {
3236match client.try_acquire() {
3237Ok(Some(token)) => tokens.push(token),
3238Ok(None) => {}
3239Err(e) if e.kind() == io::ErrorKind::Unsupported => {
3240if !tokens.is_empty() {
::core::panicking::panic("assertion failed: tokens.is_empty()")
};assert!(tokens.is_empty());
3241 unsupported = true;
3242break;
3243 }
3244Err(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}"),
3245 }
3246 }
32473248// Error on the side of oversubscription if non-blocking token acquiring is unsupported.
3249 // Linking is typically the last step in a multi-crate project build,
3250 // so the resources should usually be free.
3251if unsupported { limit.get() } else { 1 + tokens.len() }
3252 } else {
32531
3254};
32553256let prefix = if sess.target.is_like_windows { "/threads:" } else { "--threads=" };
3257cmd.link_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix, threads))
})format!("{prefix}{threads}"));
3258 }
32593260 (cmd.take_cmd(), tokens)
3261}
32623263fn add_order_independent_options(
3264 cmd: &mut dyn Linker,
3265 sess: &Session,
3266 link_output_kind: LinkOutputKind,
3267 self_contained_components: LinkSelfContainedComponents,
3268 flavor: LinkerFlavor,
3269 crate_type: CrateType,
3270 crate_info: &CrateInfo,
3271 out_filename: &Path,
3272 tmpdir: &Path,
3273) {
3274// Take care of the flavors and CLI options requesting the `lld` linker.
3275add_lld_args(cmd, sess, flavor, self_contained_components);
32763277add_apple_link_args(cmd, sess, flavor);
32783279let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
32803281if sess.target.os == Os::Fuchsia3282 && crate_type == CrateType::Executable3283 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))3284 {
3285let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
3286cmd.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"));
3287 }
32883289if sess.target.eh_frame_header {
3290cmd.add_eh_frame_header();
3291 }
32923293// Make the binary compatible with data execution prevention schemes.
3294cmd.add_no_exec();
32953296if self_contained_components.is_crt_objects_enabled() {
3297cmd.no_crt_objects();
3298 }
32993300if sess.target.os == Os::Emscripten {
3301cmd.cc_arg("-fwasm-exceptions");
3302 }
33033304if flavor == LinkerFlavor::Llbc {
3305cmd.link_args(&[
3306"--target",
3307&versioned_llvm_target(sess),
3308"--target-cpu",
3309&crate_info.target_cpu,
3310 ]);
3311if crate_info.target_features.len() > 0 {
3312cmd.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(",")));
3313 }
3314 } else if flavor == LinkerFlavor::Bpf {
3315cmd.link_args(&["--cpu", &crate_info.target_cpu]);
3316if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
3317 .into_iter()
3318 .find(|feat| !feat.is_empty())
3319 {
3320cmd.link_args(&["--cpu-features", feat]);
3321 }
3322 }
33233324cmd.linker_plugin_lto();
33253326add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
33273328cmd.output_filename(out_filename);
33293330if crate_type == CrateType::Executable3331 && sess.target.is_like_windows
3332 && let Some(s) = &crate_info.windows_subsystem
3333 {
3334cmd.windows_subsystem(*s);
3335 }
33363337// Try to strip as much out of the generated object by removing unused
3338 // sections if possible. See more comments in linker.rs
3339if !sess.link_dead_code() {
3340// If PGO is enabled sometimes gc_sections will remove the profile data section
3341 // as it appears to be unused. This can then cause the PGO profile file to lose
3342 // some functions. If we are generating a profile we shouldn't strip those metadata
3343 // sections to ensure we have all the data for PGO.
3344let keep_metadata =
3345crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
3346cmd.gc_sections(keep_metadata);
3347 }
33483349cmd.set_output_kind(link_output_kind, crate_type, out_filename);
33503351add_relro_args(cmd, sess);
33523353// Pass optimization flags down to the linker.
3354cmd.optimize();
33553356// Gather the set of NatVis files, if any, and write them out to a temp directory.
3357let natvis_visualizers = collect_natvis_visualizers(
3358tmpdir,
3359sess,
3360&crate_info.local_crate_name,
3361&crate_info.natvis_debugger_visualizers,
3362 );
33633364// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
3365cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
33663367// We want to prevent the compiler from accidentally leaking in any system libraries,
3368 // so by default we tell linkers not to link to any default libraries.
3369if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
3370cmd.no_default_libraries();
3371 }
33723373if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
3374cmd.pgo_gen();
3375 }
33763377if sess.opts.unstable_opts.instrument_mcount != InstrumentMcount::Disabled {
3378cmd.enable_profiling();
3379 }
33803381if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
3382cmd.control_flow_guard();
3383 }
33843385// OBJECT-FILES-NO, AUDIT-ORDER
3386if sess.opts.unstable_opts.ehcont_guard {
3387cmd.ehcont_guard();
3388 }
33893390add_rpath_args(cmd, sess, crate_info, out_filename);
3391}
33923393// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
3394fn collect_natvis_visualizers(
3395 tmpdir: &Path,
3396 sess: &Session,
3397 crate_name: &Symbol,
3398 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
3399) -> Vec<PathBuf> {
3400let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
34013402for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
3403let 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));
34043405match fs::write(&visualizer_out_file, &visualizer.src) {
3406Ok(()) => {
3407 visualizer_paths.push(visualizer_out_file);
3408 }
3409Err(error) => {
3410 sess.dcx().emit_warn(diagnostics::UnableToWriteDebuggerVisualizer {
3411 path: visualizer_out_file,
3412 error,
3413 });
3414 }
3415 };
3416 }
3417visualizer_paths3418}
34193420fn add_native_libs_from_crate(
3421 cmd: &mut dyn Linker,
3422 sess: &Session,
3423 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3424 rmeta_link_cache: &mut RmetaLinkCache,
3425 crate_info: &CrateInfo,
3426 tmpdir: &Path,
3427 bundled_libs: &FxIndexSet<Symbol>,
3428 cnum: CrateNum,
3429 link_static: bool,
3430 link_dynamic: bool,
3431 link_output_kind: LinkOutputKind,
3432) {
3433if !sess.opts.unstable_opts.link_native_libraries {
3434// If `-Zlink-native-libraries=false` is set, then the assumption is that an
3435 // external build system already has the native dependencies defined, and it
3436 // will provide them to the linker itself.
3437return;
3438 }
34393440if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
3441// If rlib contains native libs as archives, unpack them to tmpdir.
3442let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
3443archive_builder_builder3444 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
3445 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
3446 }
34473448let (native_libs, bundled_filenames): (&Vec<NativeLib>, Vec<Option<Symbol>>) = match cnum {
3449// Bundled libraries are only linked by path for upstream crates, so the local crate
3450 // never needs their filenames.
3451LOCAL_CRATE => (&crate_info.used_libraries, Vec::new()),
3452_ => {
3453let native_libs = &crate_info.native_libraries[&cnum];
3454let filenames =
3455if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
3456rmeta_link_cache.native_lib_filenames(&sess.target, rlib_path, native_libs)
3457 } else {
3458Vec::new()
3459 };
3460 (native_libs, filenames)
3461 }
3462 };
34633464let mut last = (None, NativeLibKind::Unspecified, false);
3465for (i, lib) in native_libs.iter().enumerate() {
3466if !relevant_lib(sess, lib) {
3467continue;
3468 }
34693470// Skip if this library is the same as the last.
3471last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
3472continue;
3473 } else {
3474 (Some(lib.name), lib.kind, lib.verbatim)
3475 };
34763477let name = lib.name.as_str();
3478let verbatim = lib.verbatim;
3479match lib.kind {
3480 NativeLibKind::Static { bundle, whole_archive, .. } => {
3481if link_static {
3482let bundle = bundle.unwrap_or(true);
3483let whole_archive = whole_archive == Some(true);
3484if bundle && cnum != LOCAL_CRATE {
3485if let Some(filename) = bundled_filenames.get(i).copied().flatten() {
3486// If rlib contains native libs as archives, they are unpacked to tmpdir.
3487let path = tmpdir.join(filename.as_str());
3488 cmd.link_staticlib_by_path(&path, whole_archive);
3489 }
3490 } else {
3491 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
3492 }
3493 }
3494 }
3495 NativeLibKind::Dylib { as_needed } => {
3496if link_dynamic {
3497 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
3498 }
3499 }
3500 NativeLibKind::Unspecified => {
3501// If we are generating a static binary, prefer static library when the
3502 // link kind is unspecified.
3503if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
3504if link_static {
3505 cmd.link_staticlib_by_name(name, verbatim, false);
3506 }
3507 } else if link_dynamic {
3508 cmd.link_dylib_by_name(name, verbatim, true);
3509 }
3510 }
3511 NativeLibKind::Framework { as_needed } => {
3512if link_dynamic {
3513 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
3514 }
3515 }
3516 NativeLibKind::RawDylib { as_needed: _ } => {
3517// Handled separately in `linker_with_args`.
3518}
3519 NativeLibKind::WasmImportModule => {}
3520 NativeLibKind::LinkArg => {
3521if link_static {
3522if verbatim {
3523 cmd.verbatim_arg(name);
3524 } else {
3525 cmd.link_arg(name);
3526 }
3527 }
3528 }
3529 }
3530 }
3531}
35323533fn add_local_native_libraries(
3534 cmd: &mut dyn Linker,
3535 sess: &Session,
3536 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3537 rmeta_link_cache: &mut RmetaLinkCache,
3538 crate_info: &CrateInfo,
3539 tmpdir: &Path,
3540 link_output_kind: LinkOutputKind,
3541) {
3542// All static and dynamic native library dependencies are linked to the local crate.
3543let link_static = true;
3544let link_dynamic = true;
3545add_native_libs_from_crate(
3546cmd,
3547sess,
3548archive_builder_builder,
3549rmeta_link_cache,
3550crate_info,
3551tmpdir,
3552&Default::default(),
3553LOCAL_CRATE,
3554link_static,
3555link_dynamic,
3556link_output_kind,
3557 );
3558}
35593560fn add_upstream_rust_crates(
3561 cmd: &mut dyn Linker,
3562 sess: &Session,
3563 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3564 rmeta_link_cache: &mut RmetaLinkCache,
3565 crate_info: &CrateInfo,
3566 crate_type: CrateType,
3567 tmpdir: &Path,
3568 link_output_kind: LinkOutputKind,
3569) {
3570// All of the heavy lifting has previously been accomplished by the
3571 // dependency_format module of the compiler. This is just crawling the
3572 // output of that module, adding crates as necessary.
3573 //
3574 // Linking to a rlib involves just passing it to the linker (the linker
3575 // will slurp up the object files inside), and linking to a dynamic library
3576 // involves just passing the right -l flag.
3577let data = crate_info3578 .dependency_formats
3579 .get(&crate_type)
3580 .expect("failed to find crate type in dependency format list");
35813582if sess.target.is_like_aix {
3583// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3584 // the dependency name when outputting a shared library. Thus, `ld` will
3585 // use the full path to shared libraries as the dependency if passed it
3586 // by default unless `noipath` is passed.
3587 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3588cmd.link_or_cc_arg("-bnoipath");
3589 }
35903591for &cnum in &crate_info.used_crates {
3592// We may not pass all crates through to the linker. Some crates may appear statically in
3593 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3594 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3595 // Even if they were already included into a dylib
3596 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3597 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3598 // See the comment in inject_profiler_runtime for why this is the case.
3599let linkage = data[cnum];
3600let link_static_crate = linkage == Linkage::Static
3601 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3602 && (crate_info.compiler_builtins == Some(cnum)
3603 || crate_info.profiler_runtime == Some(cnum));
36043605let mut bundled_libs = Default::default();
3606match linkage {
3607 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3608if link_static_crate {
3609if let Some(rlib_path) = crate_info.used_crate_source[&cnum].rlib.as_ref() {
3610 bundled_libs = rmeta_link_cache
3611 .native_lib_filenames(
3612&sess.target,
3613 rlib_path,
3614&crate_info.native_libraries[&cnum],
3615 )
3616 .into_iter()
3617 .flatten()
3618 .collect();
3619 }
3620 add_static_crate(
3621 cmd,
3622 sess,
3623 archive_builder_builder,
3624 rmeta_link_cache,
3625 crate_info,
3626 tmpdir,
3627 cnum,
3628&bundled_libs,
3629 );
3630 }
3631 }
3632 Linkage::Dynamic => {
3633let src = &crate_info.used_crate_source[&cnum];
3634 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3635 }
3636 }
36373638// Static libraries are linked for a subset of linked upstream crates.
3639 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3640 // because the rlib is just an archive.
3641 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3642 // the native library because it is already linked into the dylib, and even if
3643 // inline/const/generic functions from the dylib can refer to symbols from the native
3644 // library, those symbols should be exported and available from the dylib anyway.
3645 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3646let link_static = link_static_crate;
3647// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3648let link_dynamic = false;
3649 add_native_libs_from_crate(
3650 cmd,
3651 sess,
3652 archive_builder_builder,
3653 rmeta_link_cache,
3654 crate_info,
3655 tmpdir,
3656&bundled_libs,
3657 cnum,
3658 link_static,
3659 link_dynamic,
3660 link_output_kind,
3661 );
3662 }
3663}
36643665fn add_upstream_native_libraries(
3666 cmd: &mut dyn Linker,
3667 sess: &Session,
3668 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3669 rmeta_link_cache: &mut RmetaLinkCache,
3670 crate_info: &CrateInfo,
3671 tmpdir: &Path,
3672 link_output_kind: LinkOutputKind,
3673) {
3674for &cnum in &crate_info.used_crates {
3675// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3676 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3677 // are linked together with their respective upstream crates, and in their originally
3678 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3679 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3680let link_static = false;
3681// Dynamic libraries are linked for all linked upstream crates.
3682 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3683 // because the rlib is just an archive.
3684 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3685 // the native library too because inline/const/generic functions from the dylib can refer
3686 // to symbols from the native library, so the native library providing those symbols should
3687 // be available when linking our final binary.
3688let link_dynamic = true;
3689 add_native_libs_from_crate(
3690 cmd,
3691 sess,
3692 archive_builder_builder,
3693 rmeta_link_cache,
3694 crate_info,
3695 tmpdir,
3696&Default::default(),
3697 cnum,
3698 link_static,
3699 link_dynamic,
3700 link_output_kind,
3701 );
3702 }
3703}
37043705// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3706// to be relative to the sysroot directory, which may be a relative path specified by the user.
3707//
3708// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3709// linker command line can be non-deterministic due to the paths including the current working
3710// directory. The linker command line needs to be deterministic since it appears inside the PDB
3711// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3712//
3713// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3714fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3715let sysroot_lib_path = &sess.target_tlib_path.dir;
3716let canonical_sysroot_lib_path =
3717 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.to_path_buf()) };
37183719let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3720if canonical_lib_dir == canonical_sysroot_lib_path {
3721// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3722sysroot_lib_path.to_path_buf()
3723 } else {
3724fix_windows_verbatim_for_gcc(lib_dir)
3725 }
3726}
37273728fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3729if let Some(dir) = path.parent() {
3730let file_name = path.file_name().expect("library path has no file name component");
3731rehome_sysroot_lib_dir(sess, dir).join(file_name)
3732 } else {
3733fix_windows_verbatim_for_gcc(path)
3734 }
3735}
37363737// Adds the static "rlib" versions of all crates to the command line.
3738// There's a bit of magic which happens here specifically related to LTO,
3739// namely that we remove upstream object files.
3740//
3741// When performing LTO, almost(*) all of the bytecode from the upstream
3742// libraries has already been included in our object file output. As a
3743// result we need to remove the object files in the upstream libraries so
3744// the linker doesn't try to include them twice (or whine about duplicate
3745// symbols). We must continue to include the rest of the rlib, however, as
3746// it may contain static native libraries which must be linked in.
3747//
3748// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3749// their bytecode wasn't included. The object files in those libraries must
3750// still be passed to the linker.
3751//
3752// Note, however, that if we're not doing LTO we can just pass the rlib
3753// blindly to the linker (fast) because it's fine if it's not actually
3754// included as we're at the end of the dependency chain.
3755fn add_static_crate(
3756 cmd: &mut dyn Linker,
3757 sess: &Session,
3758 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3759 rmeta_link_cache: &mut RmetaLinkCache,
3760 crate_info: &CrateInfo,
3761 tmpdir: &Path,
3762 cnum: CrateNum,
3763 bundled_lib_file_names: &FxIndexSet<Symbol>,
3764) {
3765let src = &crate_info.used_crate_source[&cnum];
3766let cratepath = src.rlib.as_ref().unwrap();
37673768let mut link_upstream =
3769 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
37703771if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3772 {
3773link_upstream(cratepath);
3774return;
3775 }
37763777let dst = tmpdir.join(cratepath.file_name().unwrap());
3778let name = cratepath.file_name().unwrap().to_str().unwrap();
3779let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3780let bundled_lib_file_names = bundled_lib_file_names.clone();
37813782sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3783let upstream_rust_objects_already_included =
3784are_upstream_rust_objects_already_included(sess);
3785let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
37863787let mut archive = archive_builder_builder.new_archive_builder(sess);
3788if let Err(error) = archive.add_archive(
3789cratepath,
3790 AddArchiveKind::Rlib(rmeta_link_cache, &|f, entry_kind| {
3791if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3792return true;
3793 }
37943795// If we're performing LTO and this is a rust-generated object
3796 // file, then we don't need the object file as it's part of the
3797 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3798 // though, so we let that object file slide.
3799if upstream_rust_objects_already_included3800 && entry_kind == ArchiveEntryKind::RustObj3801 && is_builtins3802 {
3803return true;
3804 }
38053806// We skip native libraries because:
3807 // 1. This native libraries won't be used from the generated rlib,
3808 // so we can throw them away to avoid the copying work.
3809 // 2. We can't allow it to be a single remaining entry in archive
3810 // as some linkers may complain on that.
3811if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3812return true;
3813 }
38143815false
3816}),
3817 ) {
3818sess.dcx().emit_fatal(diagnostics::RlibArchiveBuildFailure {
3819 path: cratepath.clone(),
3820error,
3821 });
3822 }
3823if archive.build(&dst, None) {
3824link_upstream(&dst);
3825 }
3826 });
3827}
38283829// Same thing as above, but for dynamic crates instead of static crates.
3830fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3831cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3832}
38333834fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3835match lib.cfg {
3836Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3837None => true,
3838 }
3839}
38403841pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3842match sess.lto() {
3843 config::Lto::Fat => true,
3844 config::Lto::Thin => {
3845// If we defer LTO to the linker, we haven't run LTO ourselves, so
3846 // any upstream object files have not been copied yet.
3847!sess.opts.cg.linker_plugin_lto.enabled()
3848 }
3849 config::Lto::No | config::Lto::ThinLocal => false,
3850 }
3851}
38523853/// We need to communicate five things to the linker on Apple/Darwin targets:
3854/// - The architecture.
3855/// - The operating system (and that it's an Apple platform).
3856/// - The environment.
3857/// - The deployment target.
3858/// - The SDK version.
3859fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3860if !sess.target.is_like_darwin {
3861return;
3862 }
3863let LinkerFlavor::Darwin(cc, _) = flavorelse {
3864return;
3865 };
38663867// `sess.target.arch` (`target_arch`) is not detailed enough.
3868let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3869let target_os = &sess.target.os;
3870let target_env = &sess.target.env;
38713872// The architecture name to forward to the linker.
3873 //
3874 // Supported architecture names can be found in the source:
3875 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3876 //
3877 // Intentionally verbose to ensure that the list always matches correctly
3878 // with the list in the source above.
3879let ld64_arch = match llvm_arch {
3880"armv7k" => "armv7k",
3881"armv7s" => "armv7s",
3882"arm64" => "arm64",
3883"arm64e" => "arm64e",
3884"arm64_32" => "arm64_32",
3885// ld64 doesn't understand i686, so fall back to i386 instead.
3886 //
3887 // Same story when linking with cc, since that ends up invoking ld64.
3888"i386" | "i686" => "i386",
3889"x86_64" => "x86_64",
3890"x86_64h" => "x86_64h",
3891_ => ::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),
3892 };
38933894if cc == Cc::No {
3895// From the man page for ld64 (`man ld`):
3896 // > The linker accepts universal (multiple-architecture) input files,
3897 // > but always creates a "thin" (single-architecture), standard
3898 // > Mach-O output file. The architecture for the output file is
3899 // > specified using the -arch option.
3900 //
3901 // The linker has heuristics to determine the desired architecture,
3902 // but to be safe, and to avoid a warning, we set the architecture
3903 // explicitly.
3904cmd.link_args(&["-arch", ld64_arch]);
39053906// Man page says that ld64 supports the following platform names:
3907 // > - macos
3908 // > - ios
3909 // > - tvos
3910 // > - watchos
3911 // > - bridgeos
3912 // > - visionos
3913 // > - xros
3914 // > - mac-catalyst
3915 // > - ios-simulator
3916 // > - tvos-simulator
3917 // > - watchos-simulator
3918 // > - visionos-simulator
3919 // > - xros-simulator
3920 // > - driverkit
3921let platform_name = match (target_os, target_env) {
3922 (os, Env::Unspecified) => os.desc(),
3923 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3924 (Os::IOs, Env::Sim) => "ios-simulator",
3925 (Os::TvOs, Env::Sim) => "tvos-simulator",
3926 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3927 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3928_ => ::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}"),
3929 };
39303931let min_version = sess.apple_deployment_target().fmt_full().to_string();
39323933// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3934 // - By dyld to give extra warnings and errors, see e.g.:
3935 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3936 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3937 // - By system frameworks to change certain behaviour. For example, the default value of
3938 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3939 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3940 //
3941 // We do not currently know the actual SDK version though, so we have a few options:
3942 // 1. Use the minimum version supported by rustc.
3943 // 2. Use the same as the deployment target.
3944 // 3. Use an arbitrary recent version.
3945 // 4. Omit the version.
3946 //
3947 // The first option is too low / too conservative, and means that users will not get the
3948 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3949 //
3950 // The second option is similarly conservative, and also wrong since if the user specified a
3951 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3952 // make invalid assumptions about the capabilities of the binary.
3953 //
3954 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3955 // version, and is also wrong for similar reasons as above.
3956 //
3957 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3958 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3959 // it as 0.0, which is again too low/conservative.
3960 //
3961 // Currently, we lie about the SDK version, and choose the second option.
3962 //
3963 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3964 // <https://github.com/rust-lang/rust/issues/129432>
3965let sdk_version = &*min_version;
39663967// From the man page for ld64 (`man ld`):
3968 // > This is set to indicate the platform, oldest supported version of
3969 // > that platform that output is to be used on, and the SDK that the
3970 // > output was built against.
3971 //
3972 // Like with `-arch`, the linker can figure out the platform versions
3973 // itself from the binaries being linked, but to be safe, we specify
3974 // the desired versions here explicitly.
3975cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3976 } else {
3977// cc == Cc::Yes
3978 //
3979 // We'd _like_ to use `-target` everywhere, since that can uniquely
3980 // communicate all the required details except for the SDK version
3981 // (which is read by Clang itself from the SDKROOT), but that doesn't
3982 // work on GCC, and since we don't know whether the `cc` compiler is
3983 // Clang, GCC, or something else, we fall back to other options that
3984 // also work on GCC when compiling for macOS.
3985 //
3986 // Targets other than macOS are ill-supported by GCC (it doesn't even
3987 // support e.g. `-miphoneos-version-min`), so in those cases we can
3988 // fairly safely use `-target`. See also the following, where it is
3989 // made explicit that the recommendation by LLVM developers is to use
3990 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3991if *target_os == Os::MacOs {
3992// `-arch` communicates the architecture.
3993 //
3994 // CC forwards the `-arch` to the linker, so we use the same value
3995 // here intentionally.
3996cmd.cc_args(&["-arch", ld64_arch]);
39973998// The presence of `-mmacosx-version-min` makes CC default to
3999 // macOS, and it sets the deployment target.
4000let version = sess.apple_deployment_target().fmt_full();
4001// Intentionally pass this as a single argument, Clang doesn't
4002 // seem to like it otherwise.
4003cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
40044005// macOS has no environment, so with these two, we've told CC the
4006 // four desired parameters.
4007 //
4008 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
4009} else {
4010cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
4011 }
4012 }
4013}
40144015fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
4016if !sess.target.is_like_darwin {
4017return None;
4018 }
4019let LinkerFlavor::Darwin(cc, _) = flavorelse {
4020return None;
4021 };
40224023// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
4024 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
4025 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
4026 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
4027 // instead we invoke `xcrun` manually.
4028 //
4029 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
4030 // cause the trampoline binary to skip looking up the SDK itself).
4031let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
40324033if cc == Cc::Yes {
4034// There are a few options to pass the SDK root when linking with a C/C++ compiler:
4035 // - The `--sysroot` flag.
4036 // - The `-isysroot` flag.
4037 // - The `SDKROOT` environment variable.
4038 //
4039 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
4040 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
4041 // only applies to include header files, but on Apple targets it also applies to libraries
4042 // and frameworks.
4043 //
4044 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
4045 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
4046 // primarily because that is the same interface that is used when invoking the tool under
4047 // `xcrun -sdk macosx $tool`.
4048 //
4049 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
4050 // clearly in the tool in question, since they also don't support being run under `xcrun`.
4051 //
4052 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
4053 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
4054 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
4055 //
4056 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
4057 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
4058 // ignoring the value we set here, and instead use their built-in sysroot).
4059cmd.cmd().env("SDKROOT", &sdkroot);
4060 } else {
4061// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
4062 // read by the linker, so it's really the only option.
4063 //
4064 // This is also what Clang does.
4065cmd.link_arg("-syslibroot");
4066cmd.link_arg(&sdkroot);
4067 }
40684069Some(sdkroot)
4070}
40714072fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
4073if let Ok(sdkroot) = env::var("SDKROOT") {
4074let p = PathBuf::from(&sdkroot);
40754076// Ignore invalid SDKs, similar to what clang does:
4077 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
4078 //
4079 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
4080 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
4081 // clearly set for the wrong platform.
4082 //
4083 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
4084match &*apple::sdk_name(&sess.target).to_lowercase() {
4085"appletvos"
4086if sdkroot.contains("TVSimulator.platform")
4087 || sdkroot.contains("MacOSX.platform") => {}
4088"appletvsimulator"
4089if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
4090"iphoneos"
4091if sdkroot.contains("iPhoneSimulator.platform")
4092 || sdkroot.contains("MacOSX.platform") => {}
4093"iphonesimulator"
4094if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
4095 }
4096"macosx"
4097if sdkroot.contains("iPhoneOS.platform")
4098 || sdkroot.contains("iPhoneSimulator.platform")
4099 || sdkroot.contains("AppleTVOS.platform")
4100 || sdkroot.contains("AppleTVSimulator.platform")
4101 || sdkroot.contains("WatchOS.platform")
4102 || sdkroot.contains("WatchSimulator.platform")
4103 || sdkroot.contains("XROS.platform")
4104 || sdkroot.contains("XRSimulator.platform") => {}
4105"watchos"
4106if sdkroot.contains("WatchSimulator.platform")
4107 || sdkroot.contains("MacOSX.platform") => {}
4108"watchsimulator"
4109if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
4110"xros"
4111if sdkroot.contains("XRSimulator.platform")
4112 || sdkroot.contains("MacOSX.platform") => {}
4113"xrsimulator"
4114if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
4115// Ignore `SDKROOT` if it's not a valid path.
4116_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
4117_ => return Some(p),
4118 }
4119 }
41204121 apple::get_sdk_root(sess)
4122}
41234124/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
4125/// invoke it:
4126/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
4127/// - or any `lld` available to `cc`.
4128fn add_lld_args(
4129 cmd: &mut dyn Linker,
4130 sess: &Session,
4131 flavor: LinkerFlavor,
4132 self_contained_components: LinkSelfContainedComponents,
4133) {
4134{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs:4134",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(4134u32),
::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!(
4135"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
4136 flavor, self_contained_components,
4137 );
41384139// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
4140 // we don't need to do anything.
4141if !(flavor.uses_cc() && flavor.uses_lld()) {
4142return;
4143 }
41444145// 1. Implement the "self-contained" part of this feature by adding rustc distribution
4146 // directories to the tool's search path, depending on a mix between what users can specify on
4147 // the CLI, and what the target spec enables (as it can't disable components):
4148 // - if the self-contained linker is enabled on the CLI or by the target spec,
4149 // - and if the self-contained linker is not disabled on the CLI.
4150let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
4151let self_contained_target = self_contained_components.is_linker_enabled();
41524153let self_contained_linker = self_contained_cli || self_contained_target;
4154if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
4155let mut linker_path_exists = false;
4156for path in sess.get_tools_search_paths(false) {
4157let linker_path = path.join("gcc-ld");
4158 linker_path_exists |= linker_path.exists();
4159 cmd.cc_arg({
4160let mut arg = OsString::from("-B");
4161 arg.push(linker_path);
4162 arg
4163 });
4164 }
4165if !linker_path_exists {
4166// As a sanity check, we emit an error if none of these paths exist: we want
4167 // self-contained linking and have no linker.
4168sess.dcx().emit_fatal(diagnostics::SelfContainedLinkerMissing);
4169 }
4170 }
41714172// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
4173 // `lld` as the linker.
4174 //
4175 // Note that wasm targets skip this step since the only option there anyway
4176 // is to use LLD but component-producing targets rely on a wrapper around
4177 // this, `wasm-component-ld`, which is overridden if this option is passed.
4178if !sess.target.is_like_wasm {
4179cmd.cc_arg("-fuse-ld=lld");
4180 }
41814182if !flavor.is_gnu() {
4183// Tell clang to use a non-default LLD flavor.
4184 // Gcc doesn't understand the target option, but we currently assume
4185 // that gcc is not used for Apple and Wasm targets (#97402).
4186 //
4187 // Note that we don't want to do that by default on macOS: e.g. passing a
4188 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
4189 // shown in issue #101653 and the discussion in PR #101792.
4190 //
4191 // It could be required in some cases of cross-compiling with
4192 // LLD, but this is generally unspecified, and we don't know
4193 // which specific versions of clang, macOS SDK, host and target OS
4194 // combinations impact us here.
4195 //
4196 // So we do a simple first-approximation until we know more of what the
4197 // Apple targets require (and which would be handled prior to hitting this
4198 // LLD codepath anyway), but the expectation is that until then
4199 // this should be manually passed if needed. We specify the target when
4200 // targeting a different linker flavor on macOS, and that's also always
4201 // the case when targeting WASM.
4202if sess.target.linker_flavor != sess.host.linker_flavor {
4203cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
4204 }
4205 }
4206}
42074208// gold has been deprecated with binutils 2.44
4209// and is known to behave incorrectly around Rust programs.
4210// There have been reports of being unable to bootstrap with gold:
4211// https://github.com/rust-lang/rust/issues/139425
4212// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
4213// emitted with `#[used(linker)]`.
4214fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
4215use object::read::elf::{FileHeader, SectionHeader};
4216use object::read::{ReadCache, ReadRef, Result};
4217use object::{Endianness, elf};
42184219fn elf_has_gold_version_note<'a>(
4220 elf: &impl FileHeader,
4221 data: impl ReadRef<'a>,
4222 ) -> Result<bool> {
4223let endian = elf.endian()?;
42244225let section =
4226 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
4227if let Some((_, section)) = section4228 && let Some(mut notes) = section.notes(endian, data)?
4229{
4230return Ok(notes.any(|note| {
4231note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
4232 }));
4233 }
42344235Ok(false)
4236 }
42374238let data = ReadCache::new(BufReader::new(File::open(path)?));
42394240let was_linked_with_gold = if sess.target.pointer_width == 64 {
4241let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
4242 elf_has_gold_version_note(elf, &data)?
4243} else if sess.target.pointer_width == 32 {
4244let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
4245 elf_has_gold_version_note(elf, &data)?
4246} else {
4247return Ok(());
4248 };
42494250if was_linked_with_gold {
4251let mut warn =
4252sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
4253warn.help("consider using LLD or ld from GNU binutils instead");
4254warn.emit();
4255 }
4256Ok(())
4257}