1mod raw_dylib;
23use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
1112use find_msvc_tools;
13use itertools::Itertools;
14use object::{Object, ObjectSection, ObjectSymbol};
15use regex::Regex;
16use rustc_arena::TypedArena;
17use rustc_attr_parsing::eval_config_entry;
18use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::DiagCtxtHandle;
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_lint_defs::builtin::LINKER_INFO;
26use rustc_macros::Diagnostic;
27use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
28use rustc_metadata::{
29 EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
30 walk_native_lib_search_dirs,
31};
32use rustc_middle::bug;
33use rustc_middle::lint::emit_lint_base;
34use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
35use rustc_middle::middle::dependency_format::Linkage;
36use rustc_middle::middle::exported_symbols::SymbolExportKind;
37use rustc_session::config::{
38self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
39OutputType, PrintKind, SplitDwarfKind, Strip,
40};
41use rustc_session::lint::builtin::LINKER_MESSAGES;
42use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
43use rustc_session::search_paths::PathKind;
44/// For all the linkers we support, and information they might
45/// need out of the shared crate context before we get rid of it.
46use rustc_session::{Session, filesearch};
47use rustc_span::Symbol;
48use rustc_target::spec::crt_objects::CrtObjects;
49use rustc_target::spec::{
50Arch, BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
51LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
52RelroLevel, SanitizerSet, SplitDebuginfo,
53};
54use tracing::{debug, info, warn};
5556use super::archive::{
57AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind, ArchiveSymbols,
58};
59use super::command::Command;
60use super::linker::{self, Linker};
61use super::metadata::{MetadataPosition, create_wrapper_file};
62use super::rpath::{self, RPathConfig};
63use super::{apple, rmeta_link, versioned_llvm_target};
64use crate::base::needs_allocator_shim_for_linking;
65use crate::{CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors};
6667pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
68if let Err(e) = fs::remove_file(path) {
69if e.kind() != io::ErrorKind::NotFound {
70dcx.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));
71 }
72 }
73}
7475/// Performs the linkage portion of the compilation phase. This will generate all
76/// of the requested outputs for this compilation session.
77pub fn link_binary(
78 sess: &Session,
79 archive_builder_builder: &dyn ArchiveBuilderBuilder,
80 compiled_modules: CompiledModules,
81 crate_info: CrateInfo,
82 metadata: EncodedMetadata,
83 outputs: &OutputFilenames,
84 codegen_backend: &'static str,
85) {
86let _timer = sess.timer("link_binary");
87let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
88let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
89for &crate_type in &crate_info.crate_types {
90// Ignore executable crates if we have -Z no-codegen, as they will error.
91if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
92 && !output_metadata
93 && crate_type == CrateType::Executable
94 {
95continue;
96 }
9798if invalid_output_for_target(sess, crate_type) {
99::rustc_middle::util::bug::bug_fmt(format_args!("invalid output type `{0:?}` for target `{1}`",
crate_type, sess.opts.target_triple));bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
100 }
101102 sess.time("link_binary_check_files_are_writeable", || {
103for m in &compiled_modules.modules {
104if let Some(obj) = &m.object {
105 check_file_is_writeable(obj, sess);
106 }
107if let Some(obj) = &m.global_asm_object {
108 check_file_is_writeable(obj, sess);
109 }
110 }
111 });
112113if outputs.outputs.should_link() {
114let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
115let tmpdir = TempDirBuilder::new()
116 .prefix("rustc")
117 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
118 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
119let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
120121let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
122let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
123match crate_type {
124 CrateType::Rlib => {
125let _timer = sess.timer("link_rlib");
126{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:126",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(126u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing rlib to {0:?}",
out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing rlib to {:?}", out_filename);
127 link_rlib(
128 sess,
129 archive_builder_builder,
130&compiled_modules,
131&crate_info,
132&metadata,
133 RlibFlavor::Normal,
134&path,
135 )
136 .build(&out_filename, None);
137 }
138 CrateType::StaticLib => {
139 link_staticlib(
140 sess,
141 archive_builder_builder,
142&compiled_modules,
143&crate_info,
144&metadata,
145&out_filename,
146&path,
147 );
148 }
149_ => {
150 link_natively(
151 sess,
152 archive_builder_builder,
153 crate_type,
154&out_filename,
155&compiled_modules,
156&crate_info,
157&metadata,
158 path.as_ref(),
159 codegen_backend,
160 );
161 }
162 }
163if sess.opts.json_artifact_notifications {
164 sess.dcx().emit_artifact_notification(&out_filename, "link");
165 }
166167if sess.prof.enabled()
168 && let Some(artifact_name) = out_filename.file_name()
169 {
170// Record size for self-profiling
171let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
172173 sess.prof.artifact_size(
174"linked_artifact",
175 artifact_name.to_string_lossy(),
176 file_size,
177 );
178 }
179180if sess.target.binary_format == BinaryFormat::Elf {
181if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
182{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:182",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(182u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message", "err"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Error while checking if gold was the linker")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&err) as
&dyn Value))])
});
} else { ; }
};info!(?err, "Error while checking if gold was the linker");
183 }
184 }
185186if output.is_stdout() {
187if output.is_tty() {
188 sess.dcx().emit_err(errors::BinaryOutputToTty {
189 shorthand: OutputType::Exe.shorthand(),
190 });
191 } else if let Err(e) = copy_to_stdout(&out_filename) {
192 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
193 }
194 tempfiles_for_stdout_output.push(out_filename);
195 }
196 }
197 }
198199// Remove the temporary object file and metadata if we aren't saving temps.
200sess.time("link_binary_remove_temps", || {
201// If the user requests that temporaries are saved, don't delete any.
202if sess.opts.cg.save_temps {
203return;
204 }
205206let maybe_remove_temps_from_module =
207 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
208if !preserve_objects && let Some(ref obj) = module.object {
209ensure_removed(sess.dcx(), obj);
210 }
211212if !preserve_objects && let Some(ref obj) = module.global_asm_object {
213ensure_removed(sess.dcx(), obj);
214 }
215216if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
217ensure_removed(sess.dcx(), dwo_obj);
218 }
219 };
220221let remove_temps_from_module =
222 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
223224// Otherwise, always remove the allocator module temporaries.
225if let Some(ref allocator_module) = compiled_modules.allocator_module {
226remove_temps_from_module(allocator_module);
227 }
228229// Remove the temporary files if output goes to stdout
230for temp in tempfiles_for_stdout_output {
231 ensure_removed(sess.dcx(), &temp);
232 }
233234// If no requested outputs require linking, then the object temporaries should
235 // be kept.
236if !sess.opts.output_types.should_link() {
237return;
238 }
239240// Potentially keep objects for their debuginfo.
241let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
242{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:242",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(242u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["preserve_objects",
"preserve_dwarf_objects"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&preserve_objects)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&preserve_dwarf_objects)
as &dyn Value))])
});
} else { ; }
};debug!(?preserve_objects, ?preserve_dwarf_objects);
243244for module in &compiled_modules.modules {
245 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
246 }
247 });
248}
249250// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
251// crate types must use the same dependency formats.
252pub fn each_linked_rlib(
253 info: &CrateInfo,
254 crate_type: Option<CrateType>,
255 f: &mut dyn FnMut(CrateNum, &Path),
256) -> Result<(), errors::LinkRlibError> {
257let fmts = if let Some(crate_type) = crate_type {
258let Some(fmts) = info.dependency_formats.get(&crate_type) else {
259return Err(errors::LinkRlibError::MissingFormat);
260 };
261262fmts263 } else {
264let mut dep_formats = info.dependency_formats.iter();
265let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
266if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
267return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
268 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
269 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
270 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
271 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
272 });
273 }
274list1275 };
276277let used_dep_crates = info.used_crates.iter();
278for &cnum in used_dep_crates {
279match fmts.get(cnum) {
280Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
281Some(_) => {}
282None => return Err(errors::LinkRlibError::MissingFormat),
283 }
284let crate_name = info.crate_name[&cnum];
285let used_crate_source = &info.used_crate_source[&cnum];
286if let Some(path) = &used_crate_source.rlib {
287 f(cnum, path);
288 } else if used_crate_source.rmeta.is_some() {
289return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
290 } else {
291return Err(errors::LinkRlibError::NotFound { crate_name });
292 }
293 }
294Ok(())
295}
296297/// Create an 'rlib'.
298///
299/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
300/// The rlib primarily contains the object file of the crate, but it also some of the object files
301/// from native libraries.
302fn link_rlib<'a>(
303 sess: &'a Session,
304 archive_builder_builder: &dyn ArchiveBuilderBuilder,
305 compiled_modules: &CompiledModules,
306 crate_info: &CrateInfo,
307 metadata: &EncodedMetadata,
308 flavor: RlibFlavor,
309 tmpdir: &MaybeTempDir,
310) -> Box<dyn ArchiveBuilder + 'a> {
311let mut ab = archive_builder_builder.new_archive_builder(sess);
312313// Pre-compute the list of Rust object filenames and materialize the rmeta-link
314 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
315 // placed immediately after metadata in the archive, so consumers can find
316 // it without iterating every archive member.
317let rust_object_files: Vec<String> = compiled_modules318 .modules
319 .iter()
320 .filter_map(|m| m.object.as_ref())
321 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
322 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
323 .collect();
324325let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
326let metadata_link = rmeta_link::RmetaLink { rust_object_files };
327let metadata_link_data = metadata_link.encode();
328let (wrapper, _) =
329create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
330Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
331 } else {
332None333 };
334335let trailing_metadata = match flavor {
336 RlibFlavor::Normal => {
337let (metadata, metadata_position) =
338create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
339let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
340match metadata_position {
341 MetadataPosition::First => {
342// Most of the time metadata in rlib files is wrapped in a "dummy" object
343 // file for the target platform so the rlib can be processed entirely by
344 // normal linkers for the platform. Sometimes this is not possible however.
345 // If it is possible however, placing the metadata object first improves
346 // performance of getting metadata from rlibs.
347ab.add_file(&metadata, ArchiveEntryKind::Other);
348// Place the rmeta-link member immediately after metadata so consumers
349 // can find it without iterating the whole archive.
350if let Some(file) = &metadata_link_file {
351ab.add_file(file, ArchiveEntryKind::Other);
352 }
353None354 }
355 MetadataPosition::Last => Some(metadata),
356 }
357 }
358359 RlibFlavor::StaticlibBase => None,
360 };
361362for m in &compiled_modules.modules {
363if let Some(obj) = m.object.as_ref() {
364 ab.add_file(obj, ArchiveEntryKind::RustObj);
365 }
366367if let Some(obj) = m.global_asm_object.as_ref() {
368 ab.add_file(obj, ArchiveEntryKind::RustObj);
369 }
370371if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
372 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
373 }
374 }
375376match flavor {
377 RlibFlavor::Normal => {}
378 RlibFlavor::StaticlibBase => {
379if let Some(m) = &compiled_modules.allocator_module {
380if let Some(obj) = &m.object {
381ab.add_file(obj, ArchiveEntryKind::RustObj);
382 }
383if let Some(obj) = &m.global_asm_object {
384ab.add_file(obj, ArchiveEntryKind::RustObj);
385 }
386 }
387 }
388 }
389390// Used if packed_bundled_libs flag enabled.
391let mut packed_bundled_libs = Vec::new();
392393// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
394 // we may not be configured to actually include a static library if we're
395 // adding it here. That's because later when we consume this rlib we'll
396 // decide whether we actually needed the static library or not.
397 //
398 // To do this "correctly" we'd need to keep track of which libraries added
399 // which object files to the archive. We don't do that here, however. The
400 // #[link(cfg(..))] feature is unstable, though, and only intended to get
401 // liblibc working. In that sense the check below just indicates that if
402 // there are any libraries we want to omit object files for at link time we
403 // just exclude all custom object files.
404 //
405 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
406 // feature then we'll need to figure out how to record what objects were
407 // loaded from the libraries found here and then encode that into the
408 // metadata of the rlib we're generating somehow.
409for lib in crate_info.used_libraries.iter() {
410let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
411continue;
412 };
413if flavor == RlibFlavor::Normal
414 && let Some(filename) = lib.filename
415 {
416let path = find_native_static_library(filename.as_str(), true, sess);
417let src = read(path)
418 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
419let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
420let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
421 packed_bundled_libs.push(wrapper_file);
422 } else {
423let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
424 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
425 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
426 });
427 }
428 }
429430// On Windows, we add the raw-dylib import libraries to the rlibs already.
431 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
432 // Instead, we add all raw-dylibs to the final link on ELF.
433if sess.target.is_like_windows {
434for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
435 sess,
436 archive_builder_builder,
437 crate_info.used_libraries.iter(),
438 tmpdir.as_ref(),
439true,
440 ) {
441 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
442 sess.dcx()
443 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
444 });
445 }
446 }
447448if let Some(trailing_metadata) = trailing_metadata {
449// Note that it is important that we add all of our non-object "magical
450 // files" *after* all of the object files in the archive. The reason for
451 // this is as follows:
452 //
453 // * When performing LTO, this archive will be modified to remove
454 // objects from above. The reason for this is described below.
455 //
456 // * When the system linker looks at an archive, it will attempt to
457 // determine the architecture of the archive in order to see whether its
458 // linkable.
459 //
460 // The algorithm for this detection is: iterate over the files in the
461 // archive. Skip magical SYMDEF names. Interpret the first file as an
462 // object file. Read architecture from the object file.
463 //
464 // * As one can probably see, if "metadata" and "foo.bc" were placed
465 // before all of the objects, then the architecture of this archive would
466 // not be correctly inferred once 'foo.o' is removed.
467 //
468 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
469 // file for the target platform so the rlib can be processed entirely by
470 // normal linkers for the platform. Sometimes this is not possible however.
471 //
472 // Basically, all this means is that this code should not move above the
473 // code above.
474ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
475// Place the rmeta-link member immediately after metadata so consumers can
476 // find it without iterating the whole archive.
477if let Some(file) = &metadata_link_file {
478ab.add_file(file, ArchiveEntryKind::Other);
479 }
480 }
481482// Add all bundled static native library dependencies.
483 // Archives added to the end of .rlib archive, see comment above for the reason.
484for lib in packed_bundled_libs {
485 ab.add_file(&lib, ArchiveEntryKind::Other)
486 }
487488ab489}
490491/// Create a static archive.
492///
493/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
494/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
495/// dependencies as well.
496///
497/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
498/// library dependencies that they're not linked in.
499///
500/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
501/// object file (and also don't prepare the archive with a metadata file).
502fn link_staticlib(
503 sess: &Session,
504 archive_builder_builder: &dyn ArchiveBuilderBuilder,
505 compiled_modules: &CompiledModules,
506 crate_info: &CrateInfo,
507 metadata: &EncodedMetadata,
508 out_filename: &Path,
509 tempdir: &MaybeTempDir,
510) {
511{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:511",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(511u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing staticlib to {0:?}",
out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing staticlib to {:?}", out_filename);
512let mut ab = link_rlib(
513sess,
514archive_builder_builder,
515compiled_modules,
516crate_info,
517metadata,
518 RlibFlavor::StaticlibBase,
519tempdir,
520 );
521let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
522523let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
524let lto = are_upstream_rust_objects_already_included(sess)
525 && !ignored_for_lto(sess, crate_info, cnum);
526527let native_libs = crate_info.native_libraries[&cnum].iter();
528let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
529let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
530531let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
532ab.add_archive(
533path,
534 AddArchiveKind::Rlib(&|fname: &str, entry_kind| {
535// Ignore metadata and rmeta-link files.
536if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
537return true;
538 }
539540// Don't include Rust objects if LTO is enabled.
541if lto && entry_kind == ArchiveEntryKind::RustObj {
542return true;
543 }
544545// Skip objects for bundled libs.
546if bundled_libs.contains(&Symbol::intern(fname)) {
547return true;
548 }
549550false
551}),
552 )
553 .unwrap();
554555archive_builder_builder556 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
557 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
558559for filename in relevant_libs.iter() {
560let joined = tempdir.as_ref().join(filename.as_str());
561let path = joined.as_path();
562 ab.add_archive(path, AddArchiveKind::Other).unwrap();
563 }
564565all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
566 });
567if let Err(e) = res {
568sess.dcx().emit_fatal(e);
569 }
570571let hide = sess.opts.unstable_opts.staticlib_hide_internal_symbols;
572let rename = sess.opts.unstable_opts.staticlib_rename_internal_symbols;
573574let exported_symbols = if hide || rename {
575if !#[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) {
576if hide {
577sess.dcx().emit_warn(errors::StaticlibHideInternalSymbolsUnsupported {
578 binary_format: sess.target.archive_format.to_string(),
579 });
580 }
581if rename {
582sess.dcx().emit_warn(errors::StaticlibRenameInternalSymbolsUnsupported {
583 binary_format: sess.target.archive_format.to_string(),
584 });
585 }
586None587 } else {
588crate_info589 .exported_symbols
590 .get(&CrateType::StaticLib)
591 .map(|symbols| symbols.iter().map(|(s, _)| s.clone()).collect())
592 }
593 } else {
594None595 };
596597let symbols = exported_symbols.map(|exported| ArchiveSymbols {
598exported,
599 rename_suffix: rename.then(|| crate_info.symbol_rename_suffix.clone()),
600hide,
601 });
602603ab.build(out_filename, symbols);
604605let crates = crate_info.used_crates.iter();
606607let fmts = crate_info608 .dependency_formats
609 .get(&CrateType::StaticLib)
610 .expect("no dependency formats for staticlib");
611612let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
613for &cnum in crates {
614let Some(Linkage::Dynamic) = fmts.get(cnum) else {
615continue;
616 };
617let crate_name = crate_info.crate_name[&cnum];
618let used_crate_source = &crate_info.used_crate_source[&cnum];
619if let Some(path) = &used_crate_source.dylib {
620 all_rust_dylibs.push(&**path);
621 } else if used_crate_source.rmeta.is_some() {
622 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
623 } else {
624 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
625 }
626 }
627628all_native_libs.extend_from_slice(&crate_info.used_libraries);
629630for print in &sess.opts.prints {
631if print.kind == PrintKind::NativeStaticLibs {
632 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
633 }
634 }
635}
636637/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
638/// DWARF package.
639fn link_dwarf_object(
640 sess: &Session,
641 compiled_modules: &CompiledModules,
642 crate_info: &CrateInfo,
643 executable_out_filename: &Path,
644) {
645let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
646dwp_out_filename.push(".dwp");
647{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:647",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(647u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["dwp_out_filename",
"executable_out_filename"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&dwp_out_filename)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&executable_out_filename)
as &dyn Value))])
});
} else { ; }
};debug!(?dwp_out_filename, ?executable_out_filename);
648649#[derive(#[automatically_derived]
impl<Relocations: ::core::default::Default> ::core::default::Default for
ThorinSession<Relocations> {
#[inline]
fn default() -> ThorinSession<Relocations> {
ThorinSession {
arena_data: ::core::default::Default::default(),
arena_mmap: ::core::default::Default::default(),
arena_relocations: ::core::default::Default::default(),
}
}
}Default)]
650struct ThorinSession<Relocations> {
651 arena_data: TypedArena<Vec<u8>>,
652 arena_mmap: TypedArena<Mmap>,
653 arena_relocations: TypedArena<Relocations>,
654 }
655656impl<Relocations> ThorinSession<Relocations> {
657fn alloc_mmap(&self, data: Mmap) -> &Mmap {
658&*self.arena_mmap.alloc(data)
659 }
660 }
661662impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
663fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
664&*self.arena_data.alloc(data)
665 }
666667fn alloc_relocation(&self, data: Relocations) -> &Relocations {
668&*self.arena_relocations.alloc(data)
669 }
670671fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
672let file = File::open(&path)?;
673let mmap = (unsafe { Mmap::map(file) })?;
674Ok(self.alloc_mmap(mmap))
675 }
676 }
677678match sess.time("run_thorin", || -> Result<(), thorin::Error> {
679let thorin_sess = ThorinSession::default();
680let mut package = thorin::DwarfPackage::new(&thorin_sess);
681682// Input objs contain .o/.dwo files from the current crate.
683match sess.opts.unstable_opts.split_dwarf_kind {
684 SplitDwarfKind::Single => {
685for m in &compiled_modules.modules {
686if let Some(input_obj) = &m.object {
687 package.add_input_object(input_obj)?;
688 }
689if let Some(input_obj) = &m.global_asm_object {
690 package.add_input_object(input_obj)?;
691 }
692 }
693 }
694 SplitDwarfKind::Split => {
695for input_obj in
696compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
697 {
698 package.add_input_object(input_obj)?;
699 }
700 }
701 }
702703// Input rlibs contain .o/.dwo files from dependencies.
704let input_rlibs = crate_info705 .used_crate_source
706 .items()
707 .filter_map(|(_, csource)| csource.rlib.as_ref())
708 .into_sorted_stable_ord();
709710for input_rlib in input_rlibs {
711{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:711",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(711u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["input_rlib"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&input_rlib)
as &dyn Value))])
});
} else { ; }
};debug!(?input_rlib);
712 package.add_input_object(input_rlib)?;
713 }
714715// Failing to read the referenced objects is expected for dependencies where the path in the
716 // executable will have been cleaned by Cargo, but the referenced objects will be contained
717 // within rlibs provided as inputs.
718 //
719 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
720 // found, but are provided explicitly above.
721 //
722 // Adding an executable is primarily done to make `thorin` check that all the referenced
723 // dwarf objects are found in the end.
724package.add_executable(
725 executable_out_filename,
726 thorin::MissingReferencedObjectBehaviour::Skip,
727 )?;
728729let output_stream = BufWriter::new(
730 OpenOptions::new()
731 .read(true)
732 .write(true)
733 .create(true)
734 .truncate(true)
735 .open(dwp_out_filename)?,
736 );
737let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
738 package.finish()?.emit(&mut output_stream)?;
739 output_stream.result()?;
740 output_stream.into_inner().flush()?;
741742Ok(())
743 }) {
744Ok(()) => {}
745Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
746 }
747}
748749#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for LinkerOutput
where G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
LinkerOutput { inner: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$inner}")));
;
diag.arg("inner", __binding_0);
diag
}
}
}
}
};Diagnostic)]
750#[diag("{$inner}")]
751/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
752/// end up with inconsistent languages within the same diagnostic.
753struct LinkerOutput {
754 inner: String,
755}
756757fn is_msvc_link_exe(sess: &Session) -> bool {
758let (linker_path, flavor) = linker_and_flavor(sess);
759sess.target.is_like_msvc
760 && flavor == LinkerFlavor::Msvc(Lld::No)
761// Match exactly "link.exe"
762&& linker_path.to_str() == Some("link.exe")
763}
764765fn is_macos_ld(sess: &Session) -> bool {
766let (_, flavor) = linker_and_flavor(sess);
767sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))768}
769770fn is_windows_gnu_ld(sess: &Session) -> bool {
771let (_, flavor) = linker_and_flavor(sess);
772sess.target.is_like_windows
773 && !sess.target.is_like_msvc
774 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))775 && sess.target.options.cfg_abi != CfgAbi::Llvm776}
777778fn is_windows_gnu_clang(sess: &Session) -> bool {
779let (_, flavor) = linker_and_flavor(sess);
780sess.target.is_like_windows
781 && !sess.target.is_like_msvc
782 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))783 && sess.target.options.cfg_abi == CfgAbi::Llvm784}
785786fn report_linker_output(
787 sess: &Session,
788 levels: CodegenLintLevelSpecs,
789 stdout: &[u8],
790 stderr: &[u8],
791) {
792let mut escaped_stderr = escape_string(&stderr);
793let mut escaped_stdout = escape_string(&stdout);
794let mut linker_info = String::new();
795796{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:796",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(796u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stderr:\n{0}",
&escaped_stderr) as &dyn Value))])
});
} else { ; }
};info!("linker stderr:\n{}", &escaped_stderr);
797{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:797",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(797u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stdout:\n{0}",
&escaped_stdout) as &dyn Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &escaped_stdout);
798799fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
800let mut output = String::new();
801if let Ok(str) = str::from_utf8(bytes) {
802{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:802",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(802u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("line: {0}",
str) as &dyn Value))])
});
} else { ; }
};info!("line: {str}");
803output = String::with_capacity(str.len());
804for line in str.lines() {
805 f(line.trim(), &mut output);
806 }
807 }
808escape_string(output.trim().as_bytes())
809 }
810811if is_msvc_link_exe(sess) {
812{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:812",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(812u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred MSVC link.exe")
as &dyn Value))])
});
} else { ; }
};info!("inferred MSVC link.exe");
813814escaped_stdout = for_each(&stdout, |line, output| {
815// Hide some progress messages from link.exe that we don't care about.
816 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
817 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
818 // missing, link.exe prints the path of the missing .exe followed by:
819let ilk_but_no_exe =
820"not found or not built by the last incremental link; performing full link";
821let trimmed = line.trim_start();
822if trimmed.starts_with("Creating library")
823 || trimmed.starts_with("Generating code")
824 || trimmed.starts_with("Finished generating code")
825 || trimmed.ends_with(ilk_but_no_exe)
826 {
827linker_info += line;
828linker_info += "\r\n";
829 } else {
830*output += line;
831*output += "\r\n"
832}
833 });
834 } else if is_macos_ld(sess) {
835{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:835",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(835u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred macOS LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred macOS LD");
836837// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
838let deployment_mismatch = |line: &str| {
839// ld64 (object files + dylibs) and ld_prime (object files only):
840(line.starts_with("ld: ")
841 && line.contains("was built for newer")
842 && line.contains("than being linked"))
843// ld_prime (Xcode 15+, dylibs only):
844|| (line.starts_with("ld: ")
845 && line.contains("building for")
846 && line.contains("but linking with")
847 && line.contains("which was built for newer version"))
848 };
849// FIXME: This is a real warning we would like to show, but it hits too many crates
850 // to want to turn it on immediately.
851let search_path = |line: &str| {
852line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
853 };
854escaped_stderr = for_each(&stderr, |line, output| {
855// This duplicate library warning is just not helpful at all.
856if line.starts_with("ld: warning: ignoring duplicate libraries: ")
857 || deployment_mismatch(line)
858 || search_path(line)
859 {
860linker_info += line;
861linker_info += "\n";
862 } else {
863*output += line;
864*output += "\n"
865}
866 });
867 } else if is_windows_gnu_ld(sess) {
868{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:868",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(868u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows GNU LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows GNU LD");
869870let mut saw_exclude_symbol = false;
871// See https://github.com/rust-lang/rust/issues/112368.
872 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
873let exclude_symbols = |line: &str| {
874line.starts_with("Warning: .drectve `-exclude-symbols:")
875 && line.ends_with("' unrecognized")
876 };
877escaped_stderr = for_each(&stderr, |line, output| {
878if exclude_symbols(line) {
879saw_exclude_symbol = true;
880linker_info += line;
881linker_info += "\n";
882 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
883linker_info += line;
884linker_info += "\n";
885 } else {
886*output += line;
887*output += "\n"
888}
889 });
890 } else if is_windows_gnu_clang(sess) {
891{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:891",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(891u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows Clang (GNU ABI)")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows Clang (GNU ABI)");
892escaped_stderr = for_each(&stderr, |line, output| {
893if line.contains("argument unused during compilation: '-nolibc'") {
894linker_info += line;
895linker_info += "\n";
896 } else {
897*output += line;
898*output += "\n"
899}
900 });
901 };
902903let lint_msg = |msg| {
904emit_lint_base(
905sess,
906LINKER_MESSAGES,
907levels.linker_messages,
908None,
909LinkerOutput { inner: msg },
910 );
911 };
912let lint_info = |msg| {
913emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
914 };
915916if !escaped_stderr.is_empty() {
917// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
918escaped_stderr =
919escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
920// Windows GNU LD prints uppercase Warning
921escaped_stderr = escaped_stderr922 .strip_prefix("Warning: ")
923 .unwrap_or(&escaped_stderr)
924 .replace(": warning: ", ": ");
925lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
926 }
927if !escaped_stdout.is_empty() {
928lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
929 }
930if !linker_info.is_empty() {
931lint_info(linker_info);
932 }
933}
934935/// Create a dynamic library or executable.
936///
937/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
938/// files as well.
939fn link_natively(
940 sess: &Session,
941 archive_builder_builder: &dyn ArchiveBuilderBuilder,
942 crate_type: CrateType,
943 out_filename: &Path,
944 compiled_modules: &CompiledModules,
945 crate_info: &CrateInfo,
946 metadata: &EncodedMetadata,
947 tmpdir: &Path,
948 codegen_backend: &'static str,
949) {
950{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:950",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(950u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing {0:?} to {1:?}",
crate_type, out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
951let (linker_path, flavor) = linker_and_flavor(sess);
952let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
953954// On AIX, we ship all libraries as .a big_af archive
955 // the expected format is lib<name>.a(libname.so) for the actual
956 // dynamic library. So we link to a temporary .so file to be archived
957 // at the final out_filename location
958let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
959let archive_member =
960should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
961let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
962963let mut cmd = linker_with_args(
964&linker_path,
965flavor,
966sess,
967archive_builder_builder,
968crate_type,
969tmpdir,
970temp_filename,
971compiled_modules,
972crate_info,
973metadata,
974self_contained_components,
975codegen_backend,
976 );
977978 linker::disable_localization(&mut cmd);
979980for (k, v) in sess.target.link_env.as_ref() {
981 cmd.env(k.as_ref(), v.as_ref());
982 }
983for k in sess.target.link_env_remove.as_ref() {
984 cmd.env_remove(k.as_ref());
985 }
986987for print in &sess.opts.prints {
988if print.kind == PrintKind::LinkArgs {
989let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
990 print.out.overwrite(&content, sess);
991 }
992 }
993994// May have not found libraries in the right formats.
995sess.dcx().abort_if_errors();
996997// Invoke the system linker
998{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:998",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(998u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
999let unknown_arg_regex =
1000Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
1001let mut prog;
1002loop {
1003prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
1004let Ok(ref output) = progelse {
1005break;
1006 };
1007if output.status.success() {
1008break;
1009 }
1010let mut out = output.stderr.clone();
1011out.extend(&output.stdout);
1012let out = String::from_utf8_lossy(&out);
10131014// Check to see if the link failed with an error message that indicates it
1015 // doesn't recognize the -no-pie option. If so, re-perform the link step
1016 // without it. This is safe because if the linker doesn't support -no-pie
1017 // then it should not default to linking executables as pie. Different
1018 // versions of gcc seem to use different quotes in the error message so
1019 // don't check for them.
1020if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1021 && unknown_arg_regex.is_match(&out)
1022 && out.contains("-no-pie")
1023 && cmd.get_args().iter().any(|e| e == "-no-pie")
1024 {
1025{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1025",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1025u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1026{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1026",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1026u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Linker does not support -no-pie command line option. Retrying without.")
as &dyn Value))])
});
} else { ; }
};warn!("Linker does not support -no-pie command line option. Retrying without.");
1027for arg in cmd.take_args() {
1028if arg != "-no-pie" {
1029 cmd.arg(arg);
1030 }
1031 }
1032{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1032",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1032u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1033continue;
1034 }
10351036// Check if linking failed with an error message that indicates the driver didn't recognize
1037 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1038 // to spawn multiple instances on the happy path to do version checking, and ensures things
1039 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1040 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1041if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1042 && unknown_arg_regex.is_match(&out)
1043 && out.contains("-fuse-ld=lld")
1044 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
1045 {
1046{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1046",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1046u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1047{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1047",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1047u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.")
as &dyn Value))])
});
} else { ; }
};info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
1048for arg in cmd.take_args() {
1049if arg.to_string_lossy() != "-fuse-ld=lld" {
1050 cmd.arg(arg);
1051 }
1052 }
1053{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1053",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1053u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1054continue;
1055 }
10561057// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1058 // Fallback from '-static-pie' to '-static' in that case.
1059if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1060 && unknown_arg_regex.is_match(&out)
1061 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1062 && cmd.get_args().iter().any(|e| e == "-static-pie")
1063 {
1064{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1064",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1064u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1065{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1065",
"rustc_codegen_ssa::back::link", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1065u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Linker does not support -static-pie command line option. Retrying with -static instead.")
as &dyn Value))])
});
} else { ; }
};warn!(
1066"Linker does not support -static-pie command line option. Retrying with -static instead."
1067);
1068// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1069let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1070let opts = &sess.target;
1071let pre_objects = if self_contained_crt_objects {
1072&opts.pre_link_objects_self_contained
1073 } else {
1074&opts.pre_link_objects
1075 };
1076let post_objects = if self_contained_crt_objects {
1077&opts.post_link_objects_self_contained
1078 } else {
1079&opts.post_link_objects
1080 };
1081let get_objects = |objects: &CrtObjects, kind| {
1082objects1083 .get(&kind)
1084 .iter()
1085 .copied()
1086 .flatten()
1087 .map(|obj| {
1088get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1089 })
1090 .collect::<Vec<_>>()
1091 };
1092let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1093let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1094let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1095let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1096// Assume that we know insertion positions for the replacement arguments from replaced
1097 // arguments, which is true for all supported targets.
1098if !(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());
1099if !(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());
1100for arg in cmd.take_args() {
1101if arg == "-static-pie" {
1102// Replace the output kind.
1103cmd.arg("-static");
1104 } else if pre_objects_static_pie.contains(&arg) {
1105// Replace the pre-link objects (replace the first and remove the rest).
1106cmd.args(mem::take(&mut pre_objects_static));
1107 } else if post_objects_static_pie.contains(&arg) {
1108// Replace the post-link objects (replace the first and remove the rest).
1109cmd.args(mem::take(&mut post_objects_static));
1110 } else {
1111 cmd.arg(arg);
1112 }
1113 }
1114{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1114",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1114u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
1115continue;
1116 }
11171118break;
1119 }
11201121match prog {
1122Ok(prog) => {
1123if !prog.status.success() {
1124let mut output = prog.stderr.clone();
1125output.extend_from_slice(&prog.stdout);
1126let escaped_output = escape_linker_output(&output, flavor);
1127let err = errors::LinkingFailed {
1128 linker_path: &linker_path,
1129 exit_status: prog.status,
1130 command: cmd,
1131escaped_output,
1132 verbose: sess.opts.verbose,
1133 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1134 };
1135sess.dcx().emit_err(err);
1136// If MSVC's `link.exe` was expected but the return code
1137 // is not a Microsoft LNK error then suggest a way to fix or
1138 // install the Visual Studio build tools.
1139if let Some(code) = prog.status.code() {
1140// All Microsoft `link.exe` linking ror codes are
1141 // four digit numbers in the range 1000 to 9999 inclusive
1142if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1143let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1144let has_linker =
1145 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1146 .is_some();
11471148sess.dcx().emit_note(errors::LinkExeUnexpectedError);
11491150// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1151 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1152const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1153if code == STATUS_STACK_BUFFER_OVERRUN {
1154sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1155 }
11561157if is_vs_installed && has_linker {
1158// the linker is broken
1159sess.dcx().emit_note(errors::RepairVSBuildTools);
1160sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1161 } else if is_vs_installed {
1162// the linker is not installed
1163sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1164 } else {
1165// visual studio is not installed
1166sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1167 }
1168 }
1169 }
11701171sess.dcx().abort_if_errors();
1172 }
11731174{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1174",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1174u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("reporting linker output: flavor={0:?}",
flavor) as &dyn Value))])
});
} else { ; }
};info!("reporting linker output: flavor={flavor:?}");
1175report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1176 }
1177Err(e) => {
1178let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11791180let err = if linker_not_found {
1181sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1182 } else {
1183sess.dcx().emit_err(errors::UnableToExeLinker {
1184linker_path,
1185 error: e,
1186 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1187 })
1188 };
11891190if sess.target.is_like_msvc && linker_not_found {
1191sess.dcx().emit_note(errors::MsvcMissingLinker);
1192sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1193sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1194 }
1195err.raise_fatal();
1196 }
1197 }
11981199match sess.split_debuginfo() {
1200// If split debug information is disabled or located in individual files
1201 // there's nothing to do here.
1202SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
12031204// If packed split-debuginfo is requested, but the final compilation
1205 // doesn't actually have any debug information, then we skip this step.
1206SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
12071208// On macOS the external `dsymutil` tool is used to create the packed
1209 // debug information. Note that this will read debug information from
1210 // the objects on the filesystem which we'll clean up later.
1211SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1212let prog = Command::new("dsymutil").arg(out_filename).output();
1213match prog {
1214Ok(prog) => {
1215if !prog.status.success() {
1216let mut output = prog.stderr.clone();
1217output.extend_from_slice(&prog.stdout);
1218sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1219 status: prog.status,
1220 output: escape_string(&output),
1221 });
1222 }
1223 }
1224Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1225 }
1226 }
12271228// On MSVC packed debug information is produced by the linker itself so
1229 // there's no need to do anything else here.
1230SplitDebuginfo::Packedif sess.target.is_like_windows => {}
12311232// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1233 //
1234 // We cannot rely on the .o paths in the executable because they may have been
1235 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1236 // the .o/.dwo paths explicitly.
1237SplitDebuginfo::Packed => {
1238link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1239 }
1240 }
12411242let strip = sess.opts.cg.strip;
12431244if sess.target.is_like_darwin {
1245let stripcmd = "rust-objcopy";
1246match (strip, crate_type) {
1247 (Strip::Debuginfo, _) => {
1248strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1249 }
12501251// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1252(
1253 Strip::Symbols,
1254 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1255 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1256 (Strip::Symbols, _) => {
1257strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1258 }
1259 (Strip::None, _) => {}
1260 }
1261 }
12621263if sess.target.is_like_solaris {
1264// Many illumos systems will have both the native 'strip' utility and
1265 // the GNU one. Use the native version explicitly and do not rely on
1266 // what's in the path.
1267 //
1268 // If cross-compiling and there is not a native version, then use
1269 // `llvm-strip` and hope.
1270let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1271match strip {
1272// Always preserve the symbol table (-x).
1273Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1274// Strip::Symbols is handled via the --strip-all linker option.
1275Strip::Symbols => {}
1276 Strip::None => {}
1277 }
1278 }
12791280if sess.target.is_like_aix {
1281// `llvm-strip` doesn't work for AIX - their strip must be used.
1282if !sess.host.is_like_aix {
1283sess.dcx().emit_warn(errors::AixStripNotUsed);
1284 }
1285let stripcmd = "/usr/bin/strip";
1286match strip {
1287 Strip::Debuginfo => {
1288// FIXME: AIX's strip utility only offers option to strip line number information.
1289strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1290 }
1291 Strip::Symbols => {
1292// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1293strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1294 }
1295 Strip::None => {}
1296 }
1297 }
12981299if should_archive {
1300let mut ab = archive_builder_builder.new_archive_builder(sess);
1301ab.add_file(temp_filename, ArchiveEntryKind::Other);
1302ab.build(out_filename, None);
1303 }
1304}
13051306fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1307let mut cmd = Command::new(util);
1308cmd.args(options);
13091310let mut new_path = sess.get_tools_search_paths(false);
1311if let Some(path) = env::var_os("PATH") {
1312new_path.extend(env::split_paths(&path));
1313 }
1314cmd.env("PATH", env::join_paths(new_path).unwrap());
13151316let prog = cmd.arg(out_filename).output();
1317match prog {
1318Ok(prog) => {
1319if !prog.status.success() {
1320let mut output = prog.stderr.clone();
1321output.extend_from_slice(&prog.stdout);
1322sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1323util,
1324 status: prog.status,
1325 output: escape_string(&output),
1326 });
1327 }
1328 }
1329Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1330 }
1331}
13321333fn escape_string(s: &[u8]) -> String {
1334match str::from_utf8(s) {
1335Ok(s) => s.to_owned(),
1336Err(_) => ::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()),
1337 }
1338}
13391340#[cfg(not(windows))]
1341fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1342escape_string(s)
1343}
13441345/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1346/// then try to convert the string from the OEM encoding.
1347#[cfg(windows)]
1348fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1349// This only applies to the actual MSVC linker.
1350if flavour != LinkerFlavor::Msvc(Lld::No) {
1351return escape_string(s);
1352 }
1353match str::from_utf8(s) {
1354Ok(s) => return s.to_owned(),
1355Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1356Some(s) => s,
1357// The string is not UTF-8 and isn't valid for the OEM code page
1358None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1359 },
1360 }
1361}
13621363/// Wrappers around the Windows API.
1364#[cfg(windows)]
1365mod win {
1366use windows::Win32::Globalization::{
1367 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1368 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1369 };
13701371/// Get the Windows system OEM code page. This is most notably the code page
1372 /// used for link.exe's output.
1373pub(super) fn oem_code_page() -> u32 {
1374unsafe {
1375let mut cp: u32 = 0;
1376// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1377 // But the API requires us to pass the data as though it's a [u16] string.
1378let len = size_of::<u32>() / size_of::<u16>();
1379let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1380let len_written = GetLocaleInfoEx(
1381 LOCALE_NAME_SYSTEM_DEFAULT,
1382 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1383Some(data),
1384 );
1385if len_written as usize == len { cp } else { CP_OEMCP }
1386 }
1387 }
1388/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1389 /// The string does not need to be null terminated.
1390 ///
1391 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1392 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1393 ///
1394 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1395 /// any invalid bytes for the expected encoding.
1396pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1397// `MultiByteToWideChar` requires a length to be a "positive integer".
1398if s.len() > isize::MAX as usize {
1399return None;
1400 }
1401// Error if the string is not valid for the expected code page.
1402let flags = MB_ERR_INVALID_CHARS;
1403// Call MultiByteToWideChar twice.
1404 // First to calculate the length then to convert the string.
1405let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1406if len > 0 {
1407let mut utf16 = vec![0; len as usize];
1408 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1409if len > 0 {
1410return utf16.get(..len as usize).map(String::from_utf16_lossy);
1411 }
1412 }
1413None
1414}
1415}
14161417fn add_sanitizer_libraries(
1418 sess: &Session,
1419 flavor: LinkerFlavor,
1420 crate_type: CrateType,
1421 linker: &mut dyn Linker,
1422) {
1423if sess.target.is_like_android {
1424// Sanitizer runtime libraries are provided dynamically on Android
1425 // targets.
1426return;
1427 }
14281429if sess.opts.unstable_opts.external_clangrt {
1430// Linking against in-tree sanitizer runtimes is disabled via
1431 // `-Z external-clangrt`
1432return;
1433 }
14341435if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1436return;
1437 }
14381439// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1440 // which should be linked to both executables and dynamic libraries.
1441 // Everywhere else the runtimes are currently distributed as static
1442 // libraries which should be linked to executables only.
1443if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1444 crate_type,
1445 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1446 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1447 {
1448return;
1449 }
14501451let sanitizer = sess.sanitizers();
1452if sanitizer.contains(SanitizerSet::ADDRESS) {
1453link_sanitizer_runtime(sess, flavor, linker, "asan");
1454 }
1455if sanitizer.contains(SanitizerSet::DATAFLOW) {
1456link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1457 }
1458if sanitizer.contains(SanitizerSet::LEAK)
1459 && !sanitizer.contains(SanitizerSet::ADDRESS)
1460 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1461 {
1462link_sanitizer_runtime(sess, flavor, linker, "lsan");
1463 }
1464if sanitizer.contains(SanitizerSet::MEMORY) {
1465link_sanitizer_runtime(sess, flavor, linker, "msan");
1466 }
1467if sanitizer.contains(SanitizerSet::THREAD) {
1468link_sanitizer_runtime(sess, flavor, linker, "tsan");
1469 }
1470if sanitizer.contains(SanitizerSet::HWADDRESS) {
1471link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1472 }
1473if sanitizer.contains(SanitizerSet::SAFESTACK) {
1474link_sanitizer_runtime(sess, flavor, linker, "safestack");
1475 }
1476if sanitizer.contains(SanitizerSet::REALTIME) {
1477link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1478 }
1479}
14801481fn link_sanitizer_runtime(
1482 sess: &Session,
1483 flavor: LinkerFlavor,
1484 linker: &mut dyn Linker,
1485 name: &str,
1486) {
1487fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1488let path = sess.target_tlib_path.dir.join(filename);
1489if path.exists() {
1490sess.target_tlib_path.dir.clone()
1491 } else {
1492 filesearch::make_target_lib_path(
1493&sess.opts.sysroot.default,
1494sess.opts.target_triple.tuple(),
1495 )
1496 }
1497 }
14981499let channel =
1500::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();
15011502if sess.target.is_like_darwin {
1503// On Apple platforms, the sanitizer is always built as a dylib, and
1504 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1505 // rpath to the library as well (the rpath should be absolute, see
1506 // PR #41352 for details).
1507let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1508let path = find_sanitizer_runtime(sess, &filename);
1509let rpath = path.to_str().expect("non-utf8 component in path");
1510linker.link_args(&["-rpath", rpath]);
1511linker.link_dylib_by_name(&filename, false, true);
1512 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1513// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1514 // compatible ASAN library.
1515linker.link_arg("/INFERASANLIBS");
1516 } else {
1517let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1518let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1519linker.link_staticlib_by_path(&path, true);
1520 }
1521}
15221523/// Returns a boolean indicating whether the specified crate should be ignored
1524/// during LTO.
1525///
1526/// Crates ignored during LTO are not lumped together in the "massive object
1527/// file" that we create and are linked in their normal rlib states. See
1528/// comments below for what crates do not participate in LTO.
1529///
1530/// It's unusual for a crate to not participate in LTO. Typically only
1531/// compiler-specific and unstable crates have a reason to not participate in
1532/// LTO.
1533pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1534// If our target enables builtin function lowering in LLVM then the
1535 // crates providing these functions don't participate in LTO (e.g.
1536 // no_builtins or compiler builtins crates).
1537!sess.target.no_builtins
1538 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1539}
15401541/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1542pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1543fn infer_from(
1544 sess: &Session,
1545 linker: Option<PathBuf>,
1546 flavor: Option<LinkerFlavor>,
1547 features: LinkerFeaturesCli,
1548 ) -> Option<(PathBuf, LinkerFlavor)> {
1549let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1550match (linker, flavor) {
1551 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1552// only the linker flavor is known; use the default linker for the selected flavor
1553(None, Some(flavor)) => Some((
1554PathBuf::from(match flavor {
1555 LinkerFlavor::Gnu(Cc::Yes, _)
1556 | LinkerFlavor::Darwin(Cc::Yes, _)
1557 | LinkerFlavor::WasmLld(Cc::Yes)
1558 | LinkerFlavor::Unix(Cc::Yes) => {
1559if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1560// On historical Solaris systems, "cc" may have
1561 // been Sun Studio, which is not flag-compatible
1562 // with "gcc". This history casts a long shadow,
1563 // and many modern illumos distributions today
1564 // ship GCC as "gcc" without also making it
1565 // available as "cc".
1566"gcc"
1567} else {
1568"cc"
1569}
1570 }
1571 LinkerFlavor::Gnu(_, Lld::Yes)
1572 | LinkerFlavor::Darwin(_, Lld::Yes)
1573 | LinkerFlavor::WasmLld(..)
1574 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1575 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1576"ld"
1577}
1578 LinkerFlavor::Msvc(..) => "link.exe",
1579 LinkerFlavor::EmCc => {
1580if falsecfg!(windows) {
1581"emcc.bat"
1582} else {
1583"emcc"
1584}
1585 }
1586 LinkerFlavor::Bpf => "bpf-linker",
1587 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1588 }),
1589flavor,
1590 )),
1591 (Some(linker), None) => {
1592let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1593sess.dcx().emit_fatal(errors::LinkerFileStem);
1594 });
1595let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1596let flavor = adjust_flavor_to_features(flavor, features);
1597Some((linker, flavor))
1598 }
1599 (None, None) => None,
1600 }
1601 }
16021603// While linker flavors and linker features are isomorphic (and thus targets don't need to
1604 // define features separately), we use the flavor as the root piece of data and have the
1605 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1606 // both yet.
1607fn adjust_flavor_to_features(
1608 flavor: LinkerFlavor,
1609 features: LinkerFeaturesCli,
1610 ) -> LinkerFlavor {
1611// Note: a linker feature cannot be both enabled and disabled on the CLI.
1612if features.enabled.contains(LinkerFeatures::LLD) {
1613flavor.with_lld_enabled()
1614 } else if features.disabled.contains(LinkerFeatures::LLD) {
1615flavor.with_lld_disabled()
1616 } else {
1617flavor1618 }
1619 }
16201621let features = sess.opts.cg.linker_features;
16221623// linker and linker flavor specified via command line have precedence over what the target
1624 // specification specifies
1625let linker_flavor = match sess.opts.cg.linker_flavor {
1626// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1627Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1628// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1629linker_flavor => {
1630linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1631 }
1632 };
1633if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1634return ret;
1635 }
16361637if let Some(ret) = infer_from(
1638sess,
1639sess.target.linker.as_deref().map(PathBuf::from),
1640Some(sess.target.linker_flavor),
1641features,
1642 ) {
1643return ret;
1644 }
16451646::rustc_middle::util::bug::bug_fmt(format_args!("Not enough information provided to determine how to invoke the linker"));bug!("Not enough information provided to determine how to invoke the linker");
1647}
16481649/// Returns a pair of boolean indicating whether we should preserve the object and
1650/// dwarf object files on the filesystem for their debug information. This is often
1651/// useful with split-dwarf like schemes.
1652fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1653// If the objects don't have debuginfo there's nothing to preserve.
1654if sess.opts.debuginfo == config::DebugInfo::None {
1655return (false, false);
1656 }
16571658match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1659// If there is no split debuginfo then do not preserve objects.
1660(SplitDebuginfo::Off, _) => (false, false),
1661// If there is packed split debuginfo, then the debuginfo in the objects
1662 // has been packaged and the objects can be deleted.
1663(SplitDebuginfo::Packed, _) => (false, false),
1664// If there is unpacked split debuginfo and the current target can not use
1665 // split dwarf, then keep objects.
1666(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1667// If there is unpacked split debuginfo and the target can use split dwarf, then
1668 // keep the object containing that debuginfo (whether that is an object file or
1669 // dwarf object file depends on the split dwarf kind).
1670(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1671 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1672 }
1673}
16741675#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for RlibFlavor {
#[inline]
fn eq(&self, other: &RlibFlavor) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1676enum RlibFlavor {
1677 Normal,
1678 StaticlibBase,
1679}
16801681fn print_native_static_libs(
1682 sess: &Session,
1683 out: &OutFileName,
1684 all_native_libs: &[NativeLib],
1685 all_rust_dylibs: &[&Path],
1686) {
1687let mut lib_args: Vec<_> = all_native_libs1688 .iter()
1689 .filter(|l| relevant_lib(sess, l))
1690 .filter_map(|lib| {
1691let name = lib.name;
1692match lib.kind {
1693 NativeLibKind::Static { bundle: Some(false), .. }
1694 | NativeLibKind::Dylib { .. }
1695 | NativeLibKind::Unspecified => {
1696let verbatim = lib.verbatim;
1697if sess.target.is_like_msvc {
1698let (prefix, suffix) = sess.staticlib_components(verbatim);
1699Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1700 } else if sess.target.linker_flavor.is_gnu() {
1701Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1702 } else {
1703Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1704 }
1705 }
1706 NativeLibKind::Framework { .. } => {
1707// ld-only syntax, since there are no frameworks in MSVC
1708Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1709 }
1710// These are included, no need to print them
1711NativeLibKind::Static { bundle: None | Some(true), .. }
1712 | NativeLibKind::LinkArg1713 | NativeLibKind::WasmImportModule1714 | NativeLibKind::RawDylib { .. } => None,
1715 }
1716 })
1717// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1718.dedup()
1719 .collect();
1720for path in all_rust_dylibs {
1721// FIXME deduplicate with add_dynamic_crate
17221723 // Just need to tell the linker about where the library lives and
1724 // what its name is
1725let parent = path.parent();
1726if let Some(dir) = parent {
1727let dir = fix_windows_verbatim_for_gcc(dir);
1728if sess.target.is_like_msvc {
1729let mut arg = String::from("/LIBPATH:");
1730 arg.push_str(&dir.display().to_string());
1731 lib_args.push(arg);
1732 } else {
1733 lib_args.push("-L".to_owned());
1734 lib_args.push(dir.display().to_string());
1735 }
1736 }
1737let stem = path.file_stem().unwrap().to_str().unwrap();
1738// Convert library file-stem into a cc -l argument.
1739let lib = if let Some(lib) = stem.strip_prefix("lib")
1740 && !sess.target.is_like_windows
1741 {
1742 lib
1743 } else {
1744 stem
1745 };
1746let path = parent.unwrap_or_else(|| Path::new(""));
1747if sess.target.is_like_msvc {
1748// When producing a dll, the MSVC linker may not actually emit a
1749 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1750 // check to see if the file is there and just omit linking to it if it's
1751 // not present.
1752let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1753if path.join(&name).exists() {
1754 lib_args.push(name);
1755 }
1756 } else {
1757 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1758 }
1759 }
17601761match out {
1762 OutFileName::Real(path) => {
1763out.overwrite(&lib_args.join(" "), sess);
1764sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1765 }
1766 OutFileName::Stdout => {
1767sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1768// Prefix for greppability
1769 // Note: This must not be translated as tools are allowed to depend on this exact string.
1770sess.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(" ")));
1771 }
1772 }
1773}
17741775fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1776let file_path = sess.target_tlib_path.dir.join(name);
1777if file_path.exists() {
1778return file_path;
1779 }
1780// Special directory with objects used only in self-contained linkage mode
1781if self_contained {
1782let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1783if file_path.exists() {
1784return file_path;
1785 }
1786 }
1787for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1788let file_path = search_path.dir.join(name);
1789if file_path.exists() {
1790return file_path;
1791 }
1792 }
1793PathBuf::from(name)
1794}
17951796fn exec_linker(
1797 sess: &Session,
1798 cmd: &Command,
1799 out_filename: &Path,
1800 flavor: LinkerFlavor,
1801 tmpdir: &Path,
1802) -> io::Result<Output> {
1803// When attempting to spawn the linker we run a risk of blowing out the
1804 // size limits for spawning a new process with respect to the arguments
1805 // we pass on the command line.
1806 //
1807 // Here we attempt to handle errors from the OS saying "your list of
1808 // arguments is too big" by reinvoking the linker again with an `@`-file
1809 // that contains all the arguments (aka 'response' files).
1810 // The theory is that this is then accepted on all linkers and the linker
1811 // will read all its options out of there instead of looking at the command line.
1812if !cmd.very_likely_to_exceed_some_spawn_limit() {
1813match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1814Ok(child) => {
1815let output = child.wait_with_output();
1816 flush_linked_file(&output, out_filename)?;
1817return output;
1818 }
1819Err(ref e) if command_line_too_big(e) => {
1820{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1820",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1820u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("command line to linker was too big: {0}",
e) as &dyn Value))])
});
} else { ; }
};info!("command line to linker was too big: {}", e);
1821 }
1822Err(e) => return Err(e),
1823 }
1824 }
18251826{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1826",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1826u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("falling back to passing arguments to linker via an @-file")
as &dyn Value))])
});
} else { ; }
};info!("falling back to passing arguments to linker via an @-file");
1827let mut cmd2 = cmd.clone();
1828let mut args = String::new();
1829for arg in cmd2.take_args() {
1830 args.push_str(
1831&Escape {
1832 arg: arg.to_str().unwrap(),
1833// Windows-style escaping for @-files is used by
1834 // - all linkers targeting MSVC-like targets, including LLD
1835 // - all LLD flavors running on Windows hosts
1836 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1837is_like_msvc: sess.target.is_like_msvc
1838 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1839 }
1840 .to_string(),
1841 );
1842 args.push('\n');
1843 }
1844let file = tmpdir.join("linker-arguments");
1845let bytes = if sess.target.is_like_msvc {
1846let mut out = Vec::with_capacity((1 + args.len()) * 2);
1847// start the stream with a UTF-16 BOM
1848for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1849// encode in little endian
1850out.push(c as u8);
1851 out.push((c >> 8) as u8);
1852 }
1853out1854 } else {
1855args.into_bytes()
1856 };
1857 fs::write(&file, &bytes)?;
1858cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1859{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:1859",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(1859u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoking linker {0:?}",
cmd2) as &dyn Value))])
});
} else { ; }
};info!("invoking linker {:?}", cmd2);
1860let output = cmd2.output();
1861 flush_linked_file(&output, out_filename)?;
1862return output;
18631864#[cfg(not(windows))]
1865fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1866Ok(())
1867 }
18681869#[cfg(windows)]
1870fn flush_linked_file(
1871 command_output: &io::Result<Output>,
1872 out_filename: &Path,
1873 ) -> io::Result<()> {
1874// On Windows, under high I/O load, output buffers are sometimes not flushed,
1875 // even long after process exit, causing nasty, non-reproducible output bugs.
1876 //
1877 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1878 //
1879 // А full writeup of the original Chrome bug can be found at
1880 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18811882if let &Ok(ref out) = command_output {
1883if out.status.success() {
1884if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1885 of.sync_all()?;
1886 }
1887 }
1888 }
18891890Ok(())
1891 }
18921893#[cfg(unix)]
1894fn command_line_too_big(err: &io::Error) -> bool {
1895err.raw_os_error() == Some(::libc::E2BIG)
1896 }
18971898#[cfg(windows)]
1899fn command_line_too_big(err: &io::Error) -> bool {
1900const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1901 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1902 }
19031904#[cfg(not(any(unix, windows)))]
1905fn command_line_too_big(_: &io::Error) -> bool {
1906false
1907}
19081909struct Escape<'a> {
1910 arg: &'a str,
1911 is_like_msvc: bool,
1912 }
19131914impl<'a> fmt::Displayfor Escape<'a> {
1915fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1916if self.is_like_msvc {
1917// This is "documented" at
1918 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1919 //
1920 // Unfortunately there's not a great specification of the
1921 // syntax I could find online (at least) but some local
1922 // testing showed that this seemed sufficient-ish to catch
1923 // at least a few edge cases.
1924f.write_fmt(format_args!("\""))write!(f, "\"")?;
1925for c in self.arg.chars() {
1926match c {
1927'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1928 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1929 }
1930 }
1931f.write_fmt(format_args!("\""))write!(f, "\"")?;
1932 } else {
1933// This is documented at https://linux.die.net/man/1/ld, namely:
1934 //
1935 // > Options in file are separated by whitespace. A whitespace
1936 // > character may be included in an option by surrounding the
1937 // > entire option in either single or double quotes. Any
1938 // > character (including a backslash) may be included by
1939 // > prefixing the character to be included with a backslash.
1940 //
1941 // We put an argument on each line, so all we need to do is
1942 // ensure the line is interpreted as one whole argument.
1943for c in self.arg.chars() {
1944match c {
1945'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1946 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1947 }
1948 }
1949 }
1950Ok(())
1951 }
1952 }
1953}
19541955fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1956let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1957 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1958 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1959 LinkOutputKind::DynamicPicExe1960 }
1961 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1962 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1963 LinkOutputKind::StaticPicExe1964 }
1965 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1966 (_, true, _) => LinkOutputKind::StaticDylib,
1967 (_, false, _) => LinkOutputKind::DynamicDylib,
1968 };
19691970// Adjust the output kind to target capabilities.
1971let opts = &sess.target;
1972let pic_exe_supported = opts.position_independent_executables;
1973let static_pic_exe_supported = opts.static_position_independent_executables;
1974let static_dylib_supported = opts.crt_static_allows_dylibs;
1975match kind {
1976 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1977 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1978 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1979_ => kind,
1980 }
1981}
19821983// Returns true if linker is located within sysroot
1984fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1985let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1986linker.with_extension("exe")
1987 } else {
1988linker.to_path_buf()
1989 };
1990for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1991let full_path = dir.join(&linker_with_extension);
1992// If linker comes from sysroot assume self-contained mode
1993if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1994return false;
1995 }
1996 }
1997true
1998}
19992000/// Various toolchain components used during linking are used from rustc distribution
2001/// instead of being found somewhere on the host system.
2002/// We only provide such support for a very limited number of targets.
2003fn self_contained_components(
2004 sess: &Session,
2005 crate_type: CrateType,
2006 linker: &Path,
2007) -> LinkSelfContainedComponents {
2008// Turn the backwards compatible bool values for `self_contained` into fully inferred
2009 // `LinkSelfContainedComponents`.
2010let self_contained =
2011if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
2012// Emit an error if the user requested self-contained mode on the CLI but the target
2013 // explicitly refuses it.
2014if sess.target.link_self_contained.is_disabled() {
2015sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
2016 }
2017self_contained2018 } else {
2019match sess.target.link_self_contained {
2020 LinkSelfContainedDefault::False => false,
2021 LinkSelfContainedDefault::True => true,
20222023 LinkSelfContainedDefault::WithComponents(components) => {
2024// For target specs with explicitly enabled components, we can return them
2025 // directly.
2026return components;
2027 }
20282029// FIXME: Find a better heuristic for "native musl toolchain is available",
2030 // based on host and linker path, for example.
2031 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2032LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2033 LinkSelfContainedDefault::InferredForMingw => {
2034sess.host == sess.target
2035 && sess.target.cfg_abi != CfgAbi::Uwp2036 && detect_self_contained_mingw(sess, linker)
2037 }
2038 }
2039 };
2040if self_contained {
2041LinkSelfContainedComponents::all()
2042 } else {
2043LinkSelfContainedComponents::empty()
2044 }
2045}
20462047/// Add pre-link object files defined by the target spec.
2048fn add_pre_link_objects(
2049 cmd: &mut dyn Linker,
2050 sess: &Session,
2051 flavor: LinkerFlavor,
2052 link_output_kind: LinkOutputKind,
2053 self_contained: bool,
2054) {
2055// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2056 // so Fuchsia has to be special-cased.
2057let opts = &sess.target;
2058let empty = Default::default();
2059let objects = if self_contained {
2060&opts.pre_link_objects_self_contained
2061 } 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, _))) {
2062&opts.pre_link_objects
2063 } else {
2064&empty2065 };
2066for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2067 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2068 }
2069}
20702071/// Add post-link object files defined by the target spec.
2072fn add_post_link_objects(
2073 cmd: &mut dyn Linker,
2074 sess: &Session,
2075 link_output_kind: LinkOutputKind,
2076 self_contained: bool,
2077) {
2078let objects = if self_contained {
2079&sess.target.post_link_objects_self_contained
2080 } else {
2081&sess.target.post_link_objects
2082 };
2083for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2084 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2085 }
2086}
20872088/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2089/// FIXME: Determine where exactly these args need to be inserted.
2090fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2091if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2092cmd.verbatim_args(args.iter().map(Deref::deref));
2093 }
20942095cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2096}
20972098/// Add a link script embedded in the target, if applicable.
2099fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2100match (crate_type, &sess.target.link_script) {
2101 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2102if !sess.target.linker_flavor.is_gnu() {
2103sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2104 }
21052106let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
21072108let path = tmpdir.join(file_name);
2109if let Err(error) = fs::write(&path, script.as_ref()) {
2110sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2111 }
21122113cmd.link_arg("--script").link_arg(path);
2114 }
2115_ => {}
2116 }
2117}
21182119/// Add arbitrary "user defined" args defined from command line.
2120/// FIXME: Determine where exactly these args need to be inserted.
2121fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2122cmd.verbatim_args(&sess.opts.cg.link_args);
2123}
21242125/// Add arbitrary "late link" args defined by the target spec.
2126/// FIXME: Determine where exactly these args need to be inserted.
2127fn add_late_link_args(
2128 cmd: &mut dyn Linker,
2129 sess: &Session,
2130 flavor: LinkerFlavor,
2131 crate_type: CrateType,
2132 crate_info: &CrateInfo,
2133) {
2134let any_dynamic_crate = crate_type == CrateType::Dylib2135 || crate_type == CrateType::Sdylib2136 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2137*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2138 });
2139if any_dynamic_crate {
2140if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2141cmd.verbatim_args(args.iter().map(Deref::deref));
2142 }
2143 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2144cmd.verbatim_args(args.iter().map(Deref::deref));
2145 }
2146if let Some(args) = sess.target.late_link_args.get(&flavor) {
2147cmd.verbatim_args(args.iter().map(Deref::deref));
2148 }
2149}
21502151/// Add arbitrary "post-link" args defined by the target spec.
2152/// FIXME: Determine where exactly these args need to be inserted.
2153fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2154if let Some(args) = sess.target.post_link_args.get(&flavor) {
2155cmd.verbatim_args(args.iter().map(Deref::deref));
2156 }
2157}
21582159/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2160/// the linker.
2161///
2162/// Background: we implement rlibs as static library (archives). Linkers treat archives
2163/// differently from object files: all object files participate in linking, while archives will
2164/// only participate in linking if they can satisfy at least one undefined reference (version
2165/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2166/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2167/// can't keep them either. This causes #47384.
2168///
2169/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2170/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2171/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2172/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2173/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2174/// from removing them, and this is especially problematic for embedded programming where every
2175/// byte counts.
2176///
2177/// This method creates a synthetic object file, which contains undefined references to all symbols
2178/// that are necessary for the linking. They are only present in symbol table but not actually
2179/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2180/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2181///
2182/// There's a few internal crates in the standard library (aka libcore and
2183/// libstd) which actually have a circular dependence upon one another. This
2184/// currently arises through "weak lang items" where libcore requires things
2185/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2186/// circular dependence to work correctly we declare some of these things
2187/// in this synthetic object.
2188fn add_linked_symbol_object(
2189 cmd: &mut dyn Linker,
2190 sess: &Session,
2191 tmpdir: &Path,
2192 symbols: &[(String, SymbolExportKind)],
2193) {
2194if symbols.is_empty() {
2195return;
2196 }
21972198let Some(mut file) = super::metadata::create_object_file(sess) else {
2199return;
2200 };
22012202if file.format() == object::BinaryFormat::Coff {
2203// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2204 // so add an empty section.
2205file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
22062207// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2208 // default mangler in `object` crate.
2209file.set_mangling(object::write::Mangling::None);
2210 }
22112212if file.format() == object::BinaryFormat::MachO {
2213// Divide up the sections into sub-sections via symbols for dead code stripping.
2214 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2215 // discard on MachO targets.
2216file.set_subsections_via_symbols();
2217 }
22182219// ld64 requires a relocation to load undefined symbols, see below.
2220 // Not strictly needed if linking with lld, but might as well do it there too.
2221let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2222Some(file.add_section(
2223file.segment_name(object::write::StandardSegment::Data).to_vec(),
2224"__data".into(),
2225 object::SectionKind::Data,
2226 ))
2227 } else {
2228None2229 };
22302231for (sym, kind) in symbols.iter() {
2232let symbol = file.add_symbol(object::write::Symbol {
2233 name: sym.clone().into(),
2234 value: 0,
2235 size: 0,
2236 kind: match kind {
2237 SymbolExportKind::Text => object::SymbolKind::Text,
2238 SymbolExportKind::Data => object::SymbolKind::Data,
2239 SymbolExportKind::Tls => object::SymbolKind::Tls,
2240 },
2241 scope: object::SymbolScope::Unknown,
2242 weak: false,
2243 section: object::write::SymbolSection::Undefined,
2244 flags: object::SymbolFlags::None,
2245 });
22462247// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2248 //
2249 // Code-wise, the relevant parts of ld64 are roughly:
2250 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2251 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2252 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2253 //
2254 // 2. Read the archive table of contents (__.SYMDEF file).
2255 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2256 //
2257 // 3. Begin linking by loading "atoms" from input files.
2258 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2259 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2260 //
2261 // a. Directly specified object files (`.o`) are parsed immediately.
2262 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2263 //
2264 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2265 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2266 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2267 //
2268 // - Relocations/fixups are atoms.
2269 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2270 //
2271 // b. Archives are not parsed yet.
2272 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2273 //
2274 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2275 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2276 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2277 //
2278 // All of the steps above are fairly similar to other linkers, except that **it completely
2279 // ignores undefined symbols**.
2280 //
2281 // So to make this trick work on ld64, we need to do something else to load the relevant
2282 // object files. We do this by inserting a relocation (fixup) for each symbol.
2283if let Some(section) = ld64_section_helper {
2284 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2285 .expect("failed adding relocation");
2286 }
2287 }
22882289let path = tmpdir.join("symbols.o");
2290let result = std::fs::write(&path, file.write().unwrap());
2291if let Err(error) = result {
2292sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2293 }
2294cmd.add_object(&path);
2295}
22962297/// Add object files containing code from the current crate.
2298fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2299for m in &compiled_modules.modules {
2300if let Some(obj) = &m.object {
2301 cmd.add_object(obj);
2302 }
2303if let Some(obj) = &m.global_asm_object {
2304 cmd.add_object(obj);
2305 }
2306 }
2307}
23082309/// Add object files for allocator code linked once for the whole crate tree.
2310fn add_local_crate_allocator_objects(
2311 cmd: &mut dyn Linker,
2312 compiled_modules: &CompiledModules,
2313 crate_info: &CrateInfo,
2314 crate_type: CrateType,
2315) {
2316if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2317 && let Some(m) = &compiled_modules.allocator_module
2318 {
2319if let Some(obj) = &m.object {
2320cmd.add_object(obj);
2321 }
2322if let Some(obj) = &m.global_asm_object {
2323cmd.add_object(obj);
2324 }
2325 }
2326}
23272328/// Add object files containing metadata for the current crate.
2329fn add_local_crate_metadata_objects(
2330 cmd: &mut dyn Linker,
2331 sess: &Session,
2332 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2333 crate_type: CrateType,
2334 tmpdir: &Path,
2335 crate_info: &CrateInfo,
2336 metadata: &EncodedMetadata,
2337) {
2338// When linking a dynamic library, we put the metadata into a section of the
2339 // executable. This metadata is in a separate object file from the main
2340 // object file, so we create and link it in here.
2341if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2342let data = archive_builder_builder.create_dylib_metadata_wrapper(
2343sess,
2344&metadata,
2345&crate_info.metadata_symbol,
2346 );
2347let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
23482349cmd.add_object(&obj);
2350 }
2351}
23522353/// Add sysroot and other globally set directories to the directory search list.
2354fn add_library_search_dirs(
2355 cmd: &mut dyn Linker,
2356 sess: &Session,
2357 self_contained_components: LinkSelfContainedComponents,
2358 apple_sdk_root: Option<&Path>,
2359) {
2360if !sess.opts.unstable_opts.link_native_libraries {
2361return;
2362 }
23632364let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2365let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2366if is_framework {
2367cmd.framework_path(dir);
2368 } else {
2369cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2370 }
2371 ControlFlow::<()>::Continue(())
2372 });
2373}
23742375/// Add options making relocation sections in the produced ELF files read-only
2376/// and suppressing lazy binding.
2377fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2378match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2379 RelroLevel::Full => cmd.full_relro(),
2380 RelroLevel::Partial => cmd.partial_relro(),
2381 RelroLevel::Off => cmd.no_relro(),
2382 RelroLevel::None => {}
2383 }
2384}
23852386/// Add library search paths used at runtime by dynamic linkers.
2387fn add_rpath_args(
2388 cmd: &mut dyn Linker,
2389 sess: &Session,
2390 crate_info: &CrateInfo,
2391 out_filename: &Path,
2392) {
2393if !sess.target.has_rpath {
2394return;
2395 }
23962397// FIXME (#2397): At some point we want to rpath our guesses as to
2398 // where extern libraries might live, based on the
2399 // add_lib_search_paths
2400if sess.opts.cg.rpath {
2401let libs = crate_info2402 .used_crates
2403 .iter()
2404 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2405 .collect::<Vec<_>>();
2406let rpath_config = RPathConfig {
2407 libs: &*libs,
2408 out_filename: out_filename.to_path_buf(),
2409 is_like_darwin: sess.target.is_like_darwin,
2410 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2411 };
2412cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2413 }
2414}
24152416fn strip_numeric_suffix<'a>(base: &'a str, suffix: impl AsRef<str>, fallback: &'a str) -> &'a str {
2417if suffix.as_ref().parse::<u32>().is_ok() { base } else { fallback }
2418}
24192420fn undecorate_c_symbol<'a>(
2421 name: &'a str,
2422 sess: &Session,
2423 kind: SymbolExportKind,
2424) -> Option<&'a str> {
2425match sess.target.binary_format {
2426 BinaryFormat::MachO => {
2427// Mach-O: strip the leading underscore that all external symbols have.
2428 // The Darwin linker's export_symbols will add it back.
2429name.strip_prefix('_')
2430 }
2431 BinaryFormat::Coff => {
2432// MSVC C++ mangled names start with '?' and use a completely different
2433 // decorating scheme that includes '@@' as structural delimiters.
2434 // They must not be subjected to C calling-convention undecoration.
2435if name.starts_with('?') {
2436return Some(name);
2437 }
2438Some(match sess.target.arch {
2439 Arch::X86 => {
2440// COFF 32-bit: strip calling-convention decorations.
2441if let Some(rest) = name.strip_prefix('@') {
2442// fastcall: @foo@N -> foo
2443rest.rsplit_once('@')
2444 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2445 .unwrap_or(name)
2446 } else if let Some(stripped) = name.strip_prefix('_') {
2447if let Some((base, suffix)) = stripped.rsplit_once('@') {
2448// stdcall: _foo@N -> foo
2449strip_numeric_suffix(base, suffix, stripped)
2450 } else {
2451// cdecl: _foo -> foo
2452stripped2453 }
2454 } else {
2455// vectorcall: foo@@N -> foo
2456name.rsplit_once("@@")
2457 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2458 .unwrap_or(name)
2459 }
2460 }
2461 Arch::X86_64 => {
2462// COFF 64-bit: vectorcall mangling (foo@@N -> foo) also applies on x86_64.
2463name.rsplit_once("@@")
2464 .map(|(base, suffix)| strip_numeric_suffix(base, suffix, name))
2465 .unwrap_or(name)
2466 }
2467 Arch::Arm64ECif kind == SymbolExportKind::Text => {
2468// Arm64EC: `#` prefix distinguishes ARM64EC text symbols from x64 thunks.
2469name.strip_prefix('#').unwrap_or(name)
2470 }
2471_ => name,
2472 })
2473 }
2474// ELF: no decoration
2475_ => Some(name),
2476 }
2477}
24782479fn add_c_staticlib_symbols(
2480 sess: &Session,
2481 lib: &NativeLib,
2482 out: &mut Vec<(String, SymbolExportKind)>,
2483) -> io::Result<()> {
2484let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
24852486let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
24872488let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2489 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24902491for member in archive.members() {
2492let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24932494let data = member
2495 .data(&*archive_map)
2496 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24972498// clang LTO: raw LLVM bitcode
2499if data.starts_with(b"BC\xc0\xde") {
2500return Err(io::Error::new(
2501 io::ErrorKind::InvalidData,
2502"LLVM bitcode object in C static library (LTO not supported)",
2503 ));
2504 }
25052506let object = object::File::parse(&*data)
2507 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
25082509// gcc / clang ELF / Mach-O LTO
2510if object.sections().any(|s| {
2511 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2512 }) {
2513return Err(io::Error::new(
2514 io::ErrorKind::InvalidData,
2515"LTO object in C static library is not supported",
2516 ));
2517 }
25182519for symbol in object.symbols() {
2520// The `object` crate returns `Dynamic` for ELF/Mach-O global symbols,
2521 // but always returns `Linkage` for COFF external symbols.
2522 // Accept both for COFF (Windows and UEFI).
2523let scope = symbol.scope();
2524if scope != object::SymbolScope::Dynamic
2525 && !(sess.target.binary_format == BinaryFormat::Coff
2526 && scope == object::SymbolScope::Linkage)
2527 {
2528continue;
2529 }
25302531let name = match symbol.name() {
2532Ok(n) => n,
2533Err(_) => continue,
2534 };
25352536let export_kind = match symbol.kind() {
2537 object::SymbolKind::Text => SymbolExportKind::Text,
2538 object::SymbolKind::Data => SymbolExportKind::Data,
2539_ => continue,
2540 };
25412542let Some(undecorated) = undecorate_c_symbol(name, sess, export_kind) else {
2543continue;
2544 };
2545 out.push((undecorated.to_string(), export_kind));
2546 }
2547 }
25482549Ok(())
2550}
25512552/// Produce the linker command line containing linker path and arguments.
2553///
2554/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2555/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2556/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2557/// to the linking process as a whole.
2558/// Order-independent options may still override each other in order-dependent fashion,
2559/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2560fn linker_with_args(
2561 path: &Path,
2562 flavor: LinkerFlavor,
2563 sess: &Session,
2564 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2565 crate_type: CrateType,
2566 tmpdir: &Path,
2567 out_filename: &Path,
2568 compiled_modules: &CompiledModules,
2569 crate_info: &CrateInfo,
2570 metadata: &EncodedMetadata,
2571 self_contained_components: LinkSelfContainedComponents,
2572 codegen_backend: &'static str,
2573) -> Command {
2574let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2575let cmd = &mut *super::linker::get_linker(
2576sess,
2577path,
2578flavor,
2579self_contained_components.are_any_components_enabled(),
2580&crate_info.target_cpu,
2581codegen_backend,
2582 );
2583let link_output_kind = link_output_kind(sess, crate_type);
25842585let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
25862587if crate_type == CrateType::Cdylib {
2588let mut seen = FxHashSet::default();
25892590for lib in &crate_info.used_libraries {
2591if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2592 && seen.insert((lib.name, lib.verbatim))
2593 {
2594if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2595 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2596"failed to process C static library `{}`: {}",
2597 lib.name, err
2598 ));
2599 }
2600 }
2601 }
2602 }
26032604// ------------ Early order-dependent options ------------
26052606 // If we're building something like a dynamic library then some platforms
2607 // need to make sure that all symbols are exported correctly from the
2608 // dynamic library.
2609 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2610 // at least on some platforms (e.g. windows-gnu).
2611cmd.export_symbols(tmpdir, crate_type, &export_symbols);
26122613// Can be used for adding custom CRT objects or overriding order-dependent options above.
2614 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2615 // introduce a target spec option for order-independent linker options and migrate built-in
2616 // specs to it.
2617add_pre_link_args(cmd, sess, flavor);
26182619// ------------ Object code and libraries, order-dependent ------------
26202621 // Pre-link CRT objects.
2622add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
26232624add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
26252626// Sanitizer libraries.
2627add_sanitizer_libraries(sess, flavor, crate_type, cmd);
26282629// Object code from the current crate.
2630 // Take careful note of the ordering of the arguments we pass to the linker
2631 // here. Linkers will assume that things on the left depend on things to the
2632 // right. Things on the right cannot depend on things on the left. This is
2633 // all formally implemented in terms of resolving symbols (libs on the right
2634 // resolve unknown symbols of libs on the left, but not vice versa).
2635 //
2636 // For this reason, we have organized the arguments we pass to the linker as
2637 // such:
2638 //
2639 // 1. The local object that LLVM just generated
2640 // 2. Local native libraries
2641 // 3. Upstream rust libraries
2642 // 4. Upstream native libraries
2643 //
2644 // The rationale behind this ordering is that those items lower down in the
2645 // list can't depend on items higher up in the list. For example nothing can
2646 // depend on what we just generated (e.g., that'd be a circular dependency).
2647 // Upstream rust libraries are not supposed to depend on our local native
2648 // libraries as that would violate the structure of the DAG, in that
2649 // scenario they are required to link to them as well in a shared fashion.
2650 //
2651 // Note that upstream rust libraries may contain native dependencies as
2652 // well, but they also can't depend on what we just started to add to the
2653 // link line. And finally upstream native libraries can't depend on anything
2654 // in this DAG so far because they can only depend on other native libraries
2655 // and such dependencies are also required to be specified.
2656add_local_crate_regular_objects(cmd, compiled_modules);
2657add_local_crate_metadata_objects(
2658cmd,
2659sess,
2660archive_builder_builder,
2661crate_type,
2662tmpdir,
2663crate_info,
2664metadata,
2665 );
2666add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
26672668// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2669 // at the point at which they are specified on the command line.
2670 // Must be passed before any (dynamic) libraries to have effect on them.
2671 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2672 // so it will ignore unreferenced ELF sections from relocatable objects.
2673 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2674 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2675 // and move this option back to the top.
2676cmd.add_as_needed();
26772678// Local native libraries of all kinds.
2679add_local_native_libraries(
2680cmd,
2681sess,
2682archive_builder_builder,
2683crate_info,
2684tmpdir,
2685link_output_kind,
2686 );
26872688// Upstream rust crates and their non-dynamic native libraries.
2689add_upstream_rust_crates(
2690cmd,
2691sess,
2692archive_builder_builder,
2693crate_info,
2694crate_type,
2695tmpdir,
2696link_output_kind,
2697 );
26982699// Dynamic native libraries from upstream crates.
2700add_upstream_native_libraries(
2701cmd,
2702sess,
2703archive_builder_builder,
2704crate_info,
2705tmpdir,
2706link_output_kind,
2707 );
27082709// Raw-dylibs from all crates.
2710let raw_dylib_dir = tmpdir.join("raw-dylibs");
2711if sess.target.binary_format == BinaryFormat::Elf {
2712// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2713 // instead we need to pass them via -l. To find the stub, we need to add
2714 // the directory of the stub to the linker search path.
2715 // We make an extra directory for this to avoid polluting the search path.
2716if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2717sess.dcx().emit_fatal(errors::CreateTempDir { error })
2718 }
2719cmd.include_path(&raw_dylib_dir);
2720 }
27212722// Link with the import library generated for any raw-dylib functions.
2723if sess.target.is_like_windows {
2724for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2725 sess,
2726 archive_builder_builder,
2727 crate_info.used_libraries.iter(),
2728 tmpdir,
2729true,
2730 ) {
2731 cmd.add_object(&output_path);
2732 }
2733 } else {
2734for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2735 sess,
2736 crate_info.used_libraries.iter(),
2737&raw_dylib_dir,
2738 ) {
2739// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2740cmd.link_dylib_by_name(&link_path, true, as_needed);
2741 }
2742 }
2743// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2744 // they are used within inlined functions or instantiated generic functions. We do this *after*
2745 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2746 // by the linker.
2747let dependency_linkage = crate_info2748 .dependency_formats
2749 .get(&crate_type)
2750 .expect("failed to find crate type in dependency format list");
27512752// We sort the libraries below
2753#[allow(rustc::potential_query_instability)]
2754let mut native_libraries_from_nonstatics = crate_info2755 .native_libraries
2756 .iter()
2757 .filter_map(|(&cnum, libraries)| {
2758if sess.target.is_like_windows {
2759 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2760 } else {
2761Some(libraries)
2762 }
2763 })
2764 .flatten()
2765 .collect::<Vec<_>>();
2766native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
27672768if sess.target.is_like_windows {
2769for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2770 sess,
2771 archive_builder_builder,
2772 native_libraries_from_nonstatics,
2773 tmpdir,
2774false,
2775 ) {
2776 cmd.add_object(&output_path);
2777 }
2778 } else {
2779for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2780 sess,
2781 native_libraries_from_nonstatics,
2782&raw_dylib_dir,
2783 ) {
2784// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2785cmd.link_dylib_by_name(&link_path, true, as_needed);
2786 }
2787 }
27882789// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2790 // command line shorter, reset it to default here before adding more libraries.
2791cmd.reset_per_library_state();
27922793// FIXME: Built-in target specs occasionally use this for linking system libraries,
2794 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2795 // and remove the option.
2796add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
27972798// ------------ Arbitrary order-independent options ------------
27992800 // Add order-independent options determined by rustc from its compiler options,
2801 // target properties and source code.
2802add_order_independent_options(
2803cmd,
2804sess,
2805link_output_kind,
2806self_contained_components,
2807flavor,
2808crate_type,
2809crate_info,
2810out_filename,
2811tmpdir,
2812 );
28132814// Can be used for arbitrary order-independent options.
2815 // In practice may also be occasionally used for linking native libraries.
2816 // Passed after compiler-generated options to support manual overriding when necessary.
2817add_user_defined_link_args(cmd, sess);
28182819// ------------ Builtin configurable linker scripts ------------
2820 // The user's link args should be able to overwrite symbols in the compiler's
2821 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2822 // to work correctly, the user needs to be able to specify linker arguments like
2823 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2824add_link_script(cmd, sess, tmpdir, crate_type);
28252826// ------------ Object code and libraries, order-dependent ------------
28272828 // Post-link CRT objects.
2829add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
28302831// ------------ Late order-dependent options ------------
28322833 // Doesn't really make sense.
2834 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2835 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2836 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2837add_post_link_args(cmd, sess, flavor);
28382839cmd.take_cmd()
2840}
28412842fn add_order_independent_options(
2843 cmd: &mut dyn Linker,
2844 sess: &Session,
2845 link_output_kind: LinkOutputKind,
2846 self_contained_components: LinkSelfContainedComponents,
2847 flavor: LinkerFlavor,
2848 crate_type: CrateType,
2849 crate_info: &CrateInfo,
2850 out_filename: &Path,
2851 tmpdir: &Path,
2852) {
2853// Take care of the flavors and CLI options requesting the `lld` linker.
2854add_lld_args(cmd, sess, flavor, self_contained_components);
28552856add_apple_link_args(cmd, sess, flavor);
28572858let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
28592860if sess.target.os == Os::Fuchsia2861 && crate_type == CrateType::Executable2862 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2863 {
2864let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2865cmd.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"));
2866 }
28672868if sess.target.eh_frame_header {
2869cmd.add_eh_frame_header();
2870 }
28712872// Make the binary compatible with data execution prevention schemes.
2873cmd.add_no_exec();
28742875if self_contained_components.is_crt_objects_enabled() {
2876cmd.no_crt_objects();
2877 }
28782879if sess.target.os == Os::Emscripten {
2880cmd.cc_arg("-fwasm-exceptions");
2881 }
28822883if flavor == LinkerFlavor::Llbc {
2884cmd.link_args(&[
2885"--target",
2886&versioned_llvm_target(sess),
2887"--target-cpu",
2888&crate_info.target_cpu,
2889 ]);
2890if crate_info.target_features.len() > 0 {
2891cmd.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(",")));
2892 }
2893 } else if flavor == LinkerFlavor::Bpf {
2894cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2895if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2896 .into_iter()
2897 .find(|feat| !feat.is_empty())
2898 {
2899cmd.link_args(&["--cpu-features", feat]);
2900 }
2901 }
29022903cmd.linker_plugin_lto();
29042905add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
29062907cmd.output_filename(out_filename);
29082909if crate_type == CrateType::Executable2910 && sess.target.is_like_windows
2911 && let Some(s) = &crate_info.windows_subsystem
2912 {
2913cmd.windows_subsystem(*s);
2914 }
29152916// Try to strip as much out of the generated object by removing unused
2917 // sections if possible. See more comments in linker.rs
2918if !sess.link_dead_code() {
2919// If PGO is enabled sometimes gc_sections will remove the profile data section
2920 // as it appears to be unused. This can then cause the PGO profile file to lose
2921 // some functions. If we are generating a profile we shouldn't strip those metadata
2922 // sections to ensure we have all the data for PGO.
2923let keep_metadata =
2924crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2925cmd.gc_sections(keep_metadata);
2926 }
29272928cmd.set_output_kind(link_output_kind, crate_type, out_filename);
29292930add_relro_args(cmd, sess);
29312932// Pass optimization flags down to the linker.
2933cmd.optimize();
29342935// Gather the set of NatVis files, if any, and write them out to a temp directory.
2936let natvis_visualizers = collect_natvis_visualizers(
2937tmpdir,
2938sess,
2939&crate_info.local_crate_name,
2940&crate_info.natvis_debugger_visualizers,
2941 );
29422943// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2944cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
29452946// We want to prevent the compiler from accidentally leaking in any system libraries,
2947 // so by default we tell linkers not to link to any default libraries.
2948if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2949cmd.no_default_libraries();
2950 }
29512952if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2953cmd.pgo_gen();
2954 }
29552956if sess.opts.unstable_opts.instrument_mcount {
2957cmd.enable_profiling();
2958 }
29592960if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2961cmd.control_flow_guard();
2962 }
29632964// OBJECT-FILES-NO, AUDIT-ORDER
2965if sess.opts.unstable_opts.ehcont_guard {
2966cmd.ehcont_guard();
2967 }
29682969add_rpath_args(cmd, sess, crate_info, out_filename);
2970}
29712972// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2973fn collect_natvis_visualizers(
2974 tmpdir: &Path,
2975 sess: &Session,
2976 crate_name: &Symbol,
2977 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2978) -> Vec<PathBuf> {
2979let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
29802981for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2982let 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));
29832984match fs::write(&visualizer_out_file, &visualizer.src) {
2985Ok(()) => {
2986 visualizer_paths.push(visualizer_out_file);
2987 }
2988Err(error) => {
2989 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2990 path: visualizer_out_file,
2991 error,
2992 });
2993 }
2994 };
2995 }
2996visualizer_paths2997}
29982999fn add_native_libs_from_crate(
3000 cmd: &mut dyn Linker,
3001 sess: &Session,
3002 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3003 crate_info: &CrateInfo,
3004 tmpdir: &Path,
3005 bundled_libs: &FxIndexSet<Symbol>,
3006 cnum: CrateNum,
3007 link_static: bool,
3008 link_dynamic: bool,
3009 link_output_kind: LinkOutputKind,
3010) {
3011if !sess.opts.unstable_opts.link_native_libraries {
3012// If `-Zlink-native-libraries=false` is set, then the assumption is that an
3013 // external build system already has the native dependencies defined, and it
3014 // will provide them to the linker itself.
3015return;
3016 }
30173018if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
3019// If rlib contains native libs as archives, unpack them to tmpdir.
3020let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
3021archive_builder_builder3022 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
3023 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
3024 }
30253026let native_libs = match cnum {
3027LOCAL_CRATE => &crate_info.used_libraries,
3028_ => &crate_info.native_libraries[&cnum],
3029 };
30303031let mut last = (None, NativeLibKind::Unspecified, false);
3032for lib in native_libs {
3033if !relevant_lib(sess, lib) {
3034continue;
3035 }
30363037// Skip if this library is the same as the last.
3038last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
3039continue;
3040 } else {
3041 (Some(lib.name), lib.kind, lib.verbatim)
3042 };
30433044let name = lib.name.as_str();
3045let verbatim = lib.verbatim;
3046match lib.kind {
3047 NativeLibKind::Static { bundle, whole_archive, .. } => {
3048if link_static {
3049let bundle = bundle.unwrap_or(true);
3050let whole_archive = whole_archive == Some(true);
3051if bundle && cnum != LOCAL_CRATE {
3052if let Some(filename) = lib.filename {
3053// If rlib contains native libs as archives, they are unpacked to tmpdir.
3054let path = tmpdir.join(filename.as_str());
3055 cmd.link_staticlib_by_path(&path, whole_archive);
3056 }
3057 } else {
3058 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
3059 }
3060 }
3061 }
3062 NativeLibKind::Dylib { as_needed } => {
3063if link_dynamic {
3064 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
3065 }
3066 }
3067 NativeLibKind::Unspecified => {
3068// If we are generating a static binary, prefer static library when the
3069 // link kind is unspecified.
3070if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
3071if link_static {
3072 cmd.link_staticlib_by_name(name, verbatim, false);
3073 }
3074 } else if link_dynamic {
3075 cmd.link_dylib_by_name(name, verbatim, true);
3076 }
3077 }
3078 NativeLibKind::Framework { as_needed } => {
3079if link_dynamic {
3080 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
3081 }
3082 }
3083 NativeLibKind::RawDylib { as_needed: _ } => {
3084// Handled separately in `linker_with_args`.
3085}
3086 NativeLibKind::WasmImportModule => {}
3087 NativeLibKind::LinkArg => {
3088if link_static {
3089if verbatim {
3090 cmd.verbatim_arg(name);
3091 } else {
3092 cmd.link_arg(name);
3093 }
3094 }
3095 }
3096 }
3097 }
3098}
30993100fn add_local_native_libraries(
3101 cmd: &mut dyn Linker,
3102 sess: &Session,
3103 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3104 crate_info: &CrateInfo,
3105 tmpdir: &Path,
3106 link_output_kind: LinkOutputKind,
3107) {
3108// All static and dynamic native library dependencies are linked to the local crate.
3109let link_static = true;
3110let link_dynamic = true;
3111add_native_libs_from_crate(
3112cmd,
3113sess,
3114archive_builder_builder,
3115crate_info,
3116tmpdir,
3117&Default::default(),
3118LOCAL_CRATE,
3119link_static,
3120link_dynamic,
3121link_output_kind,
3122 );
3123}
31243125fn add_upstream_rust_crates(
3126 cmd: &mut dyn Linker,
3127 sess: &Session,
3128 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3129 crate_info: &CrateInfo,
3130 crate_type: CrateType,
3131 tmpdir: &Path,
3132 link_output_kind: LinkOutputKind,
3133) {
3134// All of the heavy lifting has previously been accomplished by the
3135 // dependency_format module of the compiler. This is just crawling the
3136 // output of that module, adding crates as necessary.
3137 //
3138 // Linking to a rlib involves just passing it to the linker (the linker
3139 // will slurp up the object files inside), and linking to a dynamic library
3140 // involves just passing the right -l flag.
3141let data = crate_info3142 .dependency_formats
3143 .get(&crate_type)
3144 .expect("failed to find crate type in dependency format list");
31453146if sess.target.is_like_aix {
3147// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3148 // the dependency name when outputting a shared library. Thus, `ld` will
3149 // use the full path to shared libraries as the dependency if passed it
3150 // by default unless `noipath` is passed.
3151 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3152cmd.link_or_cc_arg("-bnoipath");
3153 }
31543155for &cnum in &crate_info.used_crates {
3156// We may not pass all crates through to the linker. Some crates may appear statically in
3157 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3158 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3159 // Even if they were already included into a dylib
3160 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3161 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3162 // See the comment in inject_profiler_runtime for why this is the case.
3163let linkage = data[cnum];
3164let link_static_crate = linkage == Linkage::Static
3165 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3166 && (crate_info.compiler_builtins == Some(cnum)
3167 || crate_info.profiler_runtime == Some(cnum));
31683169let mut bundled_libs = Default::default();
3170match linkage {
3171 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3172if link_static_crate {
3173 bundled_libs = crate_info.native_libraries[&cnum]
3174 .iter()
3175 .filter_map(|lib| lib.filename)
3176 .collect();
3177 add_static_crate(
3178 cmd,
3179 sess,
3180 archive_builder_builder,
3181 crate_info,
3182 tmpdir,
3183 cnum,
3184&bundled_libs,
3185 );
3186 }
3187 }
3188 Linkage::Dynamic => {
3189let src = &crate_info.used_crate_source[&cnum];
3190 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3191 }
3192 }
31933194// Static libraries are linked for a subset of linked upstream crates.
3195 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3196 // because the rlib is just an archive.
3197 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3198 // the native library because it is already linked into the dylib, and even if
3199 // inline/const/generic functions from the dylib can refer to symbols from the native
3200 // library, those symbols should be exported and available from the dylib anyway.
3201 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3202let link_static = link_static_crate;
3203// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3204let link_dynamic = false;
3205 add_native_libs_from_crate(
3206 cmd,
3207 sess,
3208 archive_builder_builder,
3209 crate_info,
3210 tmpdir,
3211&bundled_libs,
3212 cnum,
3213 link_static,
3214 link_dynamic,
3215 link_output_kind,
3216 );
3217 }
3218}
32193220fn add_upstream_native_libraries(
3221 cmd: &mut dyn Linker,
3222 sess: &Session,
3223 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3224 crate_info: &CrateInfo,
3225 tmpdir: &Path,
3226 link_output_kind: LinkOutputKind,
3227) {
3228for &cnum in &crate_info.used_crates {
3229// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3230 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3231 // are linked together with their respective upstream crates, and in their originally
3232 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3233 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3234let link_static = false;
3235// Dynamic libraries are linked for all linked upstream crates.
3236 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3237 // because the rlib is just an archive.
3238 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3239 // the native library too because inline/const/generic functions from the dylib can refer
3240 // to symbols from the native library, so the native library providing those symbols should
3241 // be available when linking our final binary.
3242let link_dynamic = true;
3243 add_native_libs_from_crate(
3244 cmd,
3245 sess,
3246 archive_builder_builder,
3247 crate_info,
3248 tmpdir,
3249&Default::default(),
3250 cnum,
3251 link_static,
3252 link_dynamic,
3253 link_output_kind,
3254 );
3255 }
3256}
32573258// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3259// to be relative to the sysroot directory, which may be a relative path specified by the user.
3260//
3261// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3262// linker command line can be non-deterministic due to the paths including the current working
3263// directory. The linker command line needs to be deterministic since it appears inside the PDB
3264// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3265//
3266// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3267fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3268let sysroot_lib_path = &sess.target_tlib_path.dir;
3269let canonical_sysroot_lib_path =
3270 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
32713272let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3273if canonical_lib_dir == canonical_sysroot_lib_path {
3274// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3275sysroot_lib_path.clone()
3276 } else {
3277fix_windows_verbatim_for_gcc(lib_dir)
3278 }
3279}
32803281fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3282if let Some(dir) = path.parent() {
3283let file_name = path.file_name().expect("library path has no file name component");
3284rehome_sysroot_lib_dir(sess, dir).join(file_name)
3285 } else {
3286fix_windows_verbatim_for_gcc(path)
3287 }
3288}
32893290// Adds the static "rlib" versions of all crates to the command line.
3291// There's a bit of magic which happens here specifically related to LTO,
3292// namely that we remove upstream object files.
3293//
3294// When performing LTO, almost(*) all of the bytecode from the upstream
3295// libraries has already been included in our object file output. As a
3296// result we need to remove the object files in the upstream libraries so
3297// the linker doesn't try to include them twice (or whine about duplicate
3298// symbols). We must continue to include the rest of the rlib, however, as
3299// it may contain static native libraries which must be linked in.
3300//
3301// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3302// their bytecode wasn't included. The object files in those libraries must
3303// still be passed to the linker.
3304//
3305// Note, however, that if we're not doing LTO we can just pass the rlib
3306// blindly to the linker (fast) because it's fine if it's not actually
3307// included as we're at the end of the dependency chain.
3308fn add_static_crate(
3309 cmd: &mut dyn Linker,
3310 sess: &Session,
3311 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3312 crate_info: &CrateInfo,
3313 tmpdir: &Path,
3314 cnum: CrateNum,
3315 bundled_lib_file_names: &FxIndexSet<Symbol>,
3316) {
3317let src = &crate_info.used_crate_source[&cnum];
3318let cratepath = src.rlib.as_ref().unwrap();
33193320let mut link_upstream =
3321 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
33223323if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3324 {
3325link_upstream(cratepath);
3326return;
3327 }
33283329let dst = tmpdir.join(cratepath.file_name().unwrap());
3330let name = cratepath.file_name().unwrap().to_str().unwrap();
3331let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3332let bundled_lib_file_names = bundled_lib_file_names.clone();
33333334sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3335let upstream_rust_objects_already_included =
3336are_upstream_rust_objects_already_included(sess);
3337let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
33383339let mut archive = archive_builder_builder.new_archive_builder(sess);
3340if let Err(error) = archive.add_archive(
3341cratepath,
3342 AddArchiveKind::Rlib(&|f, entry_kind| {
3343if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3344return true;
3345 }
33463347// If we're performing LTO and this is a rust-generated object
3348 // file, then we don't need the object file as it's part of the
3349 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3350 // though, so we let that object file slide.
3351if upstream_rust_objects_already_included3352 && entry_kind == ArchiveEntryKind::RustObj3353 && is_builtins3354 {
3355return true;
3356 }
33573358// We skip native libraries because:
3359 // 1. This native libraries won't be used from the generated rlib,
3360 // so we can throw them away to avoid the copying work.
3361 // 2. We can't allow it to be a single remaining entry in archive
3362 // as some linkers may complain on that.
3363if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3364return true;
3365 }
33663367false
3368}),
3369 ) {
3370sess.dcx()
3371 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3372 }
3373if archive.build(&dst, None) {
3374link_upstream(&dst);
3375 }
3376 });
3377}
33783379// Same thing as above, but for dynamic crates instead of static crates.
3380fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3381cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3382}
33833384fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3385match lib.cfg {
3386Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3387None => true,
3388 }
3389}
33903391pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3392match sess.lto() {
3393 config::Lto::Fat => true,
3394 config::Lto::Thin => {
3395// If we defer LTO to the linker, we haven't run LTO ourselves, so
3396 // any upstream object files have not been copied yet.
3397!sess.opts.cg.linker_plugin_lto.enabled()
3398 }
3399 config::Lto::No | config::Lto::ThinLocal => false,
3400 }
3401}
34023403/// We need to communicate five things to the linker on Apple/Darwin targets:
3404/// - The architecture.
3405/// - The operating system (and that it's an Apple platform).
3406/// - The environment.
3407/// - The deployment target.
3408/// - The SDK version.
3409fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3410if !sess.target.is_like_darwin {
3411return;
3412 }
3413let LinkerFlavor::Darwin(cc, _) = flavorelse {
3414return;
3415 };
34163417// `sess.target.arch` (`target_arch`) is not detailed enough.
3418let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3419let target_os = &sess.target.os;
3420let target_env = &sess.target.env;
34213422// The architecture name to forward to the linker.
3423 //
3424 // Supported architecture names can be found in the source:
3425 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3426 //
3427 // Intentionally verbose to ensure that the list always matches correctly
3428 // with the list in the source above.
3429let ld64_arch = match llvm_arch {
3430"armv7k" => "armv7k",
3431"armv7s" => "armv7s",
3432"arm64" => "arm64",
3433"arm64e" => "arm64e",
3434"arm64_32" => "arm64_32",
3435// ld64 doesn't understand i686, so fall back to i386 instead.
3436 //
3437 // Same story when linking with cc, since that ends up invoking ld64.
3438"i386" | "i686" => "i386",
3439"x86_64" => "x86_64",
3440"x86_64h" => "x86_64h",
3441_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsupported architecture in Apple target: {0}",
sess.target.llvm_target))bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3442 };
34433444if cc == Cc::No {
3445// From the man page for ld64 (`man ld`):
3446 // > The linker accepts universal (multiple-architecture) input files,
3447 // > but always creates a "thin" (single-architecture), standard
3448 // > Mach-O output file. The architecture for the output file is
3449 // > specified using the -arch option.
3450 //
3451 // The linker has heuristics to determine the desired architecture,
3452 // but to be safe, and to avoid a warning, we set the architecture
3453 // explicitly.
3454cmd.link_args(&["-arch", ld64_arch]);
34553456// Man page says that ld64 supports the following platform names:
3457 // > - macos
3458 // > - ios
3459 // > - tvos
3460 // > - watchos
3461 // > - bridgeos
3462 // > - visionos
3463 // > - xros
3464 // > - mac-catalyst
3465 // > - ios-simulator
3466 // > - tvos-simulator
3467 // > - watchos-simulator
3468 // > - visionos-simulator
3469 // > - xros-simulator
3470 // > - driverkit
3471let platform_name = match (target_os, target_env) {
3472 (os, Env::Unspecified) => os.desc(),
3473 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3474 (Os::IOs, Env::Sim) => "ios-simulator",
3475 (Os::TvOs, Env::Sim) => "tvos-simulator",
3476 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3477 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3478_ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid OS/env combination for Apple target: {0}, {1}",
target_os, target_env))bug!("invalid OS/env combination for Apple target: {target_os}, {target_env}"),
3479 };
34803481let min_version = sess.apple_deployment_target().fmt_full().to_string();
34823483// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3484 // - By dyld to give extra warnings and errors, see e.g.:
3485 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3486 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3487 // - By system frameworks to change certain behaviour. For example, the default value of
3488 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3489 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3490 //
3491 // We do not currently know the actual SDK version though, so we have a few options:
3492 // 1. Use the minimum version supported by rustc.
3493 // 2. Use the same as the deployment target.
3494 // 3. Use an arbitrary recent version.
3495 // 4. Omit the version.
3496 //
3497 // The first option is too low / too conservative, and means that users will not get the
3498 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3499 //
3500 // The second option is similarly conservative, and also wrong since if the user specified a
3501 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3502 // make invalid assumptions about the capabilities of the binary.
3503 //
3504 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3505 // version, and is also wrong for similar reasons as above.
3506 //
3507 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3508 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3509 // it as 0.0, which is again too low/conservative.
3510 //
3511 // Currently, we lie about the SDK version, and choose the second option.
3512 //
3513 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3514 // <https://github.com/rust-lang/rust/issues/129432>
3515let sdk_version = &*min_version;
35163517// From the man page for ld64 (`man ld`):
3518 // > This is set to indicate the platform, oldest supported version of
3519 // > that platform that output is to be used on, and the SDK that the
3520 // > output was built against.
3521 //
3522 // Like with `-arch`, the linker can figure out the platform versions
3523 // itself from the binaries being linked, but to be safe, we specify
3524 // the desired versions here explicitly.
3525cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3526 } else {
3527// cc == Cc::Yes
3528 //
3529 // We'd _like_ to use `-target` everywhere, since that can uniquely
3530 // communicate all the required details except for the SDK version
3531 // (which is read by Clang itself from the SDKROOT), but that doesn't
3532 // work on GCC, and since we don't know whether the `cc` compiler is
3533 // Clang, GCC, or something else, we fall back to other options that
3534 // also work on GCC when compiling for macOS.
3535 //
3536 // Targets other than macOS are ill-supported by GCC (it doesn't even
3537 // support e.g. `-miphoneos-version-min`), so in those cases we can
3538 // fairly safely use `-target`. See also the following, where it is
3539 // made explicit that the recommendation by LLVM developers is to use
3540 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3541if *target_os == Os::MacOs {
3542// `-arch` communicates the architecture.
3543 //
3544 // CC forwards the `-arch` to the linker, so we use the same value
3545 // here intentionally.
3546cmd.cc_args(&["-arch", ld64_arch]);
35473548// The presence of `-mmacosx-version-min` makes CC default to
3549 // macOS, and it sets the deployment target.
3550let version = sess.apple_deployment_target().fmt_full();
3551// Intentionally pass this as a single argument, Clang doesn't
3552 // seem to like it otherwise.
3553cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
35543555// macOS has no environment, so with these two, we've told CC the
3556 // four desired parameters.
3557 //
3558 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3559} else {
3560cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3561 }
3562 }
3563}
35643565fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3566if !sess.target.is_like_darwin {
3567return None;
3568 }
3569let LinkerFlavor::Darwin(cc, _) = flavorelse {
3570return None;
3571 };
35723573// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3574 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3575 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3576 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3577 // instead we invoke `xcrun` manually.
3578 //
3579 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3580 // cause the trampoline binary to skip looking up the SDK itself).
3581let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
35823583if cc == Cc::Yes {
3584// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3585 // - The `--sysroot` flag.
3586 // - The `-isysroot` flag.
3587 // - The `SDKROOT` environment variable.
3588 //
3589 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3590 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3591 // only applies to include header files, but on Apple targets it also applies to libraries
3592 // and frameworks.
3593 //
3594 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3595 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3596 // primarily because that is the same interface that is used when invoking the tool under
3597 // `xcrun -sdk macosx $tool`.
3598 //
3599 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3600 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3601 //
3602 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3603 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3604 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3605 //
3606 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3607 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3608 // ignoring the value we set here, and instead use their built-in sysroot).
3609cmd.cmd().env("SDKROOT", &sdkroot);
3610 } else {
3611// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3612 // read by the linker, so it's really the only option.
3613 //
3614 // This is also what Clang does.
3615cmd.link_arg("-syslibroot");
3616cmd.link_arg(&sdkroot);
3617 }
36183619Some(sdkroot)
3620}
36213622fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3623if let Ok(sdkroot) = env::var("SDKROOT") {
3624let p = PathBuf::from(&sdkroot);
36253626// Ignore invalid SDKs, similar to what clang does:
3627 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3628 //
3629 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3630 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3631 // clearly set for the wrong platform.
3632 //
3633 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3634match &*apple::sdk_name(&sess.target).to_lowercase() {
3635"appletvos"
3636if sdkroot.contains("TVSimulator.platform")
3637 || sdkroot.contains("MacOSX.platform") => {}
3638"appletvsimulator"
3639if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3640"iphoneos"
3641if sdkroot.contains("iPhoneSimulator.platform")
3642 || sdkroot.contains("MacOSX.platform") => {}
3643"iphonesimulator"
3644if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3645 }
3646"macosx"
3647if sdkroot.contains("iPhoneOS.platform")
3648 || sdkroot.contains("iPhoneSimulator.platform")
3649 || sdkroot.contains("AppleTVOS.platform")
3650 || sdkroot.contains("AppleTVSimulator.platform")
3651 || sdkroot.contains("WatchOS.platform")
3652 || sdkroot.contains("WatchSimulator.platform")
3653 || sdkroot.contains("XROS.platform")
3654 || sdkroot.contains("XRSimulator.platform") => {}
3655"watchos"
3656if sdkroot.contains("WatchSimulator.platform")
3657 || sdkroot.contains("MacOSX.platform") => {}
3658"watchsimulator"
3659if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3660"xros"
3661if sdkroot.contains("XRSimulator.platform")
3662 || sdkroot.contains("MacOSX.platform") => {}
3663"xrsimulator"
3664if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3665// Ignore `SDKROOT` if it's not a valid path.
3666_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3667_ => return Some(p),
3668 }
3669 }
36703671 apple::get_sdk_root(sess)
3672}
36733674/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3675/// invoke it:
3676/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3677/// - or any `lld` available to `cc`.
3678fn add_lld_args(
3679 cmd: &mut dyn Linker,
3680 sess: &Session,
3681 flavor: LinkerFlavor,
3682 self_contained_components: LinkSelfContainedComponents,
3683) {
3684{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:3684",
"rustc_codegen_ssa::back::link", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(3684u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("add_lld_args requested, flavor: \'{0:?}\', target self-contained components: {1:?}",
flavor, self_contained_components) as &dyn Value))])
});
} else { ; }
};debug!(
3685"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3686 flavor, self_contained_components,
3687 );
36883689// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3690 // we don't need to do anything.
3691if !(flavor.uses_cc() && flavor.uses_lld()) {
3692return;
3693 }
36943695// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3696 // directories to the tool's search path, depending on a mix between what users can specify on
3697 // the CLI, and what the target spec enables (as it can't disable components):
3698 // - if the self-contained linker is enabled on the CLI or by the target spec,
3699 // - and if the self-contained linker is not disabled on the CLI.
3700let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3701let self_contained_target = self_contained_components.is_linker_enabled();
37023703let self_contained_linker = self_contained_cli || self_contained_target;
3704if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3705let mut linker_path_exists = false;
3706for path in sess.get_tools_search_paths(false) {
3707let linker_path = path.join("gcc-ld");
3708 linker_path_exists |= linker_path.exists();
3709 cmd.cc_arg({
3710let mut arg = OsString::from("-B");
3711 arg.push(linker_path);
3712 arg
3713 });
3714 }
3715if !linker_path_exists {
3716// As a sanity check, we emit an error if none of these paths exist: we want
3717 // self-contained linking and have no linker.
3718sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3719 }
3720 }
37213722// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3723 // `lld` as the linker.
3724 //
3725 // Note that wasm targets skip this step since the only option there anyway
3726 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3727 // this, `wasm-component-ld`, which is overridden if this option is passed.
3728if !sess.target.is_like_wasm {
3729cmd.cc_arg("-fuse-ld=lld");
3730 }
37313732if !flavor.is_gnu() {
3733// Tell clang to use a non-default LLD flavor.
3734 // Gcc doesn't understand the target option, but we currently assume
3735 // that gcc is not used for Apple and Wasm targets (#97402).
3736 //
3737 // Note that we don't want to do that by default on macOS: e.g. passing a
3738 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3739 // shown in issue #101653 and the discussion in PR #101792.
3740 //
3741 // It could be required in some cases of cross-compiling with
3742 // LLD, but this is generally unspecified, and we don't know
3743 // which specific versions of clang, macOS SDK, host and target OS
3744 // combinations impact us here.
3745 //
3746 // So we do a simple first-approximation until we know more of what the
3747 // Apple targets require (and which would be handled prior to hitting this
3748 // LLD codepath anyway), but the expectation is that until then
3749 // this should be manually passed if needed. We specify the target when
3750 // targeting a different linker flavor on macOS, and that's also always
3751 // the case when targeting WASM.
3752if sess.target.linker_flavor != sess.host.linker_flavor {
3753cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3754 }
3755 }
3756}
37573758// gold has been deprecated with binutils 2.44
3759// and is known to behave incorrectly around Rust programs.
3760// There have been reports of being unable to bootstrap with gold:
3761// https://github.com/rust-lang/rust/issues/139425
3762// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3763// emitted with `#[used(linker)]`.
3764fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3765use object::read::elf::{FileHeader, SectionHeader};
3766use object::read::{ReadCache, ReadRef, Result};
3767use object::{Endianness, elf};
37683769fn elf_has_gold_version_note<'a>(
3770 elf: &impl FileHeader,
3771 data: impl ReadRef<'a>,
3772 ) -> Result<bool> {
3773let endian = elf.endian()?;
37743775let section =
3776 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3777if let Some((_, section)) = section3778 && let Some(mut notes) = section.notes(endian, data)?
3779{
3780return Ok(notes.any(|note| {
3781note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3782 }));
3783 }
37843785Ok(false)
3786 }
37873788let data = ReadCache::new(BufReader::new(File::open(path)?));
37893790let was_linked_with_gold = if sess.target.pointer_width == 64 {
3791let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3792 elf_has_gold_version_note(elf, &data)?
3793} else if sess.target.pointer_width == 32 {
3794let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3795 elf_has_gold_version_note(elf, &data)?
3796} else {
3797return Ok(());
3798 };
37993800if was_linked_with_gold {
3801let mut warn =
3802sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3803warn.help("consider using LLD or ld from GNU binutils instead");
3804warn.emit();
3805 }
3806Ok(())
3807}