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::{
50BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
51LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
52RelroLevel, SanitizerSet, SplitDebuginfo,
53};
54use tracing::{debug, info, warn};
5556use super::archive::{AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind};
57use super::command::Command;
58use super::linker::{self, Linker};
59use super::metadata::{MetadataPosition, create_wrapper_file};
60use super::rpath::{self, RPathConfig};
61use super::{apple, rmeta_link, versioned_llvm_target};
62use crate::base::needs_allocator_shim_for_linking;
63use crate::{CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors};
6465pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
66if let Err(e) = fs::remove_file(path) {
67if e.kind() != io::ErrorKind::NotFound {
68dcx.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));
69 }
70 }
71}
7273/// Performs the linkage portion of the compilation phase. This will generate all
74/// of the requested outputs for this compilation session.
75pub fn link_binary(
76 sess: &Session,
77 archive_builder_builder: &dyn ArchiveBuilderBuilder,
78 compiled_modules: CompiledModules,
79 crate_info: CrateInfo,
80 metadata: EncodedMetadata,
81 outputs: &OutputFilenames,
82 codegen_backend: &'static str,
83) {
84let _timer = sess.timer("link_binary");
85let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
86let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
87for &crate_type in &crate_info.crate_types {
88// Ignore executable crates if we have -Z no-codegen, as they will error.
89if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
90 && !output_metadata
91 && crate_type == CrateType::Executable
92 {
93continue;
94 }
9596if invalid_output_for_target(sess, crate_type) {
97::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);
98 }
99100 sess.time("link_binary_check_files_are_writeable", || {
101for m in &compiled_modules.modules {
102if let Some(obj) = &m.object {
103 check_file_is_writeable(obj, sess);
104 }
105if let Some(obj) = &m.global_asm_object {
106 check_file_is_writeable(obj, sess);
107 }
108 }
109 });
110111if outputs.outputs.should_link() {
112let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
113let tmpdir = TempDirBuilder::new()
114 .prefix("rustc")
115 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
116 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
117let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
118119let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
120let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
121match crate_type {
122 CrateType::Rlib => {
123let _timer = sess.timer("link_rlib");
124{
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:124",
"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(124u32),
::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);
125 link_rlib(
126 sess,
127 archive_builder_builder,
128&compiled_modules,
129&crate_info,
130&metadata,
131 RlibFlavor::Normal,
132&path,
133 )
134 .build(&out_filename, None);
135 }
136 CrateType::StaticLib => {
137 link_staticlib(
138 sess,
139 archive_builder_builder,
140&compiled_modules,
141&crate_info,
142&metadata,
143&out_filename,
144&path,
145 );
146 }
147_ => {
148 link_natively(
149 sess,
150 archive_builder_builder,
151 crate_type,
152&out_filename,
153&compiled_modules,
154&crate_info,
155&metadata,
156 path.as_ref(),
157 codegen_backend,
158 );
159 }
160 }
161if sess.opts.json_artifact_notifications {
162 sess.dcx().emit_artifact_notification(&out_filename, "link");
163 }
164165if sess.prof.enabled()
166 && let Some(artifact_name) = out_filename.file_name()
167 {
168// Record size for self-profiling
169let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
170171 sess.prof.artifact_size(
172"linked_artifact",
173 artifact_name.to_string_lossy(),
174 file_size,
175 );
176 }
177178if sess.target.binary_format == BinaryFormat::Elf {
179if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
180{
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:180",
"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(180u32),
::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");
181 }
182 }
183184if output.is_stdout() {
185if output.is_tty() {
186 sess.dcx().emit_err(errors::BinaryOutputToTty {
187 shorthand: OutputType::Exe.shorthand(),
188 });
189 } else if let Err(e) = copy_to_stdout(&out_filename) {
190 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
191 }
192 tempfiles_for_stdout_output.push(out_filename);
193 }
194 }
195 }
196197// Remove the temporary object file and metadata if we aren't saving temps.
198sess.time("link_binary_remove_temps", || {
199// If the user requests that temporaries are saved, don't delete any.
200if sess.opts.cg.save_temps {
201return;
202 }
203204let maybe_remove_temps_from_module =
205 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
206if !preserve_objects && let Some(ref obj) = module.object {
207ensure_removed(sess.dcx(), obj);
208 }
209210if !preserve_objects && let Some(ref obj) = module.global_asm_object {
211ensure_removed(sess.dcx(), obj);
212 }
213214if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
215ensure_removed(sess.dcx(), dwo_obj);
216 }
217 };
218219let remove_temps_from_module =
220 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
221222// Otherwise, always remove the allocator module temporaries.
223if let Some(ref allocator_module) = compiled_modules.allocator_module {
224remove_temps_from_module(allocator_module);
225 }
226227// Remove the temporary files if output goes to stdout
228for temp in tempfiles_for_stdout_output {
229 ensure_removed(sess.dcx(), &temp);
230 }
231232// If no requested outputs require linking, then the object temporaries should
233 // be kept.
234if !sess.opts.output_types.should_link() {
235return;
236 }
237238// Potentially keep objects for their debuginfo.
239let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
240{
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:240",
"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(240u32),
::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);
241242for module in &compiled_modules.modules {
243 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
244 }
245 });
246}
247248// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
249// crate types must use the same dependency formats.
250pub fn each_linked_rlib(
251 info: &CrateInfo,
252 crate_type: Option<CrateType>,
253 f: &mut dyn FnMut(CrateNum, &Path),
254) -> Result<(), errors::LinkRlibError> {
255let fmts = if let Some(crate_type) = crate_type {
256let Some(fmts) = info.dependency_formats.get(&crate_type) else {
257return Err(errors::LinkRlibError::MissingFormat);
258 };
259260fmts261 } else {
262let mut dep_formats = info.dependency_formats.iter();
263let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
264if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
265return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
266 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
267 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
268 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
269 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
270 });
271 }
272list1273 };
274275let used_dep_crates = info.used_crates.iter();
276for &cnum in used_dep_crates {
277match fmts.get(cnum) {
278Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
279Some(_) => {}
280None => return Err(errors::LinkRlibError::MissingFormat),
281 }
282let crate_name = info.crate_name[&cnum];
283let used_crate_source = &info.used_crate_source[&cnum];
284if let Some(path) = &used_crate_source.rlib {
285 f(cnum, path);
286 } else if used_crate_source.rmeta.is_some() {
287return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
288 } else {
289return Err(errors::LinkRlibError::NotFound { crate_name });
290 }
291 }
292Ok(())
293}
294295/// Create an 'rlib'.
296///
297/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
298/// The rlib primarily contains the object file of the crate, but it also some of the object files
299/// from native libraries.
300fn link_rlib<'a>(
301 sess: &'a Session,
302 archive_builder_builder: &dyn ArchiveBuilderBuilder,
303 compiled_modules: &CompiledModules,
304 crate_info: &CrateInfo,
305 metadata: &EncodedMetadata,
306 flavor: RlibFlavor,
307 tmpdir: &MaybeTempDir,
308) -> Box<dyn ArchiveBuilder + 'a> {
309let mut ab = archive_builder_builder.new_archive_builder(sess);
310311// Pre-compute the list of Rust object filenames and materialize the rmeta-link
312 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
313 // placed immediately after metadata in the archive, so consumers can find
314 // it without iterating every archive member.
315let rust_object_files: Vec<String> = compiled_modules316 .modules
317 .iter()
318 .filter_map(|m| m.object.as_ref())
319 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
320 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
321 .collect();
322323let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
324let metadata_link = rmeta_link::RmetaLink { rust_object_files };
325let metadata_link_data = metadata_link.encode();
326let (wrapper, _) =
327create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
328Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
329 } else {
330None331 };
332333let trailing_metadata = match flavor {
334 RlibFlavor::Normal => {
335let (metadata, metadata_position) =
336create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
337let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
338match metadata_position {
339 MetadataPosition::First => {
340// Most of the time metadata in rlib files is wrapped in a "dummy" object
341 // file for the target platform so the rlib can be processed entirely by
342 // normal linkers for the platform. Sometimes this is not possible however.
343 // If it is possible however, placing the metadata object first improves
344 // performance of getting metadata from rlibs.
345ab.add_file(&metadata, ArchiveEntryKind::Other);
346// Place the rmeta-link member immediately after metadata so consumers
347 // can find it without iterating the whole archive.
348if let Some(file) = &metadata_link_file {
349ab.add_file(file, ArchiveEntryKind::Other);
350 }
351None352 }
353 MetadataPosition::Last => Some(metadata),
354 }
355 }
356357 RlibFlavor::StaticlibBase => None,
358 };
359360for m in &compiled_modules.modules {
361if let Some(obj) = m.object.as_ref() {
362 ab.add_file(obj, ArchiveEntryKind::RustObj);
363 }
364365if let Some(obj) = m.global_asm_object.as_ref() {
366 ab.add_file(obj, ArchiveEntryKind::RustObj);
367 }
368369if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
370 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
371 }
372 }
373374match flavor {
375 RlibFlavor::Normal => {}
376 RlibFlavor::StaticlibBase => {
377if let Some(m) = &compiled_modules.allocator_module {
378if let Some(obj) = &m.object {
379ab.add_file(obj, ArchiveEntryKind::RustObj);
380 }
381if let Some(obj) = &m.global_asm_object {
382ab.add_file(obj, ArchiveEntryKind::RustObj);
383 }
384 }
385 }
386 }
387388// Used if packed_bundled_libs flag enabled.
389let mut packed_bundled_libs = Vec::new();
390391// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
392 // we may not be configured to actually include a static library if we're
393 // adding it here. That's because later when we consume this rlib we'll
394 // decide whether we actually needed the static library or not.
395 //
396 // To do this "correctly" we'd need to keep track of which libraries added
397 // which object files to the archive. We don't do that here, however. The
398 // #[link(cfg(..))] feature is unstable, though, and only intended to get
399 // liblibc working. In that sense the check below just indicates that if
400 // there are any libraries we want to omit object files for at link time we
401 // just exclude all custom object files.
402 //
403 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
404 // feature then we'll need to figure out how to record what objects were
405 // loaded from the libraries found here and then encode that into the
406 // metadata of the rlib we're generating somehow.
407for lib in crate_info.used_libraries.iter() {
408let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
409continue;
410 };
411if flavor == RlibFlavor::Normal
412 && let Some(filename) = lib.filename
413 {
414let path = find_native_static_library(filename.as_str(), true, sess);
415let src = read(path)
416 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
417let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
418let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
419 packed_bundled_libs.push(wrapper_file);
420 } else {
421let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
422 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
423 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
424 });
425 }
426 }
427428// On Windows, we add the raw-dylib import libraries to the rlibs already.
429 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
430 // Instead, we add all raw-dylibs to the final link on ELF.
431if sess.target.is_like_windows {
432for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
433 sess,
434 archive_builder_builder,
435 crate_info.used_libraries.iter(),
436 tmpdir.as_ref(),
437true,
438 ) {
439 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
440 sess.dcx()
441 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
442 });
443 }
444 }
445446if let Some(trailing_metadata) = trailing_metadata {
447// Note that it is important that we add all of our non-object "magical
448 // files" *after* all of the object files in the archive. The reason for
449 // this is as follows:
450 //
451 // * When performing LTO, this archive will be modified to remove
452 // objects from above. The reason for this is described below.
453 //
454 // * When the system linker looks at an archive, it will attempt to
455 // determine the architecture of the archive in order to see whether its
456 // linkable.
457 //
458 // The algorithm for this detection is: iterate over the files in the
459 // archive. Skip magical SYMDEF names. Interpret the first file as an
460 // object file. Read architecture from the object file.
461 //
462 // * As one can probably see, if "metadata" and "foo.bc" were placed
463 // before all of the objects, then the architecture of this archive would
464 // not be correctly inferred once 'foo.o' is removed.
465 //
466 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
467 // file for the target platform so the rlib can be processed entirely by
468 // normal linkers for the platform. Sometimes this is not possible however.
469 //
470 // Basically, all this means is that this code should not move above the
471 // code above.
472ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
473// Place the rmeta-link member immediately after metadata so consumers can
474 // find it without iterating the whole archive.
475if let Some(file) = &metadata_link_file {
476ab.add_file(file, ArchiveEntryKind::Other);
477 }
478 }
479480// Add all bundled static native library dependencies.
481 // Archives added to the end of .rlib archive, see comment above for the reason.
482for lib in packed_bundled_libs {
483 ab.add_file(&lib, ArchiveEntryKind::Other)
484 }
485486ab487}
488489/// Create a static archive.
490///
491/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
492/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
493/// dependencies as well.
494///
495/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
496/// library dependencies that they're not linked in.
497///
498/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
499/// object file (and also don't prepare the archive with a metadata file).
500fn link_staticlib(
501 sess: &Session,
502 archive_builder_builder: &dyn ArchiveBuilderBuilder,
503 compiled_modules: &CompiledModules,
504 crate_info: &CrateInfo,
505 metadata: &EncodedMetadata,
506 out_filename: &Path,
507 tempdir: &MaybeTempDir,
508) {
509{
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:509",
"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(509u32),
::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);
510let mut ab = link_rlib(
511sess,
512archive_builder_builder,
513compiled_modules,
514crate_info,
515metadata,
516 RlibFlavor::StaticlibBase,
517tempdir,
518 );
519let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
520521let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
522let lto = are_upstream_rust_objects_already_included(sess)
523 && !ignored_for_lto(sess, crate_info, cnum);
524525let native_libs = crate_info.native_libraries[&cnum].iter();
526let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
527let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
528529let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
530ab.add_archive(
531path,
532 AddArchiveKind::Rlib(&|fname: &str, entry_kind| {
533// Ignore metadata and rmeta-link files.
534if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
535return true;
536 }
537538// Don't include Rust objects if LTO is enabled.
539if lto && entry_kind == ArchiveEntryKind::RustObj {
540return true;
541 }
542543// Skip objects for bundled libs.
544if bundled_libs.contains(&Symbol::intern(fname)) {
545return true;
546 }
547548false
549}),
550 )
551 .unwrap();
552553archive_builder_builder554 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
555 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
556557for filename in relevant_libs.iter() {
558let joined = tempdir.as_ref().join(filename.as_str());
559let path = joined.as_path();
560 ab.add_archive(path, AddArchiveKind::Other).unwrap();
561 }
562563all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
564 });
565if let Err(e) = res {
566sess.dcx().emit_fatal(e);
567 }
568569let exported_symbols = if sess.opts.unstable_opts.staticlib_hide_internal_symbols {
570if !#[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) {
571sess.dcx().emit_warn(errors::StaticlibHideInternalSymbolsUnsupported {
572 binary_format: sess.target.archive_format.to_string(),
573 });
574None575 } else {
576crate_info577 .exported_symbols
578 .get(&CrateType::StaticLib)
579 .map(|symbols| symbols.iter().map(|(s, _)| s.clone()).collect())
580 }
581 } else {
582None583 };
584ab.build(out_filename, exported_symbols);
585586let crates = crate_info.used_crates.iter();
587588let fmts = crate_info589 .dependency_formats
590 .get(&CrateType::StaticLib)
591 .expect("no dependency formats for staticlib");
592593let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
594for &cnum in crates {
595let Some(Linkage::Dynamic) = fmts.get(cnum) else {
596continue;
597 };
598let crate_name = crate_info.crate_name[&cnum];
599let used_crate_source = &crate_info.used_crate_source[&cnum];
600if let Some(path) = &used_crate_source.dylib {
601 all_rust_dylibs.push(&**path);
602 } else if used_crate_source.rmeta.is_some() {
603 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
604 } else {
605 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
606 }
607 }
608609all_native_libs.extend_from_slice(&crate_info.used_libraries);
610611for print in &sess.opts.prints {
612if print.kind == PrintKind::NativeStaticLibs {
613 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
614 }
615 }
616}
617618/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
619/// DWARF package.
620fn link_dwarf_object(
621 sess: &Session,
622 compiled_modules: &CompiledModules,
623 crate_info: &CrateInfo,
624 executable_out_filename: &Path,
625) {
626let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
627dwp_out_filename.push(".dwp");
628{
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:628",
"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(628u32),
::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);
629630#[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)]
631struct ThorinSession<Relocations> {
632 arena_data: TypedArena<Vec<u8>>,
633 arena_mmap: TypedArena<Mmap>,
634 arena_relocations: TypedArena<Relocations>,
635 }
636637impl<Relocations> ThorinSession<Relocations> {
638fn alloc_mmap(&self, data: Mmap) -> &Mmap {
639&*self.arena_mmap.alloc(data)
640 }
641 }
642643impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
644fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
645&*self.arena_data.alloc(data)
646 }
647648fn alloc_relocation(&self, data: Relocations) -> &Relocations {
649&*self.arena_relocations.alloc(data)
650 }
651652fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
653let file = File::open(&path)?;
654let mmap = (unsafe { Mmap::map(file) })?;
655Ok(self.alloc_mmap(mmap))
656 }
657 }
658659match sess.time("run_thorin", || -> Result<(), thorin::Error> {
660let thorin_sess = ThorinSession::default();
661let mut package = thorin::DwarfPackage::new(&thorin_sess);
662663// Input objs contain .o/.dwo files from the current crate.
664match sess.opts.unstable_opts.split_dwarf_kind {
665 SplitDwarfKind::Single => {
666for m in &compiled_modules.modules {
667if let Some(input_obj) = &m.object {
668 package.add_input_object(input_obj)?;
669 }
670if let Some(input_obj) = &m.global_asm_object {
671 package.add_input_object(input_obj)?;
672 }
673 }
674 }
675 SplitDwarfKind::Split => {
676for input_obj in
677compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
678 {
679 package.add_input_object(input_obj)?;
680 }
681 }
682 }
683684// Input rlibs contain .o/.dwo files from dependencies.
685let input_rlibs = crate_info686 .used_crate_source
687 .items()
688 .filter_map(|(_, csource)| csource.rlib.as_ref())
689 .into_sorted_stable_ord();
690691for input_rlib in input_rlibs {
692{
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:692",
"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(692u32),
::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);
693 package.add_input_object(input_rlib)?;
694 }
695696// Failing to read the referenced objects is expected for dependencies where the path in the
697 // executable will have been cleaned by Cargo, but the referenced objects will be contained
698 // within rlibs provided as inputs.
699 //
700 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
701 // found, but are provided explicitly above.
702 //
703 // Adding an executable is primarily done to make `thorin` check that all the referenced
704 // dwarf objects are found in the end.
705package.add_executable(
706 executable_out_filename,
707 thorin::MissingReferencedObjectBehaviour::Skip,
708 )?;
709710let output_stream = BufWriter::new(
711 OpenOptions::new()
712 .read(true)
713 .write(true)
714 .create(true)
715 .truncate(true)
716 .open(dwp_out_filename)?,
717 );
718let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
719 package.finish()?.emit(&mut output_stream)?;
720 output_stream.result()?;
721 output_stream.into_inner().flush()?;
722723Ok(())
724 }) {
725Ok(()) => {}
726Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
727 }
728}
729730#[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)]
731#[diag("{$inner}")]
732/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
733/// end up with inconsistent languages within the same diagnostic.
734struct LinkerOutput {
735 inner: String,
736}
737738fn is_msvc_link_exe(sess: &Session) -> bool {
739let (linker_path, flavor) = linker_and_flavor(sess);
740sess.target.is_like_msvc
741 && flavor == LinkerFlavor::Msvc(Lld::No)
742// Match exactly "link.exe"
743&& linker_path.to_str() == Some("link.exe")
744}
745746fn is_macos_ld(sess: &Session) -> bool {
747let (_, flavor) = linker_and_flavor(sess);
748sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))749}
750751fn is_windows_gnu_ld(sess: &Session) -> bool {
752let (_, flavor) = linker_and_flavor(sess);
753sess.target.is_like_windows
754 && !sess.target.is_like_msvc
755 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))756 && sess.target.options.cfg_abi != CfgAbi::Llvm757}
758759fn is_windows_gnu_clang(sess: &Session) -> bool {
760let (_, flavor) = linker_and_flavor(sess);
761sess.target.is_like_windows
762 && !sess.target.is_like_msvc
763 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))764 && sess.target.options.cfg_abi == CfgAbi::Llvm765}
766767fn report_linker_output(
768 sess: &Session,
769 levels: CodegenLintLevelSpecs,
770 stdout: &[u8],
771 stderr: &[u8],
772) {
773let mut escaped_stderr = escape_string(&stderr);
774let mut escaped_stdout = escape_string(&stdout);
775let mut linker_info = String::new();
776777{
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:777",
"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(777u32),
::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);
778{
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:778",
"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(778u32),
::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);
779780fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
781let mut output = String::new();
782if let Ok(str) = str::from_utf8(bytes) {
783{
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:783",
"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(783u32),
::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}");
784output = String::with_capacity(str.len());
785for line in str.lines() {
786 f(line.trim(), &mut output);
787 }
788 }
789escape_string(output.trim().as_bytes())
790 }
791792if is_msvc_link_exe(sess) {
793{
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:793",
"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(793u32),
::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");
794795escaped_stdout = for_each(&stdout, |line, output| {
796// Hide some progress messages from link.exe that we don't care about.
797 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
798 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
799 // missing, link.exe prints the path of the missing .exe followed by:
800let ilk_but_no_exe =
801"not found or not built by the last incremental link; performing full link";
802let trimmed = line.trim_start();
803if trimmed.starts_with("Creating library")
804 || trimmed.starts_with("Generating code")
805 || trimmed.starts_with("Finished generating code")
806 || trimmed.ends_with(ilk_but_no_exe)
807 {
808linker_info += line;
809linker_info += "\r\n";
810 } else {
811*output += line;
812*output += "\r\n"
813}
814 });
815 } else if is_macos_ld(sess) {
816{
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:816",
"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(816u32),
::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");
817818// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
819let deployment_mismatch = |line: &str| {
820// ld64 (object files + dylibs) and ld_prime (object files only):
821(line.starts_with("ld: ")
822 && line.contains("was built for newer")
823 && line.contains("than being linked"))
824// ld_prime (Xcode 15+, dylibs only):
825|| (line.starts_with("ld: ")
826 && line.contains("building for")
827 && line.contains("but linking with")
828 && line.contains("which was built for newer version"))
829 };
830// FIXME: This is a real warning we would like to show, but it hits too many crates
831 // to want to turn it on immediately.
832let search_path = |line: &str| {
833line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
834 };
835escaped_stderr = for_each(&stderr, |line, output| {
836// This duplicate library warning is just not helpful at all.
837if line.starts_with("ld: warning: ignoring duplicate libraries: ")
838 || deployment_mismatch(line)
839 || search_path(line)
840 {
841linker_info += line;
842linker_info += "\n";
843 } else {
844*output += line;
845*output += "\n"
846}
847 });
848 } else if is_windows_gnu_ld(sess) {
849{
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:849",
"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(849u32),
::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");
850851let mut saw_exclude_symbol = false;
852// See https://github.com/rust-lang/rust/issues/112368.
853 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
854let exclude_symbols = |line: &str| {
855line.starts_with("Warning: .drectve `-exclude-symbols:")
856 && line.ends_with("' unrecognized")
857 };
858escaped_stderr = for_each(&stderr, |line, output| {
859if exclude_symbols(line) {
860saw_exclude_symbol = true;
861linker_info += line;
862linker_info += "\n";
863 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
864linker_info += line;
865linker_info += "\n";
866 } else {
867*output += line;
868*output += "\n"
869}
870 });
871 } else if is_windows_gnu_clang(sess) {
872{
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:872",
"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(872u32),
::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)");
873escaped_stderr = for_each(&stderr, |line, output| {
874if line.contains("argument unused during compilation: '-nolibc'") {
875linker_info += line;
876linker_info += "\n";
877 } else {
878*output += line;
879*output += "\n"
880}
881 });
882 };
883884let lint_msg = |msg| {
885emit_lint_base(
886sess,
887LINKER_MESSAGES,
888levels.linker_messages,
889None,
890LinkerOutput { inner: msg },
891 );
892 };
893let lint_info = |msg| {
894emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
895 };
896897if !escaped_stderr.is_empty() {
898// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
899escaped_stderr =
900escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
901// Windows GNU LD prints uppercase Warning
902escaped_stderr = escaped_stderr903 .strip_prefix("Warning: ")
904 .unwrap_or(&escaped_stderr)
905 .replace(": warning: ", ": ");
906lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
907 }
908if !escaped_stdout.is_empty() {
909lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
910 }
911if !linker_info.is_empty() {
912lint_info(linker_info);
913 }
914}
915916/// Create a dynamic library or executable.
917///
918/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
919/// files as well.
920fn link_natively(
921 sess: &Session,
922 archive_builder_builder: &dyn ArchiveBuilderBuilder,
923 crate_type: CrateType,
924 out_filename: &Path,
925 compiled_modules: &CompiledModules,
926 crate_info: &CrateInfo,
927 metadata: &EncodedMetadata,
928 tmpdir: &Path,
929 codegen_backend: &'static str,
930) {
931{
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:931",
"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(931u32),
::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);
932let (linker_path, flavor) = linker_and_flavor(sess);
933let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
934935// On AIX, we ship all libraries as .a big_af archive
936 // the expected format is lib<name>.a(libname.so) for the actual
937 // dynamic library. So we link to a temporary .so file to be archived
938 // at the final out_filename location
939let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
940let archive_member =
941should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
942let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
943944let mut cmd = linker_with_args(
945&linker_path,
946flavor,
947sess,
948archive_builder_builder,
949crate_type,
950tmpdir,
951temp_filename,
952compiled_modules,
953crate_info,
954metadata,
955self_contained_components,
956codegen_backend,
957 );
958959 linker::disable_localization(&mut cmd);
960961for (k, v) in sess.target.link_env.as_ref() {
962 cmd.env(k.as_ref(), v.as_ref());
963 }
964for k in sess.target.link_env_remove.as_ref() {
965 cmd.env_remove(k.as_ref());
966 }
967968for print in &sess.opts.prints {
969if print.kind == PrintKind::LinkArgs {
970let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
971 print.out.overwrite(&content, sess);
972 }
973 }
974975// May have not found libraries in the right formats.
976sess.dcx().abort_if_errors();
977978// Invoke the system linker
979{
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:979",
"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(979u32),
::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:?}");
980let unknown_arg_regex =
981Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
982let mut prog;
983loop {
984prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
985let Ok(ref output) = progelse {
986break;
987 };
988if output.status.success() {
989break;
990 }
991let mut out = output.stderr.clone();
992out.extend(&output.stdout);
993let out = String::from_utf8_lossy(&out);
994995// Check to see if the link failed with an error message that indicates it
996 // doesn't recognize the -no-pie option. If so, re-perform the link step
997 // without it. This is safe because if the linker doesn't support -no-pie
998 // then it should not default to linking executables as pie. Different
999 // versions of gcc seem to use different quotes in the error message so
1000 // don't check for them.
1001if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1002 && unknown_arg_regex.is_match(&out)
1003 && out.contains("-no-pie")
1004 && cmd.get_args().iter().any(|e| e == "-no-pie")
1005 {
1006{
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:1006",
"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(1006u32),
::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);
1007{
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:1007",
"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(1007u32),
::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.");
1008for arg in cmd.take_args() {
1009if arg != "-no-pie" {
1010 cmd.arg(arg);
1011 }
1012 }
1013{
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:1013",
"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(1013u32),
::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:?}");
1014continue;
1015 }
10161017// Check if linking failed with an error message that indicates the driver didn't recognize
1018 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1019 // to spawn multiple instances on the happy path to do version checking, and ensures things
1020 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1021 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1022if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1023 && unknown_arg_regex.is_match(&out)
1024 && out.contains("-fuse-ld=lld")
1025 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
1026 {
1027{
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:1027",
"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(1027u32),
::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);
1028{
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:1028",
"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(1028u32),
::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.");
1029for arg in cmd.take_args() {
1030if arg.to_string_lossy() != "-fuse-ld=lld" {
1031 cmd.arg(arg);
1032 }
1033 }
1034{
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:1034",
"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(1034u32),
::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:?}");
1035continue;
1036 }
10371038// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1039 // Fallback from '-static-pie' to '-static' in that case.
1040if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1041 && unknown_arg_regex.is_match(&out)
1042 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1043 && cmd.get_args().iter().any(|e| e == "-static-pie")
1044 {
1045{
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:1045",
"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(1045u32),
::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);
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::WARN,
::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::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!(
1047"Linker does not support -static-pie command line option. Retrying with -static instead."
1048);
1049// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1050let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1051let opts = &sess.target;
1052let pre_objects = if self_contained_crt_objects {
1053&opts.pre_link_objects_self_contained
1054 } else {
1055&opts.pre_link_objects
1056 };
1057let post_objects = if self_contained_crt_objects {
1058&opts.post_link_objects_self_contained
1059 } else {
1060&opts.post_link_objects
1061 };
1062let get_objects = |objects: &CrtObjects, kind| {
1063objects1064 .get(&kind)
1065 .iter()
1066 .copied()
1067 .flatten()
1068 .map(|obj| {
1069get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1070 })
1071 .collect::<Vec<_>>()
1072 };
1073let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1074let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1075let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1076let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1077// Assume that we know insertion positions for the replacement arguments from replaced
1078 // arguments, which is true for all supported targets.
1079if !(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());
1080if !(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());
1081for arg in cmd.take_args() {
1082if arg == "-static-pie" {
1083// Replace the output kind.
1084cmd.arg("-static");
1085 } else if pre_objects_static_pie.contains(&arg) {
1086// Replace the pre-link objects (replace the first and remove the rest).
1087cmd.args(mem::take(&mut pre_objects_static));
1088 } else if post_objects_static_pie.contains(&arg) {
1089// Replace the post-link objects (replace the first and remove the rest).
1090cmd.args(mem::take(&mut post_objects_static));
1091 } else {
1092 cmd.arg(arg);
1093 }
1094 }
1095{
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:1095",
"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(1095u32),
::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:?}");
1096continue;
1097 }
10981099break;
1100 }
11011102match prog {
1103Ok(prog) => {
1104if !prog.status.success() {
1105let mut output = prog.stderr.clone();
1106output.extend_from_slice(&prog.stdout);
1107let escaped_output = escape_linker_output(&output, flavor);
1108let err = errors::LinkingFailed {
1109 linker_path: &linker_path,
1110 exit_status: prog.status,
1111 command: cmd,
1112escaped_output,
1113 verbose: sess.opts.verbose,
1114 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1115 };
1116sess.dcx().emit_err(err);
1117// If MSVC's `link.exe` was expected but the return code
1118 // is not a Microsoft LNK error then suggest a way to fix or
1119 // install the Visual Studio build tools.
1120if let Some(code) = prog.status.code() {
1121// All Microsoft `link.exe` linking ror codes are
1122 // four digit numbers in the range 1000 to 9999 inclusive
1123if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1124let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1125let has_linker =
1126 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1127 .is_some();
11281129sess.dcx().emit_note(errors::LinkExeUnexpectedError);
11301131// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1132 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1133const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1134if code == STATUS_STACK_BUFFER_OVERRUN {
1135sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1136 }
11371138if is_vs_installed && has_linker {
1139// the linker is broken
1140sess.dcx().emit_note(errors::RepairVSBuildTools);
1141sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1142 } else if is_vs_installed {
1143// the linker is not installed
1144sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1145 } else {
1146// visual studio is not installed
1147sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1148 }
1149 }
1150 }
11511152sess.dcx().abort_if_errors();
1153 }
11541155{
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:1155",
"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(1155u32),
::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:?}");
1156report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1157 }
1158Err(e) => {
1159let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11601161let err = if linker_not_found {
1162sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1163 } else {
1164sess.dcx().emit_err(errors::UnableToExeLinker {
1165linker_path,
1166 error: e,
1167 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1168 })
1169 };
11701171if sess.target.is_like_msvc && linker_not_found {
1172sess.dcx().emit_note(errors::MsvcMissingLinker);
1173sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1174sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1175 }
1176err.raise_fatal();
1177 }
1178 }
11791180match sess.split_debuginfo() {
1181// If split debug information is disabled or located in individual files
1182 // there's nothing to do here.
1183SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
11841185// If packed split-debuginfo is requested, but the final compilation
1186 // doesn't actually have any debug information, then we skip this step.
1187SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
11881189// On macOS the external `dsymutil` tool is used to create the packed
1190 // debug information. Note that this will read debug information from
1191 // the objects on the filesystem which we'll clean up later.
1192SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1193let prog = Command::new("dsymutil").arg(out_filename).output();
1194match prog {
1195Ok(prog) => {
1196if !prog.status.success() {
1197let mut output = prog.stderr.clone();
1198output.extend_from_slice(&prog.stdout);
1199sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1200 status: prog.status,
1201 output: escape_string(&output),
1202 });
1203 }
1204 }
1205Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1206 }
1207 }
12081209// On MSVC packed debug information is produced by the linker itself so
1210 // there's no need to do anything else here.
1211SplitDebuginfo::Packedif sess.target.is_like_windows => {}
12121213// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1214 //
1215 // We cannot rely on the .o paths in the executable because they may have been
1216 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1217 // the .o/.dwo paths explicitly.
1218SplitDebuginfo::Packed => {
1219link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1220 }
1221 }
12221223let strip = sess.opts.cg.strip;
12241225if sess.target.is_like_darwin {
1226let stripcmd = "rust-objcopy";
1227match (strip, crate_type) {
1228 (Strip::Debuginfo, _) => {
1229strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1230 }
12311232// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1233(
1234 Strip::Symbols,
1235 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1236 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1237 (Strip::Symbols, _) => {
1238strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1239 }
1240 (Strip::None, _) => {}
1241 }
1242 }
12431244if sess.target.is_like_solaris {
1245// Many illumos systems will have both the native 'strip' utility and
1246 // the GNU one. Use the native version explicitly and do not rely on
1247 // what's in the path.
1248 //
1249 // If cross-compiling and there is not a native version, then use
1250 // `llvm-strip` and hope.
1251let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1252match strip {
1253// Always preserve the symbol table (-x).
1254Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1255// Strip::Symbols is handled via the --strip-all linker option.
1256Strip::Symbols => {}
1257 Strip::None => {}
1258 }
1259 }
12601261if sess.target.is_like_aix {
1262// `llvm-strip` doesn't work for AIX - their strip must be used.
1263if !sess.host.is_like_aix {
1264sess.dcx().emit_warn(errors::AixStripNotUsed);
1265 }
1266let stripcmd = "/usr/bin/strip";
1267match strip {
1268 Strip::Debuginfo => {
1269// FIXME: AIX's strip utility only offers option to strip line number information.
1270strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1271 }
1272 Strip::Symbols => {
1273// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1274strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1275 }
1276 Strip::None => {}
1277 }
1278 }
12791280if should_archive {
1281let mut ab = archive_builder_builder.new_archive_builder(sess);
1282ab.add_file(temp_filename, ArchiveEntryKind::Other);
1283ab.build(out_filename, None);
1284 }
1285}
12861287fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1288let mut cmd = Command::new(util);
1289cmd.args(options);
12901291let mut new_path = sess.get_tools_search_paths(false);
1292if let Some(path) = env::var_os("PATH") {
1293new_path.extend(env::split_paths(&path));
1294 }
1295cmd.env("PATH", env::join_paths(new_path).unwrap());
12961297let prog = cmd.arg(out_filename).output();
1298match prog {
1299Ok(prog) => {
1300if !prog.status.success() {
1301let mut output = prog.stderr.clone();
1302output.extend_from_slice(&prog.stdout);
1303sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1304util,
1305 status: prog.status,
1306 output: escape_string(&output),
1307 });
1308 }
1309 }
1310Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1311 }
1312}
13131314fn escape_string(s: &[u8]) -> String {
1315match str::from_utf8(s) {
1316Ok(s) => s.to_owned(),
1317Err(_) => ::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()),
1318 }
1319}
13201321#[cfg(not(windows))]
1322fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1323escape_string(s)
1324}
13251326/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1327/// then try to convert the string from the OEM encoding.
1328#[cfg(windows)]
1329fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1330// This only applies to the actual MSVC linker.
1331if flavour != LinkerFlavor::Msvc(Lld::No) {
1332return escape_string(s);
1333 }
1334match str::from_utf8(s) {
1335Ok(s) => return s.to_owned(),
1336Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1337Some(s) => s,
1338// The string is not UTF-8 and isn't valid for the OEM code page
1339None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1340 },
1341 }
1342}
13431344/// Wrappers around the Windows API.
1345#[cfg(windows)]
1346mod win {
1347use windows::Win32::Globalization::{
1348 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1349 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1350 };
13511352/// Get the Windows system OEM code page. This is most notably the code page
1353 /// used for link.exe's output.
1354pub(super) fn oem_code_page() -> u32 {
1355unsafe {
1356let mut cp: u32 = 0;
1357// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1358 // But the API requires us to pass the data as though it's a [u16] string.
1359let len = size_of::<u32>() / size_of::<u16>();
1360let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1361let len_written = GetLocaleInfoEx(
1362 LOCALE_NAME_SYSTEM_DEFAULT,
1363 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1364Some(data),
1365 );
1366if len_written as usize == len { cp } else { CP_OEMCP }
1367 }
1368 }
1369/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1370 /// The string does not need to be null terminated.
1371 ///
1372 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1373 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1374 ///
1375 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1376 /// any invalid bytes for the expected encoding.
1377pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1378// `MultiByteToWideChar` requires a length to be a "positive integer".
1379if s.len() > isize::MAX as usize {
1380return None;
1381 }
1382// Error if the string is not valid for the expected code page.
1383let flags = MB_ERR_INVALID_CHARS;
1384// Call MultiByteToWideChar twice.
1385 // First to calculate the length then to convert the string.
1386let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1387if len > 0 {
1388let mut utf16 = vec![0; len as usize];
1389 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1390if len > 0 {
1391return utf16.get(..len as usize).map(String::from_utf16_lossy);
1392 }
1393 }
1394None
1395}
1396}
13971398fn add_sanitizer_libraries(
1399 sess: &Session,
1400 flavor: LinkerFlavor,
1401 crate_type: CrateType,
1402 linker: &mut dyn Linker,
1403) {
1404if sess.target.is_like_android {
1405// Sanitizer runtime libraries are provided dynamically on Android
1406 // targets.
1407return;
1408 }
14091410if sess.opts.unstable_opts.external_clangrt {
1411// Linking against in-tree sanitizer runtimes is disabled via
1412 // `-Z external-clangrt`
1413return;
1414 }
14151416if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1417return;
1418 }
14191420// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1421 // which should be linked to both executables and dynamic libraries.
1422 // Everywhere else the runtimes are currently distributed as static
1423 // libraries which should be linked to executables only.
1424if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1425 crate_type,
1426 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1427 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1428 {
1429return;
1430 }
14311432let sanitizer = sess.sanitizers();
1433if sanitizer.contains(SanitizerSet::ADDRESS) {
1434link_sanitizer_runtime(sess, flavor, linker, "asan");
1435 }
1436if sanitizer.contains(SanitizerSet::DATAFLOW) {
1437link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1438 }
1439if sanitizer.contains(SanitizerSet::LEAK)
1440 && !sanitizer.contains(SanitizerSet::ADDRESS)
1441 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1442 {
1443link_sanitizer_runtime(sess, flavor, linker, "lsan");
1444 }
1445if sanitizer.contains(SanitizerSet::MEMORY) {
1446link_sanitizer_runtime(sess, flavor, linker, "msan");
1447 }
1448if sanitizer.contains(SanitizerSet::THREAD) {
1449link_sanitizer_runtime(sess, flavor, linker, "tsan");
1450 }
1451if sanitizer.contains(SanitizerSet::HWADDRESS) {
1452link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1453 }
1454if sanitizer.contains(SanitizerSet::SAFESTACK) {
1455link_sanitizer_runtime(sess, flavor, linker, "safestack");
1456 }
1457if sanitizer.contains(SanitizerSet::REALTIME) {
1458link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1459 }
1460}
14611462fn link_sanitizer_runtime(
1463 sess: &Session,
1464 flavor: LinkerFlavor,
1465 linker: &mut dyn Linker,
1466 name: &str,
1467) {
1468fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1469let path = sess.target_tlib_path.dir.join(filename);
1470if path.exists() {
1471sess.target_tlib_path.dir.clone()
1472 } else {
1473 filesearch::make_target_lib_path(
1474&sess.opts.sysroot.default,
1475sess.opts.target_triple.tuple(),
1476 )
1477 }
1478 }
14791480let channel =
1481::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();
14821483if sess.target.is_like_darwin {
1484// On Apple platforms, the sanitizer is always built as a dylib, and
1485 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1486 // rpath to the library as well (the rpath should be absolute, see
1487 // PR #41352 for details).
1488let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1489let path = find_sanitizer_runtime(sess, &filename);
1490let rpath = path.to_str().expect("non-utf8 component in path");
1491linker.link_args(&["-rpath", rpath]);
1492linker.link_dylib_by_name(&filename, false, true);
1493 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1494// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1495 // compatible ASAN library.
1496linker.link_arg("/INFERASANLIBS");
1497 } else {
1498let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1499let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1500linker.link_staticlib_by_path(&path, true);
1501 }
1502}
15031504/// Returns a boolean indicating whether the specified crate should be ignored
1505/// during LTO.
1506///
1507/// Crates ignored during LTO are not lumped together in the "massive object
1508/// file" that we create and are linked in their normal rlib states. See
1509/// comments below for what crates do not participate in LTO.
1510///
1511/// It's unusual for a crate to not participate in LTO. Typically only
1512/// compiler-specific and unstable crates have a reason to not participate in
1513/// LTO.
1514pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1515// If our target enables builtin function lowering in LLVM then the
1516 // crates providing these functions don't participate in LTO (e.g.
1517 // no_builtins or compiler builtins crates).
1518!sess.target.no_builtins
1519 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1520}
15211522/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1523pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1524fn infer_from(
1525 sess: &Session,
1526 linker: Option<PathBuf>,
1527 flavor: Option<LinkerFlavor>,
1528 features: LinkerFeaturesCli,
1529 ) -> Option<(PathBuf, LinkerFlavor)> {
1530let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1531match (linker, flavor) {
1532 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1533// only the linker flavor is known; use the default linker for the selected flavor
1534(None, Some(flavor)) => Some((
1535PathBuf::from(match flavor {
1536 LinkerFlavor::Gnu(Cc::Yes, _)
1537 | LinkerFlavor::Darwin(Cc::Yes, _)
1538 | LinkerFlavor::WasmLld(Cc::Yes)
1539 | LinkerFlavor::Unix(Cc::Yes) => {
1540if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1541// On historical Solaris systems, "cc" may have
1542 // been Sun Studio, which is not flag-compatible
1543 // with "gcc". This history casts a long shadow,
1544 // and many modern illumos distributions today
1545 // ship GCC as "gcc" without also making it
1546 // available as "cc".
1547"gcc"
1548} else {
1549"cc"
1550}
1551 }
1552 LinkerFlavor::Gnu(_, Lld::Yes)
1553 | LinkerFlavor::Darwin(_, Lld::Yes)
1554 | LinkerFlavor::WasmLld(..)
1555 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1556 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1557"ld"
1558}
1559 LinkerFlavor::Msvc(..) => "link.exe",
1560 LinkerFlavor::EmCc => {
1561if falsecfg!(windows) {
1562"emcc.bat"
1563} else {
1564"emcc"
1565}
1566 }
1567 LinkerFlavor::Bpf => "bpf-linker",
1568 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1569 }),
1570flavor,
1571 )),
1572 (Some(linker), None) => {
1573let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1574sess.dcx().emit_fatal(errors::LinkerFileStem);
1575 });
1576let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1577let flavor = adjust_flavor_to_features(flavor, features);
1578Some((linker, flavor))
1579 }
1580 (None, None) => None,
1581 }
1582 }
15831584// While linker flavors and linker features are isomorphic (and thus targets don't need to
1585 // define features separately), we use the flavor as the root piece of data and have the
1586 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1587 // both yet.
1588fn adjust_flavor_to_features(
1589 flavor: LinkerFlavor,
1590 features: LinkerFeaturesCli,
1591 ) -> LinkerFlavor {
1592// Note: a linker feature cannot be both enabled and disabled on the CLI.
1593if features.enabled.contains(LinkerFeatures::LLD) {
1594flavor.with_lld_enabled()
1595 } else if features.disabled.contains(LinkerFeatures::LLD) {
1596flavor.with_lld_disabled()
1597 } else {
1598flavor1599 }
1600 }
16011602let features = sess.opts.cg.linker_features;
16031604// linker and linker flavor specified via command line have precedence over what the target
1605 // specification specifies
1606let linker_flavor = match sess.opts.cg.linker_flavor {
1607// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1608Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1609// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1610linker_flavor => {
1611linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1612 }
1613 };
1614if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1615return ret;
1616 }
16171618if let Some(ret) = infer_from(
1619sess,
1620sess.target.linker.as_deref().map(PathBuf::from),
1621Some(sess.target.linker_flavor),
1622features,
1623 ) {
1624return ret;
1625 }
16261627::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");
1628}
16291630/// Returns a pair of boolean indicating whether we should preserve the object and
1631/// dwarf object files on the filesystem for their debug information. This is often
1632/// useful with split-dwarf like schemes.
1633fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1634// If the objects don't have debuginfo there's nothing to preserve.
1635if sess.opts.debuginfo == config::DebugInfo::None {
1636return (false, false);
1637 }
16381639match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1640// If there is no split debuginfo then do not preserve objects.
1641(SplitDebuginfo::Off, _) => (false, false),
1642// If there is packed split debuginfo, then the debuginfo in the objects
1643 // has been packaged and the objects can be deleted.
1644(SplitDebuginfo::Packed, _) => (false, false),
1645// If there is unpacked split debuginfo and the current target can not use
1646 // split dwarf, then keep objects.
1647(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1648// If there is unpacked split debuginfo and the target can use split dwarf, then
1649 // keep the object containing that debuginfo (whether that is an object file or
1650 // dwarf object file depends on the split dwarf kind).
1651(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1652 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1653 }
1654}
16551656#[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)]
1657enum RlibFlavor {
1658 Normal,
1659 StaticlibBase,
1660}
16611662fn print_native_static_libs(
1663 sess: &Session,
1664 out: &OutFileName,
1665 all_native_libs: &[NativeLib],
1666 all_rust_dylibs: &[&Path],
1667) {
1668let mut lib_args: Vec<_> = all_native_libs1669 .iter()
1670 .filter(|l| relevant_lib(sess, l))
1671 .filter_map(|lib| {
1672let name = lib.name;
1673match lib.kind {
1674 NativeLibKind::Static { bundle: Some(false), .. }
1675 | NativeLibKind::Dylib { .. }
1676 | NativeLibKind::Unspecified => {
1677let verbatim = lib.verbatim;
1678if sess.target.is_like_msvc {
1679let (prefix, suffix) = sess.staticlib_components(verbatim);
1680Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1681 } else if sess.target.linker_flavor.is_gnu() {
1682Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1683 } else {
1684Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1685 }
1686 }
1687 NativeLibKind::Framework { .. } => {
1688// ld-only syntax, since there are no frameworks in MSVC
1689Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1690 }
1691// These are included, no need to print them
1692NativeLibKind::Static { bundle: None | Some(true), .. }
1693 | NativeLibKind::LinkArg1694 | NativeLibKind::WasmImportModule1695 | NativeLibKind::RawDylib { .. } => None,
1696 }
1697 })
1698// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1699.dedup()
1700 .collect();
1701for path in all_rust_dylibs {
1702// FIXME deduplicate with add_dynamic_crate
17031704 // Just need to tell the linker about where the library lives and
1705 // what its name is
1706let parent = path.parent();
1707if let Some(dir) = parent {
1708let dir = fix_windows_verbatim_for_gcc(dir);
1709if sess.target.is_like_msvc {
1710let mut arg = String::from("/LIBPATH:");
1711 arg.push_str(&dir.display().to_string());
1712 lib_args.push(arg);
1713 } else {
1714 lib_args.push("-L".to_owned());
1715 lib_args.push(dir.display().to_string());
1716 }
1717 }
1718let stem = path.file_stem().unwrap().to_str().unwrap();
1719// Convert library file-stem into a cc -l argument.
1720let lib = if let Some(lib) = stem.strip_prefix("lib")
1721 && !sess.target.is_like_windows
1722 {
1723 lib
1724 } else {
1725 stem
1726 };
1727let path = parent.unwrap_or_else(|| Path::new(""));
1728if sess.target.is_like_msvc {
1729// When producing a dll, the MSVC linker may not actually emit a
1730 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1731 // check to see if the file is there and just omit linking to it if it's
1732 // not present.
1733let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1734if path.join(&name).exists() {
1735 lib_args.push(name);
1736 }
1737 } else {
1738 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1739 }
1740 }
17411742match out {
1743 OutFileName::Real(path) => {
1744out.overwrite(&lib_args.join(" "), sess);
1745sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1746 }
1747 OutFileName::Stdout => {
1748sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1749// Prefix for greppability
1750 // Note: This must not be translated as tools are allowed to depend on this exact string.
1751sess.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(" ")));
1752 }
1753 }
1754}
17551756fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1757let file_path = sess.target_tlib_path.dir.join(name);
1758if file_path.exists() {
1759return file_path;
1760 }
1761// Special directory with objects used only in self-contained linkage mode
1762if self_contained {
1763let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1764if file_path.exists() {
1765return file_path;
1766 }
1767 }
1768for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1769let file_path = search_path.dir.join(name);
1770if file_path.exists() {
1771return file_path;
1772 }
1773 }
1774PathBuf::from(name)
1775}
17761777fn exec_linker(
1778 sess: &Session,
1779 cmd: &Command,
1780 out_filename: &Path,
1781 flavor: LinkerFlavor,
1782 tmpdir: &Path,
1783) -> io::Result<Output> {
1784// When attempting to spawn the linker we run a risk of blowing out the
1785 // size limits for spawning a new process with respect to the arguments
1786 // we pass on the command line.
1787 //
1788 // Here we attempt to handle errors from the OS saying "your list of
1789 // arguments is too big" by reinvoking the linker again with an `@`-file
1790 // that contains all the arguments (aka 'response' files).
1791 // The theory is that this is then accepted on all linkers and the linker
1792 // will read all its options out of there instead of looking at the command line.
1793if !cmd.very_likely_to_exceed_some_spawn_limit() {
1794match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1795Ok(child) => {
1796let output = child.wait_with_output();
1797 flush_linked_file(&output, out_filename)?;
1798return output;
1799 }
1800Err(ref e) if command_line_too_big(e) => {
1801{
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:1801",
"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(1801u32),
::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);
1802 }
1803Err(e) => return Err(e),
1804 }
1805 }
18061807{
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:1807",
"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(1807u32),
::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");
1808let mut cmd2 = cmd.clone();
1809let mut args = String::new();
1810for arg in cmd2.take_args() {
1811 args.push_str(
1812&Escape {
1813 arg: arg.to_str().unwrap(),
1814// Windows-style escaping for @-files is used by
1815 // - all linkers targeting MSVC-like targets, including LLD
1816 // - all LLD flavors running on Windows hosts
1817 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1818is_like_msvc: sess.target.is_like_msvc
1819 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1820 }
1821 .to_string(),
1822 );
1823 args.push('\n');
1824 }
1825let file = tmpdir.join("linker-arguments");
1826let bytes = if sess.target.is_like_msvc {
1827let mut out = Vec::with_capacity((1 + args.len()) * 2);
1828// start the stream with a UTF-16 BOM
1829for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1830// encode in little endian
1831out.push(c as u8);
1832 out.push((c >> 8) as u8);
1833 }
1834out1835 } else {
1836args.into_bytes()
1837 };
1838 fs::write(&file, &bytes)?;
1839cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1840{
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:1840",
"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(1840u32),
::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);
1841let output = cmd2.output();
1842 flush_linked_file(&output, out_filename)?;
1843return output;
18441845#[cfg(not(windows))]
1846fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1847Ok(())
1848 }
18491850#[cfg(windows)]
1851fn flush_linked_file(
1852 command_output: &io::Result<Output>,
1853 out_filename: &Path,
1854 ) -> io::Result<()> {
1855// On Windows, under high I/O load, output buffers are sometimes not flushed,
1856 // even long after process exit, causing nasty, non-reproducible output bugs.
1857 //
1858 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1859 //
1860 // А full writeup of the original Chrome bug can be found at
1861 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18621863if let &Ok(ref out) = command_output {
1864if out.status.success() {
1865if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1866 of.sync_all()?;
1867 }
1868 }
1869 }
18701871Ok(())
1872 }
18731874#[cfg(unix)]
1875fn command_line_too_big(err: &io::Error) -> bool {
1876err.raw_os_error() == Some(::libc::E2BIG)
1877 }
18781879#[cfg(windows)]
1880fn command_line_too_big(err: &io::Error) -> bool {
1881const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1882 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1883 }
18841885#[cfg(not(any(unix, windows)))]
1886fn command_line_too_big(_: &io::Error) -> bool {
1887false
1888}
18891890struct Escape<'a> {
1891 arg: &'a str,
1892 is_like_msvc: bool,
1893 }
18941895impl<'a> fmt::Displayfor Escape<'a> {
1896fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1897if self.is_like_msvc {
1898// This is "documented" at
1899 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1900 //
1901 // Unfortunately there's not a great specification of the
1902 // syntax I could find online (at least) but some local
1903 // testing showed that this seemed sufficient-ish to catch
1904 // at least a few edge cases.
1905f.write_fmt(format_args!("\""))write!(f, "\"")?;
1906for c in self.arg.chars() {
1907match c {
1908'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1909 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1910 }
1911 }
1912f.write_fmt(format_args!("\""))write!(f, "\"")?;
1913 } else {
1914// This is documented at https://linux.die.net/man/1/ld, namely:
1915 //
1916 // > Options in file are separated by whitespace. A whitespace
1917 // > character may be included in an option by surrounding the
1918 // > entire option in either single or double quotes. Any
1919 // > character (including a backslash) may be included by
1920 // > prefixing the character to be included with a backslash.
1921 //
1922 // We put an argument on each line, so all we need to do is
1923 // ensure the line is interpreted as one whole argument.
1924for c in self.arg.chars() {
1925match c {
1926'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1927 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1928 }
1929 }
1930 }
1931Ok(())
1932 }
1933 }
1934}
19351936fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1937let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1938 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1939 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1940 LinkOutputKind::DynamicPicExe1941 }
1942 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1943 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1944 LinkOutputKind::StaticPicExe1945 }
1946 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1947 (_, true, _) => LinkOutputKind::StaticDylib,
1948 (_, false, _) => LinkOutputKind::DynamicDylib,
1949 };
19501951// Adjust the output kind to target capabilities.
1952let opts = &sess.target;
1953let pic_exe_supported = opts.position_independent_executables;
1954let static_pic_exe_supported = opts.static_position_independent_executables;
1955let static_dylib_supported = opts.crt_static_allows_dylibs;
1956match kind {
1957 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1958 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1959 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1960_ => kind,
1961 }
1962}
19631964// Returns true if linker is located within sysroot
1965fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1966let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1967linker.with_extension("exe")
1968 } else {
1969linker.to_path_buf()
1970 };
1971for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1972let full_path = dir.join(&linker_with_extension);
1973// If linker comes from sysroot assume self-contained mode
1974if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1975return false;
1976 }
1977 }
1978true
1979}
19801981/// Various toolchain components used during linking are used from rustc distribution
1982/// instead of being found somewhere on the host system.
1983/// We only provide such support for a very limited number of targets.
1984fn self_contained_components(
1985 sess: &Session,
1986 crate_type: CrateType,
1987 linker: &Path,
1988) -> LinkSelfContainedComponents {
1989// Turn the backwards compatible bool values for `self_contained` into fully inferred
1990 // `LinkSelfContainedComponents`.
1991let self_contained =
1992if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1993// Emit an error if the user requested self-contained mode on the CLI but the target
1994 // explicitly refuses it.
1995if sess.target.link_self_contained.is_disabled() {
1996sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1997 }
1998self_contained1999 } else {
2000match sess.target.link_self_contained {
2001 LinkSelfContainedDefault::False => false,
2002 LinkSelfContainedDefault::True => true,
20032004 LinkSelfContainedDefault::WithComponents(components) => {
2005// For target specs with explicitly enabled components, we can return them
2006 // directly.
2007return components;
2008 }
20092010// FIXME: Find a better heuristic for "native musl toolchain is available",
2011 // based on host and linker path, for example.
2012 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2013LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2014 LinkSelfContainedDefault::InferredForMingw => {
2015sess.host == sess.target
2016 && sess.target.cfg_abi != CfgAbi::Uwp2017 && detect_self_contained_mingw(sess, linker)
2018 }
2019 }
2020 };
2021if self_contained {
2022LinkSelfContainedComponents::all()
2023 } else {
2024LinkSelfContainedComponents::empty()
2025 }
2026}
20272028/// Add pre-link object files defined by the target spec.
2029fn add_pre_link_objects(
2030 cmd: &mut dyn Linker,
2031 sess: &Session,
2032 flavor: LinkerFlavor,
2033 link_output_kind: LinkOutputKind,
2034 self_contained: bool,
2035) {
2036// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2037 // so Fuchsia has to be special-cased.
2038let opts = &sess.target;
2039let empty = Default::default();
2040let objects = if self_contained {
2041&opts.pre_link_objects_self_contained
2042 } 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, _))) {
2043&opts.pre_link_objects
2044 } else {
2045&empty2046 };
2047for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2048 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2049 }
2050}
20512052/// Add post-link object files defined by the target spec.
2053fn add_post_link_objects(
2054 cmd: &mut dyn Linker,
2055 sess: &Session,
2056 link_output_kind: LinkOutputKind,
2057 self_contained: bool,
2058) {
2059let objects = if self_contained {
2060&sess.target.post_link_objects_self_contained
2061 } else {
2062&sess.target.post_link_objects
2063 };
2064for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2065 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2066 }
2067}
20682069/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2070/// FIXME: Determine where exactly these args need to be inserted.
2071fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2072if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2073cmd.verbatim_args(args.iter().map(Deref::deref));
2074 }
20752076cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2077}
20782079/// Add a link script embedded in the target, if applicable.
2080fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2081match (crate_type, &sess.target.link_script) {
2082 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2083if !sess.target.linker_flavor.is_gnu() {
2084sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2085 }
20862087let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
20882089let path = tmpdir.join(file_name);
2090if let Err(error) = fs::write(&path, script.as_ref()) {
2091sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2092 }
20932094cmd.link_arg("--script").link_arg(path);
2095 }
2096_ => {}
2097 }
2098}
20992100/// Add arbitrary "user defined" args defined from command line.
2101/// FIXME: Determine where exactly these args need to be inserted.
2102fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2103cmd.verbatim_args(&sess.opts.cg.link_args);
2104}
21052106/// Add arbitrary "late link" args defined by the target spec.
2107/// FIXME: Determine where exactly these args need to be inserted.
2108fn add_late_link_args(
2109 cmd: &mut dyn Linker,
2110 sess: &Session,
2111 flavor: LinkerFlavor,
2112 crate_type: CrateType,
2113 crate_info: &CrateInfo,
2114) {
2115let any_dynamic_crate = crate_type == CrateType::Dylib2116 || crate_type == CrateType::Sdylib2117 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2118*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2119 });
2120if any_dynamic_crate {
2121if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2122cmd.verbatim_args(args.iter().map(Deref::deref));
2123 }
2124 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2125cmd.verbatim_args(args.iter().map(Deref::deref));
2126 }
2127if let Some(args) = sess.target.late_link_args.get(&flavor) {
2128cmd.verbatim_args(args.iter().map(Deref::deref));
2129 }
2130}
21312132/// Add arbitrary "post-link" args defined by the target spec.
2133/// FIXME: Determine where exactly these args need to be inserted.
2134fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2135if let Some(args) = sess.target.post_link_args.get(&flavor) {
2136cmd.verbatim_args(args.iter().map(Deref::deref));
2137 }
2138}
21392140/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2141/// the linker.
2142///
2143/// Background: we implement rlibs as static library (archives). Linkers treat archives
2144/// differently from object files: all object files participate in linking, while archives will
2145/// only participate in linking if they can satisfy at least one undefined reference (version
2146/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2147/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2148/// can't keep them either. This causes #47384.
2149///
2150/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2151/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2152/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2153/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2154/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2155/// from removing them, and this is especially problematic for embedded programming where every
2156/// byte counts.
2157///
2158/// This method creates a synthetic object file, which contains undefined references to all symbols
2159/// that are necessary for the linking. They are only present in symbol table but not actually
2160/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2161/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2162///
2163/// There's a few internal crates in the standard library (aka libcore and
2164/// libstd) which actually have a circular dependence upon one another. This
2165/// currently arises through "weak lang items" where libcore requires things
2166/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2167/// circular dependence to work correctly we declare some of these things
2168/// in this synthetic object.
2169fn add_linked_symbol_object(
2170 cmd: &mut dyn Linker,
2171 sess: &Session,
2172 tmpdir: &Path,
2173 symbols: &[(String, SymbolExportKind)],
2174) {
2175if symbols.is_empty() {
2176return;
2177 }
21782179let Some(mut file) = super::metadata::create_object_file(sess) else {
2180return;
2181 };
21822183if file.format() == object::BinaryFormat::Coff {
2184// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2185 // so add an empty section.
2186file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
21872188// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2189 // default mangler in `object` crate.
2190file.set_mangling(object::write::Mangling::None);
2191 }
21922193if file.format() == object::BinaryFormat::MachO {
2194// Divide up the sections into sub-sections via symbols for dead code stripping.
2195 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2196 // discard on MachO targets.
2197file.set_subsections_via_symbols();
2198 }
21992200// ld64 requires a relocation to load undefined symbols, see below.
2201 // Not strictly needed if linking with lld, but might as well do it there too.
2202let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2203Some(file.add_section(
2204file.segment_name(object::write::StandardSegment::Data).to_vec(),
2205"__data".into(),
2206 object::SectionKind::Data,
2207 ))
2208 } else {
2209None2210 };
22112212for (sym, kind) in symbols.iter() {
2213let symbol = file.add_symbol(object::write::Symbol {
2214 name: sym.clone().into(),
2215 value: 0,
2216 size: 0,
2217 kind: match kind {
2218 SymbolExportKind::Text => object::SymbolKind::Text,
2219 SymbolExportKind::Data => object::SymbolKind::Data,
2220 SymbolExportKind::Tls => object::SymbolKind::Tls,
2221 },
2222 scope: object::SymbolScope::Unknown,
2223 weak: false,
2224 section: object::write::SymbolSection::Undefined,
2225 flags: object::SymbolFlags::None,
2226 });
22272228// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2229 //
2230 // Code-wise, the relevant parts of ld64 are roughly:
2231 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2232 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2233 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2234 //
2235 // 2. Read the archive table of contents (__.SYMDEF file).
2236 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2237 //
2238 // 3. Begin linking by loading "atoms" from input files.
2239 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2240 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2241 //
2242 // a. Directly specified object files (`.o`) are parsed immediately.
2243 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2244 //
2245 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2246 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2247 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2248 //
2249 // - Relocations/fixups are atoms.
2250 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2251 //
2252 // b. Archives are not parsed yet.
2253 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2254 //
2255 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2256 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2257 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2258 //
2259 // All of the steps above are fairly similar to other linkers, except that **it completely
2260 // ignores undefined symbols**.
2261 //
2262 // So to make this trick work on ld64, we need to do something else to load the relevant
2263 // object files. We do this by inserting a relocation (fixup) for each symbol.
2264if let Some(section) = ld64_section_helper {
2265 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2266 .expect("failed adding relocation");
2267 }
2268 }
22692270let path = tmpdir.join("symbols.o");
2271let result = std::fs::write(&path, file.write().unwrap());
2272if let Err(error) = result {
2273sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2274 }
2275cmd.add_object(&path);
2276}
22772278/// Add object files containing code from the current crate.
2279fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2280for m in &compiled_modules.modules {
2281if let Some(obj) = &m.object {
2282 cmd.add_object(obj);
2283 }
2284if let Some(obj) = &m.global_asm_object {
2285 cmd.add_object(obj);
2286 }
2287 }
2288}
22892290/// Add object files for allocator code linked once for the whole crate tree.
2291fn add_local_crate_allocator_objects(
2292 cmd: &mut dyn Linker,
2293 compiled_modules: &CompiledModules,
2294 crate_info: &CrateInfo,
2295 crate_type: CrateType,
2296) {
2297if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2298 && let Some(m) = &compiled_modules.allocator_module
2299 {
2300if let Some(obj) = &m.object {
2301cmd.add_object(obj);
2302 }
2303if let Some(obj) = &m.global_asm_object {
2304cmd.add_object(obj);
2305 }
2306 }
2307}
23082309/// Add object files containing metadata for the current crate.
2310fn add_local_crate_metadata_objects(
2311 cmd: &mut dyn Linker,
2312 sess: &Session,
2313 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2314 crate_type: CrateType,
2315 tmpdir: &Path,
2316 crate_info: &CrateInfo,
2317 metadata: &EncodedMetadata,
2318) {
2319// When linking a dynamic library, we put the metadata into a section of the
2320 // executable. This metadata is in a separate object file from the main
2321 // object file, so we create and link it in here.
2322if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2323let data = archive_builder_builder.create_dylib_metadata_wrapper(
2324sess,
2325&metadata,
2326&crate_info.metadata_symbol,
2327 );
2328let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
23292330cmd.add_object(&obj);
2331 }
2332}
23332334/// Add sysroot and other globally set directories to the directory search list.
2335fn add_library_search_dirs(
2336 cmd: &mut dyn Linker,
2337 sess: &Session,
2338 self_contained_components: LinkSelfContainedComponents,
2339 apple_sdk_root: Option<&Path>,
2340) {
2341if !sess.opts.unstable_opts.link_native_libraries {
2342return;
2343 }
23442345let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2346let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2347if is_framework {
2348cmd.framework_path(dir);
2349 } else {
2350cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2351 }
2352 ControlFlow::<()>::Continue(())
2353 });
2354}
23552356/// Add options making relocation sections in the produced ELF files read-only
2357/// and suppressing lazy binding.
2358fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2359match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2360 RelroLevel::Full => cmd.full_relro(),
2361 RelroLevel::Partial => cmd.partial_relro(),
2362 RelroLevel::Off => cmd.no_relro(),
2363 RelroLevel::None => {}
2364 }
2365}
23662367/// Add library search paths used at runtime by dynamic linkers.
2368fn add_rpath_args(
2369 cmd: &mut dyn Linker,
2370 sess: &Session,
2371 crate_info: &CrateInfo,
2372 out_filename: &Path,
2373) {
2374if !sess.target.has_rpath {
2375return;
2376 }
23772378// FIXME (#2397): At some point we want to rpath our guesses as to
2379 // where extern libraries might live, based on the
2380 // add_lib_search_paths
2381if sess.opts.cg.rpath {
2382let libs = crate_info2383 .used_crates
2384 .iter()
2385 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2386 .collect::<Vec<_>>();
2387let rpath_config = RPathConfig {
2388 libs: &*libs,
2389 out_filename: out_filename.to_path_buf(),
2390 is_like_darwin: sess.target.is_like_darwin,
2391 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2392 };
2393cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2394 }
2395}
23962397fn add_c_staticlib_symbols(
2398 sess: &Session,
2399 lib: &NativeLib,
2400 out: &mut Vec<(String, SymbolExportKind)>,
2401) -> io::Result<()> {
2402let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
24032404let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
24052406let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2407 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24082409for member in archive.members() {
2410let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24112412let data = member
2413 .data(&*archive_map)
2414 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24152416// clang LTO: raw LLVM bitcode
2417if data.starts_with(b"BC\xc0\xde") {
2418return Err(io::Error::new(
2419 io::ErrorKind::InvalidData,
2420"LLVM bitcode object in C static library (LTO not supported)",
2421 ));
2422 }
24232424let object = object::File::parse(&*data)
2425 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24262427// gcc / clang ELF / Mach-O LTO
2428if object.sections().any(|s| {
2429 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2430 }) {
2431return Err(io::Error::new(
2432 io::ErrorKind::InvalidData,
2433"LTO object in C static library is not supported",
2434 ));
2435 }
24362437for symbol in object.symbols() {
2438if symbol.scope() != object::SymbolScope::Dynamic {
2439continue;
2440 }
24412442let name = match symbol.name() {
2443Ok(n) => n,
2444Err(_) => continue,
2445 };
24462447let export_kind = match symbol.kind() {
2448 object::SymbolKind::Text => SymbolExportKind::Text,
2449 object::SymbolKind::Data => SymbolExportKind::Data,
2450_ => continue,
2451 };
24522453// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2454 // Need to be resolved.
2455out.push((name.to_string(), export_kind));
2456 }
2457 }
24582459Ok(())
2460}
24612462/// Produce the linker command line containing linker path and arguments.
2463///
2464/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2465/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2466/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2467/// to the linking process as a whole.
2468/// Order-independent options may still override each other in order-dependent fashion,
2469/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2470fn linker_with_args(
2471 path: &Path,
2472 flavor: LinkerFlavor,
2473 sess: &Session,
2474 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2475 crate_type: CrateType,
2476 tmpdir: &Path,
2477 out_filename: &Path,
2478 compiled_modules: &CompiledModules,
2479 crate_info: &CrateInfo,
2480 metadata: &EncodedMetadata,
2481 self_contained_components: LinkSelfContainedComponents,
2482 codegen_backend: &'static str,
2483) -> Command {
2484let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2485let cmd = &mut *super::linker::get_linker(
2486sess,
2487path,
2488flavor,
2489self_contained_components.are_any_components_enabled(),
2490&crate_info.target_cpu,
2491codegen_backend,
2492 );
2493let link_output_kind = link_output_kind(sess, crate_type);
24942495let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
24962497if crate_type == CrateType::Cdylib {
2498let mut seen = FxHashSet::default();
24992500for lib in &crate_info.used_libraries {
2501if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2502 && seen.insert((lib.name, lib.verbatim))
2503 {
2504if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2505 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2506"failed to process C static library `{}`: {}",
2507 lib.name, err
2508 ));
2509 }
2510 }
2511 }
2512 }
25132514// ------------ Early order-dependent options ------------
25152516 // If we're building something like a dynamic library then some platforms
2517 // need to make sure that all symbols are exported correctly from the
2518 // dynamic library.
2519 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2520 // at least on some platforms (e.g. windows-gnu).
2521cmd.export_symbols(tmpdir, crate_type, &export_symbols);
25222523// Can be used for adding custom CRT objects or overriding order-dependent options above.
2524 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2525 // introduce a target spec option for order-independent linker options and migrate built-in
2526 // specs to it.
2527add_pre_link_args(cmd, sess, flavor);
25282529// ------------ Object code and libraries, order-dependent ------------
25302531 // Pre-link CRT objects.
2532add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
25332534add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
25352536// Sanitizer libraries.
2537add_sanitizer_libraries(sess, flavor, crate_type, cmd);
25382539// Object code from the current crate.
2540 // Take careful note of the ordering of the arguments we pass to the linker
2541 // here. Linkers will assume that things on the left depend on things to the
2542 // right. Things on the right cannot depend on things on the left. This is
2543 // all formally implemented in terms of resolving symbols (libs on the right
2544 // resolve unknown symbols of libs on the left, but not vice versa).
2545 //
2546 // For this reason, we have organized the arguments we pass to the linker as
2547 // such:
2548 //
2549 // 1. The local object that LLVM just generated
2550 // 2. Local native libraries
2551 // 3. Upstream rust libraries
2552 // 4. Upstream native libraries
2553 //
2554 // The rationale behind this ordering is that those items lower down in the
2555 // list can't depend on items higher up in the list. For example nothing can
2556 // depend on what we just generated (e.g., that'd be a circular dependency).
2557 // Upstream rust libraries are not supposed to depend on our local native
2558 // libraries as that would violate the structure of the DAG, in that
2559 // scenario they are required to link to them as well in a shared fashion.
2560 //
2561 // Note that upstream rust libraries may contain native dependencies as
2562 // well, but they also can't depend on what we just started to add to the
2563 // link line. And finally upstream native libraries can't depend on anything
2564 // in this DAG so far because they can only depend on other native libraries
2565 // and such dependencies are also required to be specified.
2566add_local_crate_regular_objects(cmd, compiled_modules);
2567add_local_crate_metadata_objects(
2568cmd,
2569sess,
2570archive_builder_builder,
2571crate_type,
2572tmpdir,
2573crate_info,
2574metadata,
2575 );
2576add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
25772578// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2579 // at the point at which they are specified on the command line.
2580 // Must be passed before any (dynamic) libraries to have effect on them.
2581 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2582 // so it will ignore unreferenced ELF sections from relocatable objects.
2583 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2584 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2585 // and move this option back to the top.
2586cmd.add_as_needed();
25872588// Local native libraries of all kinds.
2589add_local_native_libraries(
2590cmd,
2591sess,
2592archive_builder_builder,
2593crate_info,
2594tmpdir,
2595link_output_kind,
2596 );
25972598// Upstream rust crates and their non-dynamic native libraries.
2599add_upstream_rust_crates(
2600cmd,
2601sess,
2602archive_builder_builder,
2603crate_info,
2604crate_type,
2605tmpdir,
2606link_output_kind,
2607 );
26082609// Dynamic native libraries from upstream crates.
2610add_upstream_native_libraries(
2611cmd,
2612sess,
2613archive_builder_builder,
2614crate_info,
2615tmpdir,
2616link_output_kind,
2617 );
26182619// Raw-dylibs from all crates.
2620let raw_dylib_dir = tmpdir.join("raw-dylibs");
2621if sess.target.binary_format == BinaryFormat::Elf {
2622// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2623 // instead we need to pass them via -l. To find the stub, we need to add
2624 // the directory of the stub to the linker search path.
2625 // We make an extra directory for this to avoid polluting the search path.
2626if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2627sess.dcx().emit_fatal(errors::CreateTempDir { error })
2628 }
2629cmd.include_path(&raw_dylib_dir);
2630 }
26312632// Link with the import library generated for any raw-dylib functions.
2633if sess.target.is_like_windows {
2634for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2635 sess,
2636 archive_builder_builder,
2637 crate_info.used_libraries.iter(),
2638 tmpdir,
2639true,
2640 ) {
2641 cmd.add_object(&output_path);
2642 }
2643 } else {
2644for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2645 sess,
2646 crate_info.used_libraries.iter(),
2647&raw_dylib_dir,
2648 ) {
2649// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2650cmd.link_dylib_by_name(&link_path, true, as_needed);
2651 }
2652 }
2653// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2654 // they are used within inlined functions or instantiated generic functions. We do this *after*
2655 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2656 // by the linker.
2657let dependency_linkage = crate_info2658 .dependency_formats
2659 .get(&crate_type)
2660 .expect("failed to find crate type in dependency format list");
26612662// We sort the libraries below
2663#[allow(rustc::potential_query_instability)]
2664let mut native_libraries_from_nonstatics = crate_info2665 .native_libraries
2666 .iter()
2667 .filter_map(|(&cnum, libraries)| {
2668if sess.target.is_like_windows {
2669 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2670 } else {
2671Some(libraries)
2672 }
2673 })
2674 .flatten()
2675 .collect::<Vec<_>>();
2676native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
26772678if sess.target.is_like_windows {
2679for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2680 sess,
2681 archive_builder_builder,
2682 native_libraries_from_nonstatics,
2683 tmpdir,
2684false,
2685 ) {
2686 cmd.add_object(&output_path);
2687 }
2688 } else {
2689for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2690 sess,
2691 native_libraries_from_nonstatics,
2692&raw_dylib_dir,
2693 ) {
2694// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2695cmd.link_dylib_by_name(&link_path, true, as_needed);
2696 }
2697 }
26982699// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2700 // command line shorter, reset it to default here before adding more libraries.
2701cmd.reset_per_library_state();
27022703// FIXME: Built-in target specs occasionally use this for linking system libraries,
2704 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2705 // and remove the option.
2706add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
27072708// ------------ Arbitrary order-independent options ------------
27092710 // Add order-independent options determined by rustc from its compiler options,
2711 // target properties and source code.
2712add_order_independent_options(
2713cmd,
2714sess,
2715link_output_kind,
2716self_contained_components,
2717flavor,
2718crate_type,
2719crate_info,
2720out_filename,
2721tmpdir,
2722 );
27232724// Can be used for arbitrary order-independent options.
2725 // In practice may also be occasionally used for linking native libraries.
2726 // Passed after compiler-generated options to support manual overriding when necessary.
2727add_user_defined_link_args(cmd, sess);
27282729// ------------ Builtin configurable linker scripts ------------
2730 // The user's link args should be able to overwrite symbols in the compiler's
2731 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2732 // to work correctly, the user needs to be able to specify linker arguments like
2733 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2734add_link_script(cmd, sess, tmpdir, crate_type);
27352736// ------------ Object code and libraries, order-dependent ------------
27372738 // Post-link CRT objects.
2739add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
27402741// ------------ Late order-dependent options ------------
27422743 // Doesn't really make sense.
2744 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2745 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2746 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2747add_post_link_args(cmd, sess, flavor);
27482749cmd.take_cmd()
2750}
27512752fn add_order_independent_options(
2753 cmd: &mut dyn Linker,
2754 sess: &Session,
2755 link_output_kind: LinkOutputKind,
2756 self_contained_components: LinkSelfContainedComponents,
2757 flavor: LinkerFlavor,
2758 crate_type: CrateType,
2759 crate_info: &CrateInfo,
2760 out_filename: &Path,
2761 tmpdir: &Path,
2762) {
2763// Take care of the flavors and CLI options requesting the `lld` linker.
2764add_lld_args(cmd, sess, flavor, self_contained_components);
27652766add_apple_link_args(cmd, sess, flavor);
27672768let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
27692770if sess.target.os == Os::Fuchsia2771 && crate_type == CrateType::Executable2772 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2773 {
2774let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2775cmd.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"));
2776 }
27772778if sess.target.eh_frame_header {
2779cmd.add_eh_frame_header();
2780 }
27812782// Make the binary compatible with data execution prevention schemes.
2783cmd.add_no_exec();
27842785if self_contained_components.is_crt_objects_enabled() {
2786cmd.no_crt_objects();
2787 }
27882789if sess.target.os == Os::Emscripten {
2790cmd.cc_arg("-fwasm-exceptions");
2791 }
27922793if flavor == LinkerFlavor::Llbc {
2794cmd.link_args(&[
2795"--target",
2796&versioned_llvm_target(sess),
2797"--target-cpu",
2798&crate_info.target_cpu,
2799 ]);
2800if crate_info.target_features.len() > 0 {
2801cmd.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(",")));
2802 }
2803 } else if flavor == LinkerFlavor::Bpf {
2804cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2805if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2806 .into_iter()
2807 .find(|feat| !feat.is_empty())
2808 {
2809cmd.link_args(&["--cpu-features", feat]);
2810 }
2811 }
28122813cmd.linker_plugin_lto();
28142815add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
28162817cmd.output_filename(out_filename);
28182819if crate_type == CrateType::Executable2820 && sess.target.is_like_windows
2821 && let Some(s) = &crate_info.windows_subsystem
2822 {
2823cmd.windows_subsystem(*s);
2824 }
28252826// Try to strip as much out of the generated object by removing unused
2827 // sections if possible. See more comments in linker.rs
2828if !sess.link_dead_code() {
2829// If PGO is enabled sometimes gc_sections will remove the profile data section
2830 // as it appears to be unused. This can then cause the PGO profile file to lose
2831 // some functions. If we are generating a profile we shouldn't strip those metadata
2832 // sections to ensure we have all the data for PGO.
2833let keep_metadata =
2834crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2835cmd.gc_sections(keep_metadata);
2836 }
28372838cmd.set_output_kind(link_output_kind, crate_type, out_filename);
28392840add_relro_args(cmd, sess);
28412842// Pass optimization flags down to the linker.
2843cmd.optimize();
28442845// Gather the set of NatVis files, if any, and write them out to a temp directory.
2846let natvis_visualizers = collect_natvis_visualizers(
2847tmpdir,
2848sess,
2849&crate_info.local_crate_name,
2850&crate_info.natvis_debugger_visualizers,
2851 );
28522853// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2854cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
28552856// We want to prevent the compiler from accidentally leaking in any system libraries,
2857 // so by default we tell linkers not to link to any default libraries.
2858if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2859cmd.no_default_libraries();
2860 }
28612862if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2863cmd.pgo_gen();
2864 }
28652866if sess.opts.unstable_opts.instrument_mcount {
2867cmd.enable_profiling();
2868 }
28692870if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2871cmd.control_flow_guard();
2872 }
28732874// OBJECT-FILES-NO, AUDIT-ORDER
2875if sess.opts.unstable_opts.ehcont_guard {
2876cmd.ehcont_guard();
2877 }
28782879add_rpath_args(cmd, sess, crate_info, out_filename);
2880}
28812882// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2883fn collect_natvis_visualizers(
2884 tmpdir: &Path,
2885 sess: &Session,
2886 crate_name: &Symbol,
2887 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2888) -> Vec<PathBuf> {
2889let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
28902891for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2892let 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));
28932894match fs::write(&visualizer_out_file, &visualizer.src) {
2895Ok(()) => {
2896 visualizer_paths.push(visualizer_out_file);
2897 }
2898Err(error) => {
2899 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2900 path: visualizer_out_file,
2901 error,
2902 });
2903 }
2904 };
2905 }
2906visualizer_paths2907}
29082909fn add_native_libs_from_crate(
2910 cmd: &mut dyn Linker,
2911 sess: &Session,
2912 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2913 crate_info: &CrateInfo,
2914 tmpdir: &Path,
2915 bundled_libs: &FxIndexSet<Symbol>,
2916 cnum: CrateNum,
2917 link_static: bool,
2918 link_dynamic: bool,
2919 link_output_kind: LinkOutputKind,
2920) {
2921if !sess.opts.unstable_opts.link_native_libraries {
2922// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2923 // external build system already has the native dependencies defined, and it
2924 // will provide them to the linker itself.
2925return;
2926 }
29272928if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2929// If rlib contains native libs as archives, unpack them to tmpdir.
2930let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2931archive_builder_builder2932 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2933 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2934 }
29352936let native_libs = match cnum {
2937LOCAL_CRATE => &crate_info.used_libraries,
2938_ => &crate_info.native_libraries[&cnum],
2939 };
29402941let mut last = (None, NativeLibKind::Unspecified, false);
2942for lib in native_libs {
2943if !relevant_lib(sess, lib) {
2944continue;
2945 }
29462947// Skip if this library is the same as the last.
2948last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2949continue;
2950 } else {
2951 (Some(lib.name), lib.kind, lib.verbatim)
2952 };
29532954let name = lib.name.as_str();
2955let verbatim = lib.verbatim;
2956match lib.kind {
2957 NativeLibKind::Static { bundle, whole_archive, .. } => {
2958if link_static {
2959let bundle = bundle.unwrap_or(true);
2960let whole_archive = whole_archive == Some(true);
2961if bundle && cnum != LOCAL_CRATE {
2962if let Some(filename) = lib.filename {
2963// If rlib contains native libs as archives, they are unpacked to tmpdir.
2964let path = tmpdir.join(filename.as_str());
2965 cmd.link_staticlib_by_path(&path, whole_archive);
2966 }
2967 } else {
2968 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2969 }
2970 }
2971 }
2972 NativeLibKind::Dylib { as_needed } => {
2973if link_dynamic {
2974 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2975 }
2976 }
2977 NativeLibKind::Unspecified => {
2978// If we are generating a static binary, prefer static library when the
2979 // link kind is unspecified.
2980if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2981if link_static {
2982 cmd.link_staticlib_by_name(name, verbatim, false);
2983 }
2984 } else if link_dynamic {
2985 cmd.link_dylib_by_name(name, verbatim, true);
2986 }
2987 }
2988 NativeLibKind::Framework { as_needed } => {
2989if link_dynamic {
2990 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2991 }
2992 }
2993 NativeLibKind::RawDylib { as_needed: _ } => {
2994// Handled separately in `linker_with_args`.
2995}
2996 NativeLibKind::WasmImportModule => {}
2997 NativeLibKind::LinkArg => {
2998if link_static {
2999if verbatim {
3000 cmd.verbatim_arg(name);
3001 } else {
3002 cmd.link_arg(name);
3003 }
3004 }
3005 }
3006 }
3007 }
3008}
30093010fn add_local_native_libraries(
3011 cmd: &mut dyn Linker,
3012 sess: &Session,
3013 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3014 crate_info: &CrateInfo,
3015 tmpdir: &Path,
3016 link_output_kind: LinkOutputKind,
3017) {
3018// All static and dynamic native library dependencies are linked to the local crate.
3019let link_static = true;
3020let link_dynamic = true;
3021add_native_libs_from_crate(
3022cmd,
3023sess,
3024archive_builder_builder,
3025crate_info,
3026tmpdir,
3027&Default::default(),
3028LOCAL_CRATE,
3029link_static,
3030link_dynamic,
3031link_output_kind,
3032 );
3033}
30343035fn add_upstream_rust_crates(
3036 cmd: &mut dyn Linker,
3037 sess: &Session,
3038 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3039 crate_info: &CrateInfo,
3040 crate_type: CrateType,
3041 tmpdir: &Path,
3042 link_output_kind: LinkOutputKind,
3043) {
3044// All of the heavy lifting has previously been accomplished by the
3045 // dependency_format module of the compiler. This is just crawling the
3046 // output of that module, adding crates as necessary.
3047 //
3048 // Linking to a rlib involves just passing it to the linker (the linker
3049 // will slurp up the object files inside), and linking to a dynamic library
3050 // involves just passing the right -l flag.
3051let data = crate_info3052 .dependency_formats
3053 .get(&crate_type)
3054 .expect("failed to find crate type in dependency format list");
30553056if sess.target.is_like_aix {
3057// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3058 // the dependency name when outputting a shared library. Thus, `ld` will
3059 // use the full path to shared libraries as the dependency if passed it
3060 // by default unless `noipath` is passed.
3061 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3062cmd.link_or_cc_arg("-bnoipath");
3063 }
30643065for &cnum in &crate_info.used_crates {
3066// We may not pass all crates through to the linker. Some crates may appear statically in
3067 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3068 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3069 // Even if they were already included into a dylib
3070 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3071 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3072 // See the comment in inject_profiler_runtime for why this is the case.
3073let linkage = data[cnum];
3074let link_static_crate = linkage == Linkage::Static
3075 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3076 && (crate_info.compiler_builtins == Some(cnum)
3077 || crate_info.profiler_runtime == Some(cnum));
30783079let mut bundled_libs = Default::default();
3080match linkage {
3081 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3082if link_static_crate {
3083 bundled_libs = crate_info.native_libraries[&cnum]
3084 .iter()
3085 .filter_map(|lib| lib.filename)
3086 .collect();
3087 add_static_crate(
3088 cmd,
3089 sess,
3090 archive_builder_builder,
3091 crate_info,
3092 tmpdir,
3093 cnum,
3094&bundled_libs,
3095 );
3096 }
3097 }
3098 Linkage::Dynamic => {
3099let src = &crate_info.used_crate_source[&cnum];
3100 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3101 }
3102 }
31033104// Static libraries are linked for a subset of linked upstream crates.
3105 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3106 // because the rlib is just an archive.
3107 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3108 // the native library because it is already linked into the dylib, and even if
3109 // inline/const/generic functions from the dylib can refer to symbols from the native
3110 // library, those symbols should be exported and available from the dylib anyway.
3111 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3112let link_static = link_static_crate;
3113// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3114let link_dynamic = false;
3115 add_native_libs_from_crate(
3116 cmd,
3117 sess,
3118 archive_builder_builder,
3119 crate_info,
3120 tmpdir,
3121&bundled_libs,
3122 cnum,
3123 link_static,
3124 link_dynamic,
3125 link_output_kind,
3126 );
3127 }
3128}
31293130fn add_upstream_native_libraries(
3131 cmd: &mut dyn Linker,
3132 sess: &Session,
3133 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3134 crate_info: &CrateInfo,
3135 tmpdir: &Path,
3136 link_output_kind: LinkOutputKind,
3137) {
3138for &cnum in &crate_info.used_crates {
3139// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3140 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3141 // are linked together with their respective upstream crates, and in their originally
3142 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3143 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3144let link_static = false;
3145// Dynamic libraries are linked for all linked upstream crates.
3146 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3147 // because the rlib is just an archive.
3148 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3149 // the native library too because inline/const/generic functions from the dylib can refer
3150 // to symbols from the native library, so the native library providing those symbols should
3151 // be available when linking our final binary.
3152let link_dynamic = true;
3153 add_native_libs_from_crate(
3154 cmd,
3155 sess,
3156 archive_builder_builder,
3157 crate_info,
3158 tmpdir,
3159&Default::default(),
3160 cnum,
3161 link_static,
3162 link_dynamic,
3163 link_output_kind,
3164 );
3165 }
3166}
31673168// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3169// to be relative to the sysroot directory, which may be a relative path specified by the user.
3170//
3171// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3172// linker command line can be non-deterministic due to the paths including the current working
3173// directory. The linker command line needs to be deterministic since it appears inside the PDB
3174// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3175//
3176// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3177fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3178let sysroot_lib_path = &sess.target_tlib_path.dir;
3179let canonical_sysroot_lib_path =
3180 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
31813182let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3183if canonical_lib_dir == canonical_sysroot_lib_path {
3184// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3185sysroot_lib_path.clone()
3186 } else {
3187fix_windows_verbatim_for_gcc(lib_dir)
3188 }
3189}
31903191fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3192if let Some(dir) = path.parent() {
3193let file_name = path.file_name().expect("library path has no file name component");
3194rehome_sysroot_lib_dir(sess, dir).join(file_name)
3195 } else {
3196fix_windows_verbatim_for_gcc(path)
3197 }
3198}
31993200// Adds the static "rlib" versions of all crates to the command line.
3201// There's a bit of magic which happens here specifically related to LTO,
3202// namely that we remove upstream object files.
3203//
3204// When performing LTO, almost(*) all of the bytecode from the upstream
3205// libraries has already been included in our object file output. As a
3206// result we need to remove the object files in the upstream libraries so
3207// the linker doesn't try to include them twice (or whine about duplicate
3208// symbols). We must continue to include the rest of the rlib, however, as
3209// it may contain static native libraries which must be linked in.
3210//
3211// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3212// their bytecode wasn't included. The object files in those libraries must
3213// still be passed to the linker.
3214//
3215// Note, however, that if we're not doing LTO we can just pass the rlib
3216// blindly to the linker (fast) because it's fine if it's not actually
3217// included as we're at the end of the dependency chain.
3218fn add_static_crate(
3219 cmd: &mut dyn Linker,
3220 sess: &Session,
3221 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3222 crate_info: &CrateInfo,
3223 tmpdir: &Path,
3224 cnum: CrateNum,
3225 bundled_lib_file_names: &FxIndexSet<Symbol>,
3226) {
3227let src = &crate_info.used_crate_source[&cnum];
3228let cratepath = src.rlib.as_ref().unwrap();
32293230let mut link_upstream =
3231 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
32323233if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3234 {
3235link_upstream(cratepath);
3236return;
3237 }
32383239let dst = tmpdir.join(cratepath.file_name().unwrap());
3240let name = cratepath.file_name().unwrap().to_str().unwrap();
3241let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3242let bundled_lib_file_names = bundled_lib_file_names.clone();
32433244sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3245let upstream_rust_objects_already_included =
3246are_upstream_rust_objects_already_included(sess);
3247let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
32483249let mut archive = archive_builder_builder.new_archive_builder(sess);
3250if let Err(error) = archive.add_archive(
3251cratepath,
3252 AddArchiveKind::Rlib(&|f, entry_kind| {
3253if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3254return true;
3255 }
32563257// If we're performing LTO and this is a rust-generated object
3258 // file, then we don't need the object file as it's part of the
3259 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3260 // though, so we let that object file slide.
3261if upstream_rust_objects_already_included3262 && entry_kind == ArchiveEntryKind::RustObj3263 && is_builtins3264 {
3265return true;
3266 }
32673268// We skip native libraries because:
3269 // 1. This native libraries won't be used from the generated rlib,
3270 // so we can throw them away to avoid the copying work.
3271 // 2. We can't allow it to be a single remaining entry in archive
3272 // as some linkers may complain on that.
3273if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3274return true;
3275 }
32763277false
3278}),
3279 ) {
3280sess.dcx()
3281 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3282 }
3283if archive.build(&dst, None) {
3284link_upstream(&dst);
3285 }
3286 });
3287}
32883289// Same thing as above, but for dynamic crates instead of static crates.
3290fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3291cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3292}
32933294fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3295match lib.cfg {
3296Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3297None => true,
3298 }
3299}
33003301pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3302match sess.lto() {
3303 config::Lto::Fat => true,
3304 config::Lto::Thin => {
3305// If we defer LTO to the linker, we haven't run LTO ourselves, so
3306 // any upstream object files have not been copied yet.
3307!sess.opts.cg.linker_plugin_lto.enabled()
3308 }
3309 config::Lto::No | config::Lto::ThinLocal => false,
3310 }
3311}
33123313/// We need to communicate five things to the linker on Apple/Darwin targets:
3314/// - The architecture.
3315/// - The operating system (and that it's an Apple platform).
3316/// - The environment.
3317/// - The deployment target.
3318/// - The SDK version.
3319fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3320if !sess.target.is_like_darwin {
3321return;
3322 }
3323let LinkerFlavor::Darwin(cc, _) = flavorelse {
3324return;
3325 };
33263327// `sess.target.arch` (`target_arch`) is not detailed enough.
3328let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3329let target_os = &sess.target.os;
3330let target_env = &sess.target.env;
33313332// The architecture name to forward to the linker.
3333 //
3334 // Supported architecture names can be found in the source:
3335 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3336 //
3337 // Intentionally verbose to ensure that the list always matches correctly
3338 // with the list in the source above.
3339let ld64_arch = match llvm_arch {
3340"armv7k" => "armv7k",
3341"armv7s" => "armv7s",
3342"arm64" => "arm64",
3343"arm64e" => "arm64e",
3344"arm64_32" => "arm64_32",
3345// ld64 doesn't understand i686, so fall back to i386 instead.
3346 //
3347 // Same story when linking with cc, since that ends up invoking ld64.
3348"i386" | "i686" => "i386",
3349"x86_64" => "x86_64",
3350"x86_64h" => "x86_64h",
3351_ => ::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),
3352 };
33533354if cc == Cc::No {
3355// From the man page for ld64 (`man ld`):
3356 // > The linker accepts universal (multiple-architecture) input files,
3357 // > but always creates a "thin" (single-architecture), standard
3358 // > Mach-O output file. The architecture for the output file is
3359 // > specified using the -arch option.
3360 //
3361 // The linker has heuristics to determine the desired architecture,
3362 // but to be safe, and to avoid a warning, we set the architecture
3363 // explicitly.
3364cmd.link_args(&["-arch", ld64_arch]);
33653366// Man page says that ld64 supports the following platform names:
3367 // > - macos
3368 // > - ios
3369 // > - tvos
3370 // > - watchos
3371 // > - bridgeos
3372 // > - visionos
3373 // > - xros
3374 // > - mac-catalyst
3375 // > - ios-simulator
3376 // > - tvos-simulator
3377 // > - watchos-simulator
3378 // > - visionos-simulator
3379 // > - xros-simulator
3380 // > - driverkit
3381let platform_name = match (target_os, target_env) {
3382 (os, Env::Unspecified) => os.desc(),
3383 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3384 (Os::IOs, Env::Sim) => "ios-simulator",
3385 (Os::TvOs, Env::Sim) => "tvos-simulator",
3386 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3387 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3388_ => ::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}"),
3389 };
33903391let min_version = sess.apple_deployment_target().fmt_full().to_string();
33923393// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3394 // - By dyld to give extra warnings and errors, see e.g.:
3395 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3396 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3397 // - By system frameworks to change certain behaviour. For example, the default value of
3398 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3399 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3400 //
3401 // We do not currently know the actual SDK version though, so we have a few options:
3402 // 1. Use the minimum version supported by rustc.
3403 // 2. Use the same as the deployment target.
3404 // 3. Use an arbitrary recent version.
3405 // 4. Omit the version.
3406 //
3407 // The first option is too low / too conservative, and means that users will not get the
3408 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3409 //
3410 // The second option is similarly conservative, and also wrong since if the user specified a
3411 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3412 // make invalid assumptions about the capabilities of the binary.
3413 //
3414 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3415 // version, and is also wrong for similar reasons as above.
3416 //
3417 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3418 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3419 // it as 0.0, which is again too low/conservative.
3420 //
3421 // Currently, we lie about the SDK version, and choose the second option.
3422 //
3423 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3424 // <https://github.com/rust-lang/rust/issues/129432>
3425let sdk_version = &*min_version;
34263427// From the man page for ld64 (`man ld`):
3428 // > This is set to indicate the platform, oldest supported version of
3429 // > that platform that output is to be used on, and the SDK that the
3430 // > output was built against.
3431 //
3432 // Like with `-arch`, the linker can figure out the platform versions
3433 // itself from the binaries being linked, but to be safe, we specify
3434 // the desired versions here explicitly.
3435cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3436 } else {
3437// cc == Cc::Yes
3438 //
3439 // We'd _like_ to use `-target` everywhere, since that can uniquely
3440 // communicate all the required details except for the SDK version
3441 // (which is read by Clang itself from the SDKROOT), but that doesn't
3442 // work on GCC, and since we don't know whether the `cc` compiler is
3443 // Clang, GCC, or something else, we fall back to other options that
3444 // also work on GCC when compiling for macOS.
3445 //
3446 // Targets other than macOS are ill-supported by GCC (it doesn't even
3447 // support e.g. `-miphoneos-version-min`), so in those cases we can
3448 // fairly safely use `-target`. See also the following, where it is
3449 // made explicit that the recommendation by LLVM developers is to use
3450 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3451if *target_os == Os::MacOs {
3452// `-arch` communicates the architecture.
3453 //
3454 // CC forwards the `-arch` to the linker, so we use the same value
3455 // here intentionally.
3456cmd.cc_args(&["-arch", ld64_arch]);
34573458// The presence of `-mmacosx-version-min` makes CC default to
3459 // macOS, and it sets the deployment target.
3460let version = sess.apple_deployment_target().fmt_full();
3461// Intentionally pass this as a single argument, Clang doesn't
3462 // seem to like it otherwise.
3463cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
34643465// macOS has no environment, so with these two, we've told CC the
3466 // four desired parameters.
3467 //
3468 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3469} else {
3470cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3471 }
3472 }
3473}
34743475fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3476if !sess.target.is_like_darwin {
3477return None;
3478 }
3479let LinkerFlavor::Darwin(cc, _) = flavorelse {
3480return None;
3481 };
34823483// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3484 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3485 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3486 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3487 // instead we invoke `xcrun` manually.
3488 //
3489 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3490 // cause the trampoline binary to skip looking up the SDK itself).
3491let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
34923493if cc == Cc::Yes {
3494// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3495 // - The `--sysroot` flag.
3496 // - The `-isysroot` flag.
3497 // - The `SDKROOT` environment variable.
3498 //
3499 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3500 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3501 // only applies to include header files, but on Apple targets it also applies to libraries
3502 // and frameworks.
3503 //
3504 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3505 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3506 // primarily because that is the same interface that is used when invoking the tool under
3507 // `xcrun -sdk macosx $tool`.
3508 //
3509 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3510 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3511 //
3512 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3513 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3514 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3515 //
3516 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3517 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3518 // ignoring the value we set here, and instead use their built-in sysroot).
3519cmd.cmd().env("SDKROOT", &sdkroot);
3520 } else {
3521// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3522 // read by the linker, so it's really the only option.
3523 //
3524 // This is also what Clang does.
3525cmd.link_arg("-syslibroot");
3526cmd.link_arg(&sdkroot);
3527 }
35283529Some(sdkroot)
3530}
35313532fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3533if let Ok(sdkroot) = env::var("SDKROOT") {
3534let p = PathBuf::from(&sdkroot);
35353536// Ignore invalid SDKs, similar to what clang does:
3537 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3538 //
3539 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3540 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3541 // clearly set for the wrong platform.
3542 //
3543 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3544match &*apple::sdk_name(&sess.target).to_lowercase() {
3545"appletvos"
3546if sdkroot.contains("TVSimulator.platform")
3547 || sdkroot.contains("MacOSX.platform") => {}
3548"appletvsimulator"
3549if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3550"iphoneos"
3551if sdkroot.contains("iPhoneSimulator.platform")
3552 || sdkroot.contains("MacOSX.platform") => {}
3553"iphonesimulator"
3554if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3555 }
3556"macosx"
3557if sdkroot.contains("iPhoneOS.platform")
3558 || sdkroot.contains("iPhoneSimulator.platform")
3559 || sdkroot.contains("AppleTVOS.platform")
3560 || sdkroot.contains("AppleTVSimulator.platform")
3561 || sdkroot.contains("WatchOS.platform")
3562 || sdkroot.contains("WatchSimulator.platform")
3563 || sdkroot.contains("XROS.platform")
3564 || sdkroot.contains("XRSimulator.platform") => {}
3565"watchos"
3566if sdkroot.contains("WatchSimulator.platform")
3567 || sdkroot.contains("MacOSX.platform") => {}
3568"watchsimulator"
3569if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3570"xros"
3571if sdkroot.contains("XRSimulator.platform")
3572 || sdkroot.contains("MacOSX.platform") => {}
3573"xrsimulator"
3574if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3575// Ignore `SDKROOT` if it's not a valid path.
3576_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3577_ => return Some(p),
3578 }
3579 }
35803581 apple::get_sdk_root(sess)
3582}
35833584/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3585/// invoke it:
3586/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3587/// - or any `lld` available to `cc`.
3588fn add_lld_args(
3589 cmd: &mut dyn Linker,
3590 sess: &Session,
3591 flavor: LinkerFlavor,
3592 self_contained_components: LinkSelfContainedComponents,
3593) {
3594{
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:3594",
"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(3594u32),
::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!(
3595"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3596 flavor, self_contained_components,
3597 );
35983599// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3600 // we don't need to do anything.
3601if !(flavor.uses_cc() && flavor.uses_lld()) {
3602return;
3603 }
36043605// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3606 // directories to the tool's search path, depending on a mix between what users can specify on
3607 // the CLI, and what the target spec enables (as it can't disable components):
3608 // - if the self-contained linker is enabled on the CLI or by the target spec,
3609 // - and if the self-contained linker is not disabled on the CLI.
3610let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3611let self_contained_target = self_contained_components.is_linker_enabled();
36123613let self_contained_linker = self_contained_cli || self_contained_target;
3614if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3615let mut linker_path_exists = false;
3616for path in sess.get_tools_search_paths(false) {
3617let linker_path = path.join("gcc-ld");
3618 linker_path_exists |= linker_path.exists();
3619 cmd.cc_arg({
3620let mut arg = OsString::from("-B");
3621 arg.push(linker_path);
3622 arg
3623 });
3624 }
3625if !linker_path_exists {
3626// As a sanity check, we emit an error if none of these paths exist: we want
3627 // self-contained linking and have no linker.
3628sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3629 }
3630 }
36313632// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3633 // `lld` as the linker.
3634 //
3635 // Note that wasm targets skip this step since the only option there anyway
3636 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3637 // this, `wasm-component-ld`, which is overridden if this option is passed.
3638if !sess.target.is_like_wasm {
3639cmd.cc_arg("-fuse-ld=lld");
3640 }
36413642if !flavor.is_gnu() {
3643// Tell clang to use a non-default LLD flavor.
3644 // Gcc doesn't understand the target option, but we currently assume
3645 // that gcc is not used for Apple and Wasm targets (#97402).
3646 //
3647 // Note that we don't want to do that by default on macOS: e.g. passing a
3648 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3649 // shown in issue #101653 and the discussion in PR #101792.
3650 //
3651 // It could be required in some cases of cross-compiling with
3652 // LLD, but this is generally unspecified, and we don't know
3653 // which specific versions of clang, macOS SDK, host and target OS
3654 // combinations impact us here.
3655 //
3656 // So we do a simple first-approximation until we know more of what the
3657 // Apple targets require (and which would be handled prior to hitting this
3658 // LLD codepath anyway), but the expectation is that until then
3659 // this should be manually passed if needed. We specify the target when
3660 // targeting a different linker flavor on macOS, and that's also always
3661 // the case when targeting WASM.
3662if sess.target.linker_flavor != sess.host.linker_flavor {
3663cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3664 }
3665 }
3666}
36673668// gold has been deprecated with binutils 2.44
3669// and is known to behave incorrectly around Rust programs.
3670// There have been reports of being unable to bootstrap with gold:
3671// https://github.com/rust-lang/rust/issues/139425
3672// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3673// emitted with `#[used(linker)]`.
3674fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3675use object::read::elf::{FileHeader, SectionHeader};
3676use object::read::{ReadCache, ReadRef, Result};
3677use object::{Endianness, elf};
36783679fn elf_has_gold_version_note<'a>(
3680 elf: &impl FileHeader,
3681 data: impl ReadRef<'a>,
3682 ) -> Result<bool> {
3683let endian = elf.endian()?;
36843685let section =
3686 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3687if let Some((_, section)) = section3688 && let Some(mut notes) = section.notes(endian, data)?
3689{
3690return Ok(notes.any(|note| {
3691note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3692 }));
3693 }
36943695Ok(false)
3696 }
36973698let data = ReadCache::new(BufReader::new(File::open(path)?));
36993700let was_linked_with_gold = if sess.target.pointer_width == 64 {
3701let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3702 elf_has_gold_version_note(elf, &data)?
3703} else if sess.target.pointer_width == 32 {
3704let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3705 elf_has_gold_version_note(elf, &data)?
3706} else {
3707return Ok(());
3708 };
37093710if was_linked_with_gold {
3711let mut warn =
3712sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3713warn.help("consider using LLD or ld from GNU binutils instead");
3714warn.emit();
3715 }
3716Ok(())
3717}