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::{ArchiveBuilder, ArchiveBuilderBuilder};
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 obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
102 check_file_is_writeable(obj, sess);
103 }
104 });
105106if outputs.outputs.should_link() {
107let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
108let tmpdir = TempDirBuilder::new()
109 .prefix("rustc")
110 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
111 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
112let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
113114let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
115let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
116match crate_type {
117 CrateType::Rlib => {
118let _timer = sess.timer("link_rlib");
119{
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:119",
"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(119u32),
::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);
120 link_rlib(
121 sess,
122 archive_builder_builder,
123&compiled_modules,
124&crate_info,
125&metadata,
126 RlibFlavor::Normal,
127&path,
128 )
129 .build(&out_filename);
130 }
131 CrateType::StaticLib => {
132 link_staticlib(
133 sess,
134 archive_builder_builder,
135&compiled_modules,
136&crate_info,
137&metadata,
138&out_filename,
139&path,
140 );
141 }
142_ => {
143 link_natively(
144 sess,
145 archive_builder_builder,
146 crate_type,
147&out_filename,
148&compiled_modules,
149&crate_info,
150&metadata,
151 path.as_ref(),
152 codegen_backend,
153 );
154 }
155 }
156if sess.opts.json_artifact_notifications {
157 sess.dcx().emit_artifact_notification(&out_filename, "link");
158 }
159160if sess.prof.enabled()
161 && let Some(artifact_name) = out_filename.file_name()
162 {
163// Record size for self-profiling
164let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
165166 sess.prof.artifact_size(
167"linked_artifact",
168 artifact_name.to_string_lossy(),
169 file_size,
170 );
171 }
172173if sess.target.binary_format == BinaryFormat::Elf {
174if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
175{
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:175",
"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(175u32),
::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");
176 }
177 }
178179if output.is_stdout() {
180if output.is_tty() {
181 sess.dcx().emit_err(errors::BinaryOutputToTty {
182 shorthand: OutputType::Exe.shorthand(),
183 });
184 } else if let Err(e) = copy_to_stdout(&out_filename) {
185 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
186 }
187 tempfiles_for_stdout_output.push(out_filename);
188 }
189 }
190 }
191192// Remove the temporary object file and metadata if we aren't saving temps.
193sess.time("link_binary_remove_temps", || {
194// If the user requests that temporaries are saved, don't delete any.
195if sess.opts.cg.save_temps {
196return;
197 }
198199let maybe_remove_temps_from_module =
200 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
201if !preserve_objects && let Some(ref obj) = module.object {
202ensure_removed(sess.dcx(), obj);
203 }
204205if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
206ensure_removed(sess.dcx(), dwo_obj);
207 }
208 };
209210let remove_temps_from_module =
211 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
212213// Otherwise, always remove the allocator module temporaries.
214if let Some(ref allocator_module) = compiled_modules.allocator_module {
215remove_temps_from_module(allocator_module);
216 }
217218// Remove the temporary files if output goes to stdout
219for temp in tempfiles_for_stdout_output {
220 ensure_removed(sess.dcx(), &temp);
221 }
222223// If no requested outputs require linking, then the object temporaries should
224 // be kept.
225if !sess.opts.output_types.should_link() {
226return;
227 }
228229// Potentially keep objects for their debuginfo.
230let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
231{
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:231",
"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(231u32),
::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);
232233for module in &compiled_modules.modules {
234 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
235 }
236 });
237}
238239// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
240// crate types must use the same dependency formats.
241pub fn each_linked_rlib(
242 info: &CrateInfo,
243 crate_type: Option<CrateType>,
244 f: &mut dyn FnMut(CrateNum, &Path),
245) -> Result<(), errors::LinkRlibError> {
246let fmts = if let Some(crate_type) = crate_type {
247let Some(fmts) = info.dependency_formats.get(&crate_type) else {
248return Err(errors::LinkRlibError::MissingFormat);
249 };
250251fmts252 } else {
253let mut dep_formats = info.dependency_formats.iter();
254let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
255if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
256return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
257 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
258 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
259 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
260 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
261 });
262 }
263list1264 };
265266let used_dep_crates = info.used_crates.iter();
267for &cnum in used_dep_crates {
268match fmts.get(cnum) {
269Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
270Some(_) => {}
271None => return Err(errors::LinkRlibError::MissingFormat),
272 }
273let crate_name = info.crate_name[&cnum];
274let used_crate_source = &info.used_crate_source[&cnum];
275if let Some(path) = &used_crate_source.rlib {
276 f(cnum, path);
277 } else if used_crate_source.rmeta.is_some() {
278return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
279 } else {
280return Err(errors::LinkRlibError::NotFound { crate_name });
281 }
282 }
283Ok(())
284}
285286/// Create an 'rlib'.
287///
288/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
289/// The rlib primarily contains the object file of the crate, but it also some of the object files
290/// from native libraries.
291fn link_rlib<'a>(
292 sess: &'a Session,
293 archive_builder_builder: &dyn ArchiveBuilderBuilder,
294 compiled_modules: &CompiledModules,
295 crate_info: &CrateInfo,
296 metadata: &EncodedMetadata,
297 flavor: RlibFlavor,
298 tmpdir: &MaybeTempDir,
299) -> Box<dyn ArchiveBuilder + 'a> {
300let mut ab = archive_builder_builder.new_archive_builder(sess);
301302// Pre-compute the list of Rust object filenames and materialize the rmeta-link
303 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
304 // placed immediately after metadata in the archive, so consumers can find
305 // it without iterating every archive member.
306let rust_object_files: Vec<String> = compiled_modules307 .modules
308 .iter()
309 .filter_map(|m| m.object.as_ref())
310 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
311 .collect();
312313let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
314let metadata_link = rmeta_link::RmetaLink { rust_object_files };
315let metadata_link_data = metadata_link.encode();
316let (wrapper, _) =
317create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
318Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
319 } else {
320None321 };
322323let trailing_metadata = match flavor {
324 RlibFlavor::Normal => {
325let (metadata, metadata_position) =
326create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
327let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
328match metadata_position {
329 MetadataPosition::First => {
330// Most of the time metadata in rlib files is wrapped in a "dummy" object
331 // file for the target platform so the rlib can be processed entirely by
332 // normal linkers for the platform. Sometimes this is not possible however.
333 // If it is possible however, placing the metadata object first improves
334 // performance of getting metadata from rlibs.
335ab.add_file(&metadata);
336// Place the rmeta-link member immediately after metadata so consumers
337 // can find it without iterating the whole archive.
338if let Some(file) = &metadata_link_file {
339ab.add_file(file);
340 }
341None342 }
343 MetadataPosition::Last => Some(metadata),
344 }
345 }
346347 RlibFlavor::StaticlibBase => None,
348 };
349350for m in &compiled_modules.modules {
351if let Some(obj) = m.object.as_ref() {
352 ab.add_file(obj);
353 }
354355if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
356 ab.add_file(dwarf_obj);
357 }
358 }
359360match flavor {
361 RlibFlavor::Normal => {}
362 RlibFlavor::StaticlibBase => {
363let obj = compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref());
364if let Some(obj) = obj {
365ab.add_file(obj);
366 }
367 }
368 }
369370// Used if packed_bundled_libs flag enabled.
371let mut packed_bundled_libs = Vec::new();
372373// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
374 // we may not be configured to actually include a static library if we're
375 // adding it here. That's because later when we consume this rlib we'll
376 // decide whether we actually needed the static library or not.
377 //
378 // To do this "correctly" we'd need to keep track of which libraries added
379 // which object files to the archive. We don't do that here, however. The
380 // #[link(cfg(..))] feature is unstable, though, and only intended to get
381 // liblibc working. In that sense the check below just indicates that if
382 // there are any libraries we want to omit object files for at link time we
383 // just exclude all custom object files.
384 //
385 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
386 // feature then we'll need to figure out how to record what objects were
387 // loaded from the libraries found here and then encode that into the
388 // metadata of the rlib we're generating somehow.
389for lib in crate_info.used_libraries.iter() {
390let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
391continue;
392 };
393if flavor == RlibFlavor::Normal
394 && let Some(filename) = lib.filename
395 {
396let path = find_native_static_library(filename.as_str(), true, sess);
397let src = read(path)
398 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
399let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
400let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
401 packed_bundled_libs.push(wrapper_file);
402 } else {
403let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
404 ab.add_archive(&path, None).unwrap_or_else(|error| {
405 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
406 });
407 }
408 }
409410// On Windows, we add the raw-dylib import libraries to the rlibs already.
411 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
412 // Instead, we add all raw-dylibs to the final link on ELF.
413if sess.target.is_like_windows {
414for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
415 sess,
416 archive_builder_builder,
417 crate_info.used_libraries.iter(),
418 tmpdir.as_ref(),
419true,
420 ) {
421 ab.add_archive(&output_path, None).unwrap_or_else(|error| {
422 sess.dcx()
423 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
424 });
425 }
426 }
427428if let Some(trailing_metadata) = trailing_metadata {
429// Note that it is important that we add all of our non-object "magical
430 // files" *after* all of the object files in the archive. The reason for
431 // this is as follows:
432 //
433 // * When performing LTO, this archive will be modified to remove
434 // objects from above. The reason for this is described below.
435 //
436 // * When the system linker looks at an archive, it will attempt to
437 // determine the architecture of the archive in order to see whether its
438 // linkable.
439 //
440 // The algorithm for this detection is: iterate over the files in the
441 // archive. Skip magical SYMDEF names. Interpret the first file as an
442 // object file. Read architecture from the object file.
443 //
444 // * As one can probably see, if "metadata" and "foo.bc" were placed
445 // before all of the objects, then the architecture of this archive would
446 // not be correctly inferred once 'foo.o' is removed.
447 //
448 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
449 // file for the target platform so the rlib can be processed entirely by
450 // normal linkers for the platform. Sometimes this is not possible however.
451 //
452 // Basically, all this means is that this code should not move above the
453 // code above.
454ab.add_file(&trailing_metadata);
455// Place the rmeta-link member immediately after metadata so consumers can
456 // find it without iterating the whole archive.
457if let Some(file) = &metadata_link_file {
458ab.add_file(file);
459 }
460 }
461462// Add all bundled static native library dependencies.
463 // Archives added to the end of .rlib archive, see comment above for the reason.
464for lib in packed_bundled_libs {
465 ab.add_file(&lib)
466 }
467468ab469}
470471/// Create a static archive.
472///
473/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
474/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
475/// dependencies as well.
476///
477/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
478/// library dependencies that they're not linked in.
479///
480/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
481/// object file (and also don't prepare the archive with a metadata file).
482fn link_staticlib(
483 sess: &Session,
484 archive_builder_builder: &dyn ArchiveBuilderBuilder,
485 compiled_modules: &CompiledModules,
486 crate_info: &CrateInfo,
487 metadata: &EncodedMetadata,
488 out_filename: &Path,
489 tempdir: &MaybeTempDir,
490) {
491{
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:491",
"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(491u32),
::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);
492let mut ab = link_rlib(
493sess,
494archive_builder_builder,
495compiled_modules,
496crate_info,
497metadata,
498 RlibFlavor::StaticlibBase,
499tempdir,
500 );
501let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
502503let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
504let lto = are_upstream_rust_objects_already_included(sess)
505 && !ignored_for_lto(sess, crate_info, cnum);
506507let native_libs = crate_info.native_libraries[&cnum].iter();
508let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
509let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
510511let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
512ab.add_archive(
513path,
514Some(Box::new(move |fname: &str, metadata_link| {
515// Ignore metadata and rmeta-link files.
516if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
517return true;
518 }
519520// Don't include Rust objects if LTO is enabled.
521if lto522 && metadata_link.is_some_and(|m| m.rust_object_files.iter().any(|f| f == fname))
523 {
524return true;
525 }
526527// Skip objects for bundled libs.
528if bundled_libs.contains(&Symbol::intern(fname)) {
529return true;
530 }
531532false
533})),
534 )
535 .unwrap();
536537archive_builder_builder538 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
539 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
540541for filename in relevant_libs.iter() {
542let joined = tempdir.as_ref().join(filename.as_str());
543let path = joined.as_path();
544 ab.add_archive(path, None).unwrap();
545 }
546547all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
548 });
549if let Err(e) = res {
550sess.dcx().emit_fatal(e);
551 }
552553ab.build(out_filename);
554555let crates = crate_info.used_crates.iter();
556557let fmts = crate_info558 .dependency_formats
559 .get(&CrateType::StaticLib)
560 .expect("no dependency formats for staticlib");
561562let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
563for &cnum in crates {
564let Some(Linkage::Dynamic) = fmts.get(cnum) else {
565continue;
566 };
567let crate_name = crate_info.crate_name[&cnum];
568let used_crate_source = &crate_info.used_crate_source[&cnum];
569if let Some(path) = &used_crate_source.dylib {
570 all_rust_dylibs.push(&**path);
571 } else if used_crate_source.rmeta.is_some() {
572 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
573 } else {
574 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
575 }
576 }
577578all_native_libs.extend_from_slice(&crate_info.used_libraries);
579580for print in &sess.opts.prints {
581if print.kind == PrintKind::NativeStaticLibs {
582 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
583 }
584 }
585}
586587/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
588/// DWARF package.
589fn link_dwarf_object(
590 sess: &Session,
591 compiled_modules: &CompiledModules,
592 crate_info: &CrateInfo,
593 executable_out_filename: &Path,
594) {
595let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
596dwp_out_filename.push(".dwp");
597{
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:597",
"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(597u32),
::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);
598599#[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)]
600struct ThorinSession<Relocations> {
601 arena_data: TypedArena<Vec<u8>>,
602 arena_mmap: TypedArena<Mmap>,
603 arena_relocations: TypedArena<Relocations>,
604 }
605606impl<Relocations> ThorinSession<Relocations> {
607fn alloc_mmap(&self, data: Mmap) -> &Mmap {
608&*self.arena_mmap.alloc(data)
609 }
610 }
611612impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
613fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
614&*self.arena_data.alloc(data)
615 }
616617fn alloc_relocation(&self, data: Relocations) -> &Relocations {
618&*self.arena_relocations.alloc(data)
619 }
620621fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
622let file = File::open(&path)?;
623let mmap = (unsafe { Mmap::map(file) })?;
624Ok(self.alloc_mmap(mmap))
625 }
626 }
627628match sess.time("run_thorin", || -> Result<(), thorin::Error> {
629let thorin_sess = ThorinSession::default();
630let mut package = thorin::DwarfPackage::new(&thorin_sess);
631632// Input objs contain .o/.dwo files from the current crate.
633match sess.opts.unstable_opts.split_dwarf_kind {
634 SplitDwarfKind::Single => {
635for input_obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
636 package.add_input_object(input_obj)?;
637 }
638 }
639 SplitDwarfKind::Split => {
640for input_obj in
641compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
642 {
643 package.add_input_object(input_obj)?;
644 }
645 }
646 }
647648// Input rlibs contain .o/.dwo files from dependencies.
649let input_rlibs = crate_info650 .used_crate_source
651 .items()
652 .filter_map(|(_, csource)| csource.rlib.as_ref())
653 .into_sorted_stable_ord();
654655for input_rlib in input_rlibs {
656{
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:656",
"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(656u32),
::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);
657 package.add_input_object(input_rlib)?;
658 }
659660// Failing to read the referenced objects is expected for dependencies where the path in the
661 // executable will have been cleaned by Cargo, but the referenced objects will be contained
662 // within rlibs provided as inputs.
663 //
664 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
665 // found, but are provided explicitly above.
666 //
667 // Adding an executable is primarily done to make `thorin` check that all the referenced
668 // dwarf objects are found in the end.
669package.add_executable(
670 executable_out_filename,
671 thorin::MissingReferencedObjectBehaviour::Skip,
672 )?;
673674let output_stream = BufWriter::new(
675 OpenOptions::new()
676 .read(true)
677 .write(true)
678 .create(true)
679 .truncate(true)
680 .open(dwp_out_filename)?,
681 );
682let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
683 package.finish()?.emit(&mut output_stream)?;
684 output_stream.result()?;
685 output_stream.into_inner().flush()?;
686687Ok(())
688 }) {
689Ok(()) => {}
690Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
691 }
692}
693694#[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)]
695#[diag("{$inner}")]
696/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
697/// end up with inconsistent languages within the same diagnostic.
698struct LinkerOutput {
699 inner: String,
700}
701702fn is_msvc_link_exe(sess: &Session) -> bool {
703let (linker_path, flavor) = linker_and_flavor(sess);
704sess.target.is_like_msvc
705 && flavor == LinkerFlavor::Msvc(Lld::No)
706// Match exactly "link.exe"
707&& linker_path.to_str() == Some("link.exe")
708}
709710fn is_macos_ld(sess: &Session) -> bool {
711let (_, flavor) = linker_and_flavor(sess);
712sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))713}
714715fn is_windows_gnu_ld(sess: &Session) -> bool {
716let (_, flavor) = linker_and_flavor(sess);
717sess.target.is_like_windows
718 && !sess.target.is_like_msvc
719 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))720 && sess.target.options.cfg_abi != CfgAbi::Llvm721}
722723fn is_windows_gnu_clang(sess: &Session) -> bool {
724let (_, flavor) = linker_and_flavor(sess);
725sess.target.is_like_windows
726 && !sess.target.is_like_msvc
727 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))728 && sess.target.options.cfg_abi == CfgAbi::Llvm729}
730731fn report_linker_output(
732 sess: &Session,
733 levels: CodegenLintLevelSpecs,
734 stdout: &[u8],
735 stderr: &[u8],
736) {
737let mut escaped_stderr = escape_string(&stderr);
738let mut escaped_stdout = escape_string(&stdout);
739let mut linker_info = String::new();
740741{
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:741",
"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(741u32),
::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);
742{
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:742",
"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(742u32),
::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);
743744fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
745let mut output = String::new();
746if let Ok(str) = str::from_utf8(bytes) {
747{
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:747",
"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(747u32),
::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}");
748output = String::with_capacity(str.len());
749for line in str.lines() {
750 f(line.trim(), &mut output);
751 }
752 }
753escape_string(output.trim().as_bytes())
754 }
755756if is_msvc_link_exe(sess) {
757{
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:757",
"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(757u32),
::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");
758759escaped_stdout = for_each(&stdout, |line, output| {
760// Hide some progress messages from link.exe that we don't care about.
761 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
762 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
763 // missing, link.exe prints the path of the missing .exe followed by:
764let ilk_but_no_exe =
765"not found or not built by the last incremental link; performing full link";
766let trimmed = line.trim_start();
767if trimmed.starts_with("Creating library")
768 || trimmed.starts_with("Generating code")
769 || trimmed.starts_with("Finished generating code")
770 || trimmed.ends_with(ilk_but_no_exe)
771 {
772linker_info += line;
773linker_info += "\r\n";
774 } else {
775*output += line;
776*output += "\r\n"
777}
778 });
779 } else if is_macos_ld(sess) {
780{
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:780",
"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(780u32),
::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");
781782// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
783let deployment_mismatch = |line: &str| {
784// ld64 (object files + dylibs) and ld_prime (object files only):
785(line.starts_with("ld: ")
786 && line.contains("was built for newer")
787 && line.contains("than being linked"))
788// ld_prime (Xcode 15+, dylibs only):
789|| (line.starts_with("ld: ")
790 && line.contains("building for")
791 && line.contains("but linking with")
792 && line.contains("which was built for newer version"))
793 };
794// FIXME: This is a real warning we would like to show, but it hits too many crates
795 // to want to turn it on immediately.
796let search_path = |line: &str| {
797line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
798 };
799escaped_stderr = for_each(&stderr, |line, output| {
800// This duplicate library warning is just not helpful at all.
801if line.starts_with("ld: warning: ignoring duplicate libraries: ")
802 || deployment_mismatch(line)
803 || search_path(line)
804 {
805linker_info += line;
806linker_info += "\n";
807 } else {
808*output += line;
809*output += "\n"
810}
811 });
812 } else if is_windows_gnu_ld(sess) {
813{
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:813",
"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(813u32),
::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");
814815let mut saw_exclude_symbol = false;
816// See https://github.com/rust-lang/rust/issues/112368.
817 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
818let exclude_symbols = |line: &str| {
819line.starts_with("Warning: .drectve `-exclude-symbols:")
820 && line.ends_with("' unrecognized")
821 };
822escaped_stderr = for_each(&stderr, |line, output| {
823if exclude_symbols(line) {
824saw_exclude_symbol = true;
825linker_info += line;
826linker_info += "\n";
827 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
828linker_info += line;
829linker_info += "\n";
830 } else {
831*output += line;
832*output += "\n"
833}
834 });
835 } else if is_windows_gnu_clang(sess) {
836{
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:836",
"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(836u32),
::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)");
837escaped_stderr = for_each(&stderr, |line, output| {
838if line.contains("argument unused during compilation: '-nolibc'") {
839linker_info += line;
840linker_info += "\n";
841 } else {
842*output += line;
843*output += "\n"
844}
845 });
846 };
847848let lint_msg = |msg| {
849emit_lint_base(
850sess,
851LINKER_MESSAGES,
852levels.linker_messages,
853None,
854LinkerOutput { inner: msg },
855 );
856 };
857let lint_info = |msg| {
858emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
859 };
860861if !escaped_stderr.is_empty() {
862// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
863escaped_stderr =
864escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
865// Windows GNU LD prints uppercase Warning
866escaped_stderr = escaped_stderr867 .strip_prefix("Warning: ")
868 .unwrap_or(&escaped_stderr)
869 .replace(": warning: ", ": ");
870lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
871 }
872if !escaped_stdout.is_empty() {
873lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
874 }
875if !linker_info.is_empty() {
876lint_info(linker_info);
877 }
878}
879880/// Create a dynamic library or executable.
881///
882/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
883/// files as well.
884fn link_natively(
885 sess: &Session,
886 archive_builder_builder: &dyn ArchiveBuilderBuilder,
887 crate_type: CrateType,
888 out_filename: &Path,
889 compiled_modules: &CompiledModules,
890 crate_info: &CrateInfo,
891 metadata: &EncodedMetadata,
892 tmpdir: &Path,
893 codegen_backend: &'static str,
894) {
895{
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:895",
"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(895u32),
::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);
896let (linker_path, flavor) = linker_and_flavor(sess);
897let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
898899// On AIX, we ship all libraries as .a big_af archive
900 // the expected format is lib<name>.a(libname.so) for the actual
901 // dynamic library. So we link to a temporary .so file to be archived
902 // at the final out_filename location
903let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
904let archive_member =
905should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
906let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
907908let mut cmd = linker_with_args(
909&linker_path,
910flavor,
911sess,
912archive_builder_builder,
913crate_type,
914tmpdir,
915temp_filename,
916compiled_modules,
917crate_info,
918metadata,
919self_contained_components,
920codegen_backend,
921 );
922923 linker::disable_localization(&mut cmd);
924925for (k, v) in sess.target.link_env.as_ref() {
926 cmd.env(k.as_ref(), v.as_ref());
927 }
928for k in sess.target.link_env_remove.as_ref() {
929 cmd.env_remove(k.as_ref());
930 }
931932for print in &sess.opts.prints {
933if print.kind == PrintKind::LinkArgs {
934let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
935 print.out.overwrite(&content, sess);
936 }
937 }
938939// May have not found libraries in the right formats.
940sess.dcx().abort_if_errors();
941942// Invoke the system linker
943{
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:943",
"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(943u32),
::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:?}");
944let unknown_arg_regex =
945Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
946let mut prog;
947loop {
948prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
949let Ok(ref output) = progelse {
950break;
951 };
952if output.status.success() {
953break;
954 }
955let mut out = output.stderr.clone();
956out.extend(&output.stdout);
957let out = String::from_utf8_lossy(&out);
958959// Check to see if the link failed with an error message that indicates it
960 // doesn't recognize the -no-pie option. If so, re-perform the link step
961 // without it. This is safe because if the linker doesn't support -no-pie
962 // then it should not default to linking executables as pie. Different
963 // versions of gcc seem to use different quotes in the error message so
964 // don't check for them.
965if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))966 && unknown_arg_regex.is_match(&out)
967 && out.contains("-no-pie")
968 && cmd.get_args().iter().any(|e| e == "-no-pie")
969 {
970{
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:970",
"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(970u32),
::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);
971{
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:971",
"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(971u32),
::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.");
972for arg in cmd.take_args() {
973if arg != "-no-pie" {
974 cmd.arg(arg);
975 }
976 }
977{
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:977",
"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(977u32),
::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:?}");
978continue;
979 }
980981// Check if linking failed with an error message that indicates the driver didn't recognize
982 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
983 // to spawn multiple instances on the happy path to do version checking, and ensures things
984 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
985 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
986if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))987 && unknown_arg_regex.is_match(&out)
988 && out.contains("-fuse-ld=lld")
989 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
990 {
991{
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:991",
"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(991u32),
::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);
992{
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:992",
"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(992u32),
::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.");
993for arg in cmd.take_args() {
994if arg.to_string_lossy() != "-fuse-ld=lld" {
995 cmd.arg(arg);
996 }
997 }
998{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:998",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(998u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
999continue;
1000 }
10011002// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1003 // Fallback from '-static-pie' to '-static' in that case.
1004if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1005 && unknown_arg_regex.is_match(&out)
1006 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1007 && cmd.get_args().iter().any(|e| e == "-static-pie")
1008 {
1009{
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:1009",
"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(1009u32),
::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);
1010{
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:1010",
"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(1010u32),
::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!(
1011"Linker does not support -static-pie command line option. Retrying with -static instead."
1012);
1013// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1014let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1015let opts = &sess.target;
1016let pre_objects = if self_contained_crt_objects {
1017&opts.pre_link_objects_self_contained
1018 } else {
1019&opts.pre_link_objects
1020 };
1021let post_objects = if self_contained_crt_objects {
1022&opts.post_link_objects_self_contained
1023 } else {
1024&opts.post_link_objects
1025 };
1026let get_objects = |objects: &CrtObjects, kind| {
1027objects1028 .get(&kind)
1029 .iter()
1030 .copied()
1031 .flatten()
1032 .map(|obj| {
1033get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1034 })
1035 .collect::<Vec<_>>()
1036 };
1037let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1038let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1039let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1040let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1041// Assume that we know insertion positions for the replacement arguments from replaced
1042 // arguments, which is true for all supported targets.
1043if !(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());
1044if !(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());
1045for arg in cmd.take_args() {
1046if arg == "-static-pie" {
1047// Replace the output kind.
1048cmd.arg("-static");
1049 } else if pre_objects_static_pie.contains(&arg) {
1050// Replace the pre-link objects (replace the first and remove the rest).
1051cmd.args(mem::take(&mut pre_objects_static));
1052 } else if post_objects_static_pie.contains(&arg) {
1053// Replace the post-link objects (replace the first and remove the rest).
1054cmd.args(mem::take(&mut post_objects_static));
1055 } else {
1056 cmd.arg(arg);
1057 }
1058 }
1059{
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:1059",
"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(1059u32),
::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:?}");
1060continue;
1061 }
10621063break;
1064 }
10651066match prog {
1067Ok(prog) => {
1068if !prog.status.success() {
1069let mut output = prog.stderr.clone();
1070output.extend_from_slice(&prog.stdout);
1071let escaped_output = escape_linker_output(&output, flavor);
1072let err = errors::LinkingFailed {
1073 linker_path: &linker_path,
1074 exit_status: prog.status,
1075 command: cmd,
1076escaped_output,
1077 verbose: sess.opts.verbose,
1078 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1079 };
1080sess.dcx().emit_err(err);
1081// If MSVC's `link.exe` was expected but the return code
1082 // is not a Microsoft LNK error then suggest a way to fix or
1083 // install the Visual Studio build tools.
1084if let Some(code) = prog.status.code() {
1085// All Microsoft `link.exe` linking ror codes are
1086 // four digit numbers in the range 1000 to 9999 inclusive
1087if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1088let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1089let has_linker =
1090 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1091 .is_some();
10921093sess.dcx().emit_note(errors::LinkExeUnexpectedError);
10941095// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1096 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1097const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1098if code == STATUS_STACK_BUFFER_OVERRUN {
1099sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1100 }
11011102if is_vs_installed && has_linker {
1103// the linker is broken
1104sess.dcx().emit_note(errors::RepairVSBuildTools);
1105sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1106 } else if is_vs_installed {
1107// the linker is not installed
1108sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1109 } else {
1110// visual studio is not installed
1111sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1112 }
1113 }
1114 }
11151116sess.dcx().abort_if_errors();
1117 }
11181119{
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:1119",
"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(1119u32),
::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:?}");
1120report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1121 }
1122Err(e) => {
1123let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11241125let err = if linker_not_found {
1126sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1127 } else {
1128sess.dcx().emit_err(errors::UnableToExeLinker {
1129linker_path,
1130 error: e,
1131 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1132 })
1133 };
11341135if sess.target.is_like_msvc && linker_not_found {
1136sess.dcx().emit_note(errors::MsvcMissingLinker);
1137sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1138sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1139 }
1140err.raise_fatal();
1141 }
1142 }
11431144match sess.split_debuginfo() {
1145// If split debug information is disabled or located in individual files
1146 // there's nothing to do here.
1147SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
11481149// If packed split-debuginfo is requested, but the final compilation
1150 // doesn't actually have any debug information, then we skip this step.
1151SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
11521153// On macOS the external `dsymutil` tool is used to create the packed
1154 // debug information. Note that this will read debug information from
1155 // the objects on the filesystem which we'll clean up later.
1156SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1157let prog = Command::new("dsymutil").arg(out_filename).output();
1158match prog {
1159Ok(prog) => {
1160if !prog.status.success() {
1161let mut output = prog.stderr.clone();
1162output.extend_from_slice(&prog.stdout);
1163sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1164 status: prog.status,
1165 output: escape_string(&output),
1166 });
1167 }
1168 }
1169Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1170 }
1171 }
11721173// On MSVC packed debug information is produced by the linker itself so
1174 // there's no need to do anything else here.
1175SplitDebuginfo::Packedif sess.target.is_like_windows => {}
11761177// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1178 //
1179 // We cannot rely on the .o paths in the executable because they may have been
1180 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1181 // the .o/.dwo paths explicitly.
1182SplitDebuginfo::Packed => {
1183link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1184 }
1185 }
11861187let strip = sess.opts.cg.strip;
11881189if sess.target.is_like_darwin {
1190let stripcmd = "rust-objcopy";
1191match (strip, crate_type) {
1192 (Strip::Debuginfo, _) => {
1193strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1194 }
11951196// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1197(
1198 Strip::Symbols,
1199 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1200 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1201 (Strip::Symbols, _) => {
1202strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1203 }
1204 (Strip::None, _) => {}
1205 }
1206 }
12071208if sess.target.is_like_solaris {
1209// Many illumos systems will have both the native 'strip' utility and
1210 // the GNU one. Use the native version explicitly and do not rely on
1211 // what's in the path.
1212 //
1213 // If cross-compiling and there is not a native version, then use
1214 // `llvm-strip` and hope.
1215let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1216match strip {
1217// Always preserve the symbol table (-x).
1218Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1219// Strip::Symbols is handled via the --strip-all linker option.
1220Strip::Symbols => {}
1221 Strip::None => {}
1222 }
1223 }
12241225if sess.target.is_like_aix {
1226// `llvm-strip` doesn't work for AIX - their strip must be used.
1227if !sess.host.is_like_aix {
1228sess.dcx().emit_warn(errors::AixStripNotUsed);
1229 }
1230let stripcmd = "/usr/bin/strip";
1231match strip {
1232 Strip::Debuginfo => {
1233// FIXME: AIX's strip utility only offers option to strip line number information.
1234strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1235 }
1236 Strip::Symbols => {
1237// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1238strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1239 }
1240 Strip::None => {}
1241 }
1242 }
12431244if should_archive {
1245let mut ab = archive_builder_builder.new_archive_builder(sess);
1246ab.add_file(temp_filename);
1247ab.build(out_filename);
1248 }
1249}
12501251fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1252let mut cmd = Command::new(util);
1253cmd.args(options);
12541255let mut new_path = sess.get_tools_search_paths(false);
1256if let Some(path) = env::var_os("PATH") {
1257new_path.extend(env::split_paths(&path));
1258 }
1259cmd.env("PATH", env::join_paths(new_path).unwrap());
12601261let prog = cmd.arg(out_filename).output();
1262match prog {
1263Ok(prog) => {
1264if !prog.status.success() {
1265let mut output = prog.stderr.clone();
1266output.extend_from_slice(&prog.stdout);
1267sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1268util,
1269 status: prog.status,
1270 output: escape_string(&output),
1271 });
1272 }
1273 }
1274Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1275 }
1276}
12771278fn escape_string(s: &[u8]) -> String {
1279match str::from_utf8(s) {
1280Ok(s) => s.to_owned(),
1281Err(_) => ::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()),
1282 }
1283}
12841285#[cfg(not(windows))]
1286fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1287escape_string(s)
1288}
12891290/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1291/// then try to convert the string from the OEM encoding.
1292#[cfg(windows)]
1293fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1294// This only applies to the actual MSVC linker.
1295if flavour != LinkerFlavor::Msvc(Lld::No) {
1296return escape_string(s);
1297 }
1298match str::from_utf8(s) {
1299Ok(s) => return s.to_owned(),
1300Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1301Some(s) => s,
1302// The string is not UTF-8 and isn't valid for the OEM code page
1303None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1304 },
1305 }
1306}
13071308/// Wrappers around the Windows API.
1309#[cfg(windows)]
1310mod win {
1311use windows::Win32::Globalization::{
1312 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1313 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1314 };
13151316/// Get the Windows system OEM code page. This is most notably the code page
1317 /// used for link.exe's output.
1318pub(super) fn oem_code_page() -> u32 {
1319unsafe {
1320let mut cp: u32 = 0;
1321// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1322 // But the API requires us to pass the data as though it's a [u16] string.
1323let len = size_of::<u32>() / size_of::<u16>();
1324let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1325let len_written = GetLocaleInfoEx(
1326 LOCALE_NAME_SYSTEM_DEFAULT,
1327 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1328Some(data),
1329 );
1330if len_written as usize == len { cp } else { CP_OEMCP }
1331 }
1332 }
1333/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1334 /// The string does not need to be null terminated.
1335 ///
1336 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1337 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1338 ///
1339 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1340 /// any invalid bytes for the expected encoding.
1341pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1342// `MultiByteToWideChar` requires a length to be a "positive integer".
1343if s.len() > isize::MAX as usize {
1344return None;
1345 }
1346// Error if the string is not valid for the expected code page.
1347let flags = MB_ERR_INVALID_CHARS;
1348// Call MultiByteToWideChar twice.
1349 // First to calculate the length then to convert the string.
1350let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1351if len > 0 {
1352let mut utf16 = vec![0; len as usize];
1353 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1354if len > 0 {
1355return utf16.get(..len as usize).map(String::from_utf16_lossy);
1356 }
1357 }
1358None
1359}
1360}
13611362fn add_sanitizer_libraries(
1363 sess: &Session,
1364 flavor: LinkerFlavor,
1365 crate_type: CrateType,
1366 linker: &mut dyn Linker,
1367) {
1368if sess.target.is_like_android {
1369// Sanitizer runtime libraries are provided dynamically on Android
1370 // targets.
1371return;
1372 }
13731374if sess.opts.unstable_opts.external_clangrt {
1375// Linking against in-tree sanitizer runtimes is disabled via
1376 // `-Z external-clangrt`
1377return;
1378 }
13791380if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1381return;
1382 }
13831384// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1385 // which should be linked to both executables and dynamic libraries.
1386 // Everywhere else the runtimes are currently distributed as static
1387 // libraries which should be linked to executables only.
1388if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1389 crate_type,
1390 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1391 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1392 {
1393return;
1394 }
13951396let sanitizer = sess.sanitizers();
1397if sanitizer.contains(SanitizerSet::ADDRESS) {
1398link_sanitizer_runtime(sess, flavor, linker, "asan");
1399 }
1400if sanitizer.contains(SanitizerSet::DATAFLOW) {
1401link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1402 }
1403if sanitizer.contains(SanitizerSet::LEAK)
1404 && !sanitizer.contains(SanitizerSet::ADDRESS)
1405 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1406 {
1407link_sanitizer_runtime(sess, flavor, linker, "lsan");
1408 }
1409if sanitizer.contains(SanitizerSet::MEMORY) {
1410link_sanitizer_runtime(sess, flavor, linker, "msan");
1411 }
1412if sanitizer.contains(SanitizerSet::THREAD) {
1413link_sanitizer_runtime(sess, flavor, linker, "tsan");
1414 }
1415if sanitizer.contains(SanitizerSet::HWADDRESS) {
1416link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1417 }
1418if sanitizer.contains(SanitizerSet::SAFESTACK) {
1419link_sanitizer_runtime(sess, flavor, linker, "safestack");
1420 }
1421if sanitizer.contains(SanitizerSet::REALTIME) {
1422link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1423 }
1424}
14251426fn link_sanitizer_runtime(
1427 sess: &Session,
1428 flavor: LinkerFlavor,
1429 linker: &mut dyn Linker,
1430 name: &str,
1431) {
1432fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1433let path = sess.target_tlib_path.dir.join(filename);
1434if path.exists() {
1435sess.target_tlib_path.dir.clone()
1436 } else {
1437 filesearch::make_target_lib_path(
1438&sess.opts.sysroot.default,
1439sess.opts.target_triple.tuple(),
1440 )
1441 }
1442 }
14431444let channel =
1445::core::option::Option::Some("beta")option_env!("CFG_RELEASE_CHANNEL").map(|channel| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-{0}", channel))
})format!("-{channel}")).unwrap_or_default();
14461447if sess.target.is_like_darwin {
1448// On Apple platforms, the sanitizer is always built as a dylib, and
1449 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1450 // rpath to the library as well (the rpath should be absolute, see
1451 // PR #41352 for details).
1452let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1453let path = find_sanitizer_runtime(sess, &filename);
1454let rpath = path.to_str().expect("non-utf8 component in path");
1455linker.link_args(&["-rpath", rpath]);
1456linker.link_dylib_by_name(&filename, false, true);
1457 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1458// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1459 // compatible ASAN library.
1460linker.link_arg("/INFERASANLIBS");
1461 } else {
1462let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1463let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1464linker.link_staticlib_by_path(&path, true);
1465 }
1466}
14671468/// Returns a boolean indicating whether the specified crate should be ignored
1469/// during LTO.
1470///
1471/// Crates ignored during LTO are not lumped together in the "massive object
1472/// file" that we create and are linked in their normal rlib states. See
1473/// comments below for what crates do not participate in LTO.
1474///
1475/// It's unusual for a crate to not participate in LTO. Typically only
1476/// compiler-specific and unstable crates have a reason to not participate in
1477/// LTO.
1478pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1479// If our target enables builtin function lowering in LLVM then the
1480 // crates providing these functions don't participate in LTO (e.g.
1481 // no_builtins or compiler builtins crates).
1482!sess.target.no_builtins
1483 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1484}
14851486/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1487pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1488fn infer_from(
1489 sess: &Session,
1490 linker: Option<PathBuf>,
1491 flavor: Option<LinkerFlavor>,
1492 features: LinkerFeaturesCli,
1493 ) -> Option<(PathBuf, LinkerFlavor)> {
1494let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1495match (linker, flavor) {
1496 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1497// only the linker flavor is known; use the default linker for the selected flavor
1498(None, Some(flavor)) => Some((
1499PathBuf::from(match flavor {
1500 LinkerFlavor::Gnu(Cc::Yes, _)
1501 | LinkerFlavor::Darwin(Cc::Yes, _)
1502 | LinkerFlavor::WasmLld(Cc::Yes)
1503 | LinkerFlavor::Unix(Cc::Yes) => {
1504if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1505// On historical Solaris systems, "cc" may have
1506 // been Sun Studio, which is not flag-compatible
1507 // with "gcc". This history casts a long shadow,
1508 // and many modern illumos distributions today
1509 // ship GCC as "gcc" without also making it
1510 // available as "cc".
1511"gcc"
1512} else {
1513"cc"
1514}
1515 }
1516 LinkerFlavor::Gnu(_, Lld::Yes)
1517 | LinkerFlavor::Darwin(_, Lld::Yes)
1518 | LinkerFlavor::WasmLld(..)
1519 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1520 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1521"ld"
1522}
1523 LinkerFlavor::Msvc(..) => "link.exe",
1524 LinkerFlavor::EmCc => {
1525if falsecfg!(windows) {
1526"emcc.bat"
1527} else {
1528"emcc"
1529}
1530 }
1531 LinkerFlavor::Bpf => "bpf-linker",
1532 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1533 LinkerFlavor::Ptx => "rust-ptx-linker",
1534 }),
1535flavor,
1536 )),
1537 (Some(linker), None) => {
1538let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1539sess.dcx().emit_fatal(errors::LinkerFileStem);
1540 });
1541let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1542let flavor = adjust_flavor_to_features(flavor, features);
1543Some((linker, flavor))
1544 }
1545 (None, None) => None,
1546 }
1547 }
15481549// While linker flavors and linker features are isomorphic (and thus targets don't need to
1550 // define features separately), we use the flavor as the root piece of data and have the
1551 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1552 // both yet.
1553fn adjust_flavor_to_features(
1554 flavor: LinkerFlavor,
1555 features: LinkerFeaturesCli,
1556 ) -> LinkerFlavor {
1557// Note: a linker feature cannot be both enabled and disabled on the CLI.
1558if features.enabled.contains(LinkerFeatures::LLD) {
1559flavor.with_lld_enabled()
1560 } else if features.disabled.contains(LinkerFeatures::LLD) {
1561flavor.with_lld_disabled()
1562 } else {
1563flavor1564 }
1565 }
15661567let features = sess.opts.cg.linker_features;
15681569// linker and linker flavor specified via command line have precedence over what the target
1570 // specification specifies
1571let linker_flavor = match sess.opts.cg.linker_flavor {
1572// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1573Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1574Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1575// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1576linker_flavor => {
1577linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1578 }
1579 };
1580if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1581return ret;
1582 }
15831584if let Some(ret) = infer_from(
1585sess,
1586sess.target.linker.as_deref().map(PathBuf::from),
1587Some(sess.target.linker_flavor),
1588features,
1589 ) {
1590return ret;
1591 }
15921593::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");
1594}
15951596/// Returns a pair of boolean indicating whether we should preserve the object and
1597/// dwarf object files on the filesystem for their debug information. This is often
1598/// useful with split-dwarf like schemes.
1599fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1600// If the objects don't have debuginfo there's nothing to preserve.
1601if sess.opts.debuginfo == config::DebugInfo::None {
1602return (false, false);
1603 }
16041605match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1606// If there is no split debuginfo then do not preserve objects.
1607(SplitDebuginfo::Off, _) => (false, false),
1608// If there is packed split debuginfo, then the debuginfo in the objects
1609 // has been packaged and the objects can be deleted.
1610(SplitDebuginfo::Packed, _) => (false, false),
1611// If there is unpacked split debuginfo and the current target can not use
1612 // split dwarf, then keep objects.
1613(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1614// If there is unpacked split debuginfo and the target can use split dwarf, then
1615 // keep the object containing that debuginfo (whether that is an object file or
1616 // dwarf object file depends on the split dwarf kind).
1617(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1618 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1619 }
1620}
16211622#[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)]
1623enum RlibFlavor {
1624 Normal,
1625 StaticlibBase,
1626}
16271628fn print_native_static_libs(
1629 sess: &Session,
1630 out: &OutFileName,
1631 all_native_libs: &[NativeLib],
1632 all_rust_dylibs: &[&Path],
1633) {
1634let mut lib_args: Vec<_> = all_native_libs1635 .iter()
1636 .filter(|l| relevant_lib(sess, l))
1637 .filter_map(|lib| {
1638let name = lib.name;
1639match lib.kind {
1640 NativeLibKind::Static { bundle: Some(false), .. }
1641 | NativeLibKind::Dylib { .. }
1642 | NativeLibKind::Unspecified => {
1643let verbatim = lib.verbatim;
1644if sess.target.is_like_msvc {
1645let (prefix, suffix) = sess.staticlib_components(verbatim);
1646Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1647 } else if sess.target.linker_flavor.is_gnu() {
1648Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1649 } else {
1650Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1651 }
1652 }
1653 NativeLibKind::Framework { .. } => {
1654// ld-only syntax, since there are no frameworks in MSVC
1655Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1656 }
1657// These are included, no need to print them
1658NativeLibKind::Static { bundle: None | Some(true), .. }
1659 | NativeLibKind::LinkArg1660 | NativeLibKind::WasmImportModule1661 | NativeLibKind::RawDylib { .. } => None,
1662 }
1663 })
1664// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1665.dedup()
1666 .collect();
1667for path in all_rust_dylibs {
1668// FIXME deduplicate with add_dynamic_crate
16691670 // Just need to tell the linker about where the library lives and
1671 // what its name is
1672let parent = path.parent();
1673if let Some(dir) = parent {
1674let dir = fix_windows_verbatim_for_gcc(dir);
1675if sess.target.is_like_msvc {
1676let mut arg = String::from("/LIBPATH:");
1677 arg.push_str(&dir.display().to_string());
1678 lib_args.push(arg);
1679 } else {
1680 lib_args.push("-L".to_owned());
1681 lib_args.push(dir.display().to_string());
1682 }
1683 }
1684let stem = path.file_stem().unwrap().to_str().unwrap();
1685// Convert library file-stem into a cc -l argument.
1686let lib = if let Some(lib) = stem.strip_prefix("lib")
1687 && !sess.target.is_like_windows
1688 {
1689 lib
1690 } else {
1691 stem
1692 };
1693let path = parent.unwrap_or_else(|| Path::new(""));
1694if sess.target.is_like_msvc {
1695// When producing a dll, the MSVC linker may not actually emit a
1696 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1697 // check to see if the file is there and just omit linking to it if it's
1698 // not present.
1699let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1700if path.join(&name).exists() {
1701 lib_args.push(name);
1702 }
1703 } else {
1704 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1705 }
1706 }
17071708match out {
1709 OutFileName::Real(path) => {
1710out.overwrite(&lib_args.join(" "), sess);
1711sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1712 }
1713 OutFileName::Stdout => {
1714sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1715// Prefix for greppability
1716 // Note: This must not be translated as tools are allowed to depend on this exact string.
1717sess.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(" ")));
1718 }
1719 }
1720}
17211722fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1723let file_path = sess.target_tlib_path.dir.join(name);
1724if file_path.exists() {
1725return file_path;
1726 }
1727// Special directory with objects used only in self-contained linkage mode
1728if self_contained {
1729let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1730if file_path.exists() {
1731return file_path;
1732 }
1733 }
1734for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1735let file_path = search_path.dir.join(name);
1736if file_path.exists() {
1737return file_path;
1738 }
1739 }
1740PathBuf::from(name)
1741}
17421743fn exec_linker(
1744 sess: &Session,
1745 cmd: &Command,
1746 out_filename: &Path,
1747 flavor: LinkerFlavor,
1748 tmpdir: &Path,
1749) -> io::Result<Output> {
1750// When attempting to spawn the linker we run a risk of blowing out the
1751 // size limits for spawning a new process with respect to the arguments
1752 // we pass on the command line.
1753 //
1754 // Here we attempt to handle errors from the OS saying "your list of
1755 // arguments is too big" by reinvoking the linker again with an `@`-file
1756 // that contains all the arguments (aka 'response' files).
1757 // The theory is that this is then accepted on all linkers and the linker
1758 // will read all its options out of there instead of looking at the command line.
1759if !cmd.very_likely_to_exceed_some_spawn_limit() {
1760match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1761Ok(child) => {
1762let output = child.wait_with_output();
1763 flush_linked_file(&output, out_filename)?;
1764return output;
1765 }
1766Err(ref e) if command_line_too_big(e) => {
1767{
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:1767",
"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(1767u32),
::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);
1768 }
1769Err(e) => return Err(e),
1770 }
1771 }
17721773{
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:1773",
"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(1773u32),
::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");
1774let mut cmd2 = cmd.clone();
1775let mut args = String::new();
1776for arg in cmd2.take_args() {
1777 args.push_str(
1778&Escape {
1779 arg: arg.to_str().unwrap(),
1780// Windows-style escaping for @-files is used by
1781 // - all linkers targeting MSVC-like targets, including LLD
1782 // - all LLD flavors running on Windows hosts
1783 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1784is_like_msvc: sess.target.is_like_msvc
1785 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1786 }
1787 .to_string(),
1788 );
1789 args.push('\n');
1790 }
1791let file = tmpdir.join("linker-arguments");
1792let bytes = if sess.target.is_like_msvc {
1793let mut out = Vec::with_capacity((1 + args.len()) * 2);
1794// start the stream with a UTF-16 BOM
1795for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1796// encode in little endian
1797out.push(c as u8);
1798 out.push((c >> 8) as u8);
1799 }
1800out1801 } else {
1802args.into_bytes()
1803 };
1804 fs::write(&file, &bytes)?;
1805cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1806{
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:1806",
"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(1806u32),
::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);
1807let output = cmd2.output();
1808 flush_linked_file(&output, out_filename)?;
1809return output;
18101811#[cfg(not(windows))]
1812fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1813Ok(())
1814 }
18151816#[cfg(windows)]
1817fn flush_linked_file(
1818 command_output: &io::Result<Output>,
1819 out_filename: &Path,
1820 ) -> io::Result<()> {
1821// On Windows, under high I/O load, output buffers are sometimes not flushed,
1822 // even long after process exit, causing nasty, non-reproducible output bugs.
1823 //
1824 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1825 //
1826 // А full writeup of the original Chrome bug can be found at
1827 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18281829if let &Ok(ref out) = command_output {
1830if out.status.success() {
1831if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1832 of.sync_all()?;
1833 }
1834 }
1835 }
18361837Ok(())
1838 }
18391840#[cfg(unix)]
1841fn command_line_too_big(err: &io::Error) -> bool {
1842err.raw_os_error() == Some(::libc::E2BIG)
1843 }
18441845#[cfg(windows)]
1846fn command_line_too_big(err: &io::Error) -> bool {
1847const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1848 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1849 }
18501851#[cfg(not(any(unix, windows)))]
1852fn command_line_too_big(_: &io::Error) -> bool {
1853false
1854}
18551856struct Escape<'a> {
1857 arg: &'a str,
1858 is_like_msvc: bool,
1859 }
18601861impl<'a> fmt::Displayfor Escape<'a> {
1862fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863if self.is_like_msvc {
1864// This is "documented" at
1865 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1866 //
1867 // Unfortunately there's not a great specification of the
1868 // syntax I could find online (at least) but some local
1869 // testing showed that this seemed sufficient-ish to catch
1870 // at least a few edge cases.
1871f.write_fmt(format_args!("\""))write!(f, "\"")?;
1872for c in self.arg.chars() {
1873match c {
1874'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1875 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1876 }
1877 }
1878f.write_fmt(format_args!("\""))write!(f, "\"")?;
1879 } else {
1880// This is documented at https://linux.die.net/man/1/ld, namely:
1881 //
1882 // > Options in file are separated by whitespace. A whitespace
1883 // > character may be included in an option by surrounding the
1884 // > entire option in either single or double quotes. Any
1885 // > character (including a backslash) may be included by
1886 // > prefixing the character to be included with a backslash.
1887 //
1888 // We put an argument on each line, so all we need to do is
1889 // ensure the line is interpreted as one whole argument.
1890for c in self.arg.chars() {
1891match c {
1892'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1893 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1894 }
1895 }
1896 }
1897Ok(())
1898 }
1899 }
1900}
19011902fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1903let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1904 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1905 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1906 LinkOutputKind::DynamicPicExe1907 }
1908 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1909 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1910 LinkOutputKind::StaticPicExe1911 }
1912 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1913 (_, true, _) => LinkOutputKind::StaticDylib,
1914 (_, false, _) => LinkOutputKind::DynamicDylib,
1915 };
19161917// Adjust the output kind to target capabilities.
1918let opts = &sess.target;
1919let pic_exe_supported = opts.position_independent_executables;
1920let static_pic_exe_supported = opts.static_position_independent_executables;
1921let static_dylib_supported = opts.crt_static_allows_dylibs;
1922match kind {
1923 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1924 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1925 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1926_ => kind,
1927 }
1928}
19291930// Returns true if linker is located within sysroot
1931fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1932let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1933linker.with_extension("exe")
1934 } else {
1935linker.to_path_buf()
1936 };
1937for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1938let full_path = dir.join(&linker_with_extension);
1939// If linker comes from sysroot assume self-contained mode
1940if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1941return false;
1942 }
1943 }
1944true
1945}
19461947/// Various toolchain components used during linking are used from rustc distribution
1948/// instead of being found somewhere on the host system.
1949/// We only provide such support for a very limited number of targets.
1950fn self_contained_components(
1951 sess: &Session,
1952 crate_type: CrateType,
1953 linker: &Path,
1954) -> LinkSelfContainedComponents {
1955// Turn the backwards compatible bool values for `self_contained` into fully inferred
1956 // `LinkSelfContainedComponents`.
1957let self_contained =
1958if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1959// Emit an error if the user requested self-contained mode on the CLI but the target
1960 // explicitly refuses it.
1961if sess.target.link_self_contained.is_disabled() {
1962sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1963 }
1964self_contained1965 } else {
1966match sess.target.link_self_contained {
1967 LinkSelfContainedDefault::False => false,
1968 LinkSelfContainedDefault::True => true,
19691970 LinkSelfContainedDefault::WithComponents(components) => {
1971// For target specs with explicitly enabled components, we can return them
1972 // directly.
1973return components;
1974 }
19751976// FIXME: Find a better heuristic for "native musl toolchain is available",
1977 // based on host and linker path, for example.
1978 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1979LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1980 LinkSelfContainedDefault::InferredForMingw => {
1981sess.host == sess.target
1982 && sess.target.cfg_abi != CfgAbi::Uwp1983 && detect_self_contained_mingw(sess, linker)
1984 }
1985 }
1986 };
1987if self_contained {
1988LinkSelfContainedComponents::all()
1989 } else {
1990LinkSelfContainedComponents::empty()
1991 }
1992}
19931994/// Add pre-link object files defined by the target spec.
1995fn add_pre_link_objects(
1996 cmd: &mut dyn Linker,
1997 sess: &Session,
1998 flavor: LinkerFlavor,
1999 link_output_kind: LinkOutputKind,
2000 self_contained: bool,
2001) {
2002// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2003 // so Fuchsia has to be special-cased.
2004let opts = &sess.target;
2005let empty = Default::default();
2006let objects = if self_contained {
2007&opts.pre_link_objects_self_contained
2008 } 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, _))) {
2009&opts.pre_link_objects
2010 } else {
2011&empty2012 };
2013for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2014 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2015 }
2016}
20172018/// Add post-link object files defined by the target spec.
2019fn add_post_link_objects(
2020 cmd: &mut dyn Linker,
2021 sess: &Session,
2022 link_output_kind: LinkOutputKind,
2023 self_contained: bool,
2024) {
2025let objects = if self_contained {
2026&sess.target.post_link_objects_self_contained
2027 } else {
2028&sess.target.post_link_objects
2029 };
2030for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2031 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2032 }
2033}
20342035/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2036/// FIXME: Determine where exactly these args need to be inserted.
2037fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2038if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2039cmd.verbatim_args(args.iter().map(Deref::deref));
2040 }
20412042cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2043}
20442045/// Add a link script embedded in the target, if applicable.
2046fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2047match (crate_type, &sess.target.link_script) {
2048 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2049if !sess.target.linker_flavor.is_gnu() {
2050sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2051 }
20522053let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
20542055let path = tmpdir.join(file_name);
2056if let Err(error) = fs::write(&path, script.as_ref()) {
2057sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2058 }
20592060cmd.link_arg("--script").link_arg(path);
2061 }
2062_ => {}
2063 }
2064}
20652066/// Add arbitrary "user defined" args defined from command line.
2067/// FIXME: Determine where exactly these args need to be inserted.
2068fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2069cmd.verbatim_args(&sess.opts.cg.link_args);
2070}
20712072/// Add arbitrary "late link" args defined by the target spec.
2073/// FIXME: Determine where exactly these args need to be inserted.
2074fn add_late_link_args(
2075 cmd: &mut dyn Linker,
2076 sess: &Session,
2077 flavor: LinkerFlavor,
2078 crate_type: CrateType,
2079 crate_info: &CrateInfo,
2080) {
2081let any_dynamic_crate = crate_type == CrateType::Dylib2082 || crate_type == CrateType::Sdylib2083 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2084*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2085 });
2086if any_dynamic_crate {
2087if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2088cmd.verbatim_args(args.iter().map(Deref::deref));
2089 }
2090 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2091cmd.verbatim_args(args.iter().map(Deref::deref));
2092 }
2093if let Some(args) = sess.target.late_link_args.get(&flavor) {
2094cmd.verbatim_args(args.iter().map(Deref::deref));
2095 }
2096}
20972098/// Add arbitrary "post-link" args defined by the target spec.
2099/// FIXME: Determine where exactly these args need to be inserted.
2100fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2101if let Some(args) = sess.target.post_link_args.get(&flavor) {
2102cmd.verbatim_args(args.iter().map(Deref::deref));
2103 }
2104}
21052106/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2107/// the linker.
2108///
2109/// Background: we implement rlibs as static library (archives). Linkers treat archives
2110/// differently from object files: all object files participate in linking, while archives will
2111/// only participate in linking if they can satisfy at least one undefined reference (version
2112/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2113/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2114/// can't keep them either. This causes #47384.
2115///
2116/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2117/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2118/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2119/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2120/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2121/// from removing them, and this is especially problematic for embedded programming where every
2122/// byte counts.
2123///
2124/// This method creates a synthetic object file, which contains undefined references to all symbols
2125/// that are necessary for the linking. They are only present in symbol table but not actually
2126/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2127/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2128///
2129/// There's a few internal crates in the standard library (aka libcore and
2130/// libstd) which actually have a circular dependence upon one another. This
2131/// currently arises through "weak lang items" where libcore requires things
2132/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2133/// circular dependence to work correctly we declare some of these things
2134/// in this synthetic object.
2135fn add_linked_symbol_object(
2136 cmd: &mut dyn Linker,
2137 sess: &Session,
2138 tmpdir: &Path,
2139 symbols: &[(String, SymbolExportKind)],
2140) {
2141if symbols.is_empty() {
2142return;
2143 }
21442145let Some(mut file) = super::metadata::create_object_file(sess) else {
2146return;
2147 };
21482149if file.format() == object::BinaryFormat::Coff {
2150// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2151 // so add an empty section.
2152file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
21532154// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2155 // default mangler in `object` crate.
2156file.set_mangling(object::write::Mangling::None);
2157 }
21582159if file.format() == object::BinaryFormat::MachO {
2160// Divide up the sections into sub-sections via symbols for dead code stripping.
2161 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2162 // discard on MachO targets.
2163file.set_subsections_via_symbols();
2164 }
21652166// ld64 requires a relocation to load undefined symbols, see below.
2167 // Not strictly needed if linking with lld, but might as well do it there too.
2168let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2169Some(file.add_section(
2170file.segment_name(object::write::StandardSegment::Data).to_vec(),
2171"__data".into(),
2172 object::SectionKind::Data,
2173 ))
2174 } else {
2175None2176 };
21772178for (sym, kind) in symbols.iter() {
2179let symbol = file.add_symbol(object::write::Symbol {
2180 name: sym.clone().into(),
2181 value: 0,
2182 size: 0,
2183 kind: match kind {
2184 SymbolExportKind::Text => object::SymbolKind::Text,
2185 SymbolExportKind::Data => object::SymbolKind::Data,
2186 SymbolExportKind::Tls => object::SymbolKind::Tls,
2187 },
2188 scope: object::SymbolScope::Unknown,
2189 weak: false,
2190 section: object::write::SymbolSection::Undefined,
2191 flags: object::SymbolFlags::None,
2192 });
21932194// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2195 //
2196 // Code-wise, the relevant parts of ld64 are roughly:
2197 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2198 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2199 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2200 //
2201 // 2. Read the archive table of contents (__.SYMDEF file).
2202 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2203 //
2204 // 3. Begin linking by loading "atoms" from input files.
2205 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2206 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2207 //
2208 // a. Directly specified object files (`.o`) are parsed immediately.
2209 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2210 //
2211 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2212 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2213 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2214 //
2215 // - Relocations/fixups are atoms.
2216 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2217 //
2218 // b. Archives are not parsed yet.
2219 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2220 //
2221 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2222 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2223 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2224 //
2225 // All of the steps above are fairly similar to other linkers, except that **it completely
2226 // ignores undefined symbols**.
2227 //
2228 // So to make this trick work on ld64, we need to do something else to load the relevant
2229 // object files. We do this by inserting a relocation (fixup) for each symbol.
2230if let Some(section) = ld64_section_helper {
2231 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2232 .expect("failed adding relocation");
2233 }
2234 }
22352236let path = tmpdir.join("symbols.o");
2237let result = std::fs::write(&path, file.write().unwrap());
2238if let Err(error) = result {
2239sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2240 }
2241cmd.add_object(&path);
2242}
22432244/// Add object files containing code from the current crate.
2245fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2246for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
2247 cmd.add_object(obj);
2248 }
2249}
22502251/// Add object files for allocator code linked once for the whole crate tree.
2252fn add_local_crate_allocator_objects(
2253 cmd: &mut dyn Linker,
2254 compiled_modules: &CompiledModules,
2255 crate_info: &CrateInfo,
2256 crate_type: CrateType,
2257) {
2258if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type) {
2259if let Some(obj) =
2260compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref())
2261 {
2262cmd.add_object(obj);
2263 }
2264 }
2265}
22662267/// Add object files containing metadata for the current crate.
2268fn add_local_crate_metadata_objects(
2269 cmd: &mut dyn Linker,
2270 sess: &Session,
2271 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2272 crate_type: CrateType,
2273 tmpdir: &Path,
2274 crate_info: &CrateInfo,
2275 metadata: &EncodedMetadata,
2276) {
2277// When linking a dynamic library, we put the metadata into a section of the
2278 // executable. This metadata is in a separate object file from the main
2279 // object file, so we create and link it in here.
2280if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2281let data = archive_builder_builder.create_dylib_metadata_wrapper(
2282sess,
2283&metadata,
2284&crate_info.metadata_symbol,
2285 );
2286let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
22872288cmd.add_object(&obj);
2289 }
2290}
22912292/// Add sysroot and other globally set directories to the directory search list.
2293fn add_library_search_dirs(
2294 cmd: &mut dyn Linker,
2295 sess: &Session,
2296 self_contained_components: LinkSelfContainedComponents,
2297 apple_sdk_root: Option<&Path>,
2298) {
2299if !sess.opts.unstable_opts.link_native_libraries {
2300return;
2301 }
23022303let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2304let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2305if is_framework {
2306cmd.framework_path(dir);
2307 } else {
2308cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2309 }
2310 ControlFlow::<()>::Continue(())
2311 });
2312}
23132314/// Add options making relocation sections in the produced ELF files read-only
2315/// and suppressing lazy binding.
2316fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2317match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2318 RelroLevel::Full => cmd.full_relro(),
2319 RelroLevel::Partial => cmd.partial_relro(),
2320 RelroLevel::Off => cmd.no_relro(),
2321 RelroLevel::None => {}
2322 }
2323}
23242325/// Add library search paths used at runtime by dynamic linkers.
2326fn add_rpath_args(
2327 cmd: &mut dyn Linker,
2328 sess: &Session,
2329 crate_info: &CrateInfo,
2330 out_filename: &Path,
2331) {
2332if !sess.target.has_rpath {
2333return;
2334 }
23352336// FIXME (#2397): At some point we want to rpath our guesses as to
2337 // where extern libraries might live, based on the
2338 // add_lib_search_paths
2339if sess.opts.cg.rpath {
2340let libs = crate_info2341 .used_crates
2342 .iter()
2343 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2344 .collect::<Vec<_>>();
2345let rpath_config = RPathConfig {
2346 libs: &*libs,
2347 out_filename: out_filename.to_path_buf(),
2348 is_like_darwin: sess.target.is_like_darwin,
2349 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2350 };
2351cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2352 }
2353}
23542355fn add_c_staticlib_symbols(
2356 sess: &Session,
2357 lib: &NativeLib,
2358 out: &mut Vec<(String, SymbolExportKind)>,
2359) -> io::Result<()> {
2360let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
23612362let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
23632364let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2365 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23662367for member in archive.members() {
2368let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23692370let data = member
2371 .data(&*archive_map)
2372 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23732374// clang LTO: raw LLVM bitcode
2375if data.starts_with(b"BC\xc0\xde") {
2376return Err(io::Error::new(
2377 io::ErrorKind::InvalidData,
2378"LLVM bitcode object in C static library (LTO not supported)",
2379 ));
2380 }
23812382let object = object::File::parse(&*data)
2383 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23842385// gcc / clang ELF / Mach-O LTO
2386if object.sections().any(|s| {
2387 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2388 }) {
2389return Err(io::Error::new(
2390 io::ErrorKind::InvalidData,
2391"LTO object in C static library is not supported",
2392 ));
2393 }
23942395for symbol in object.symbols() {
2396if symbol.scope() != object::SymbolScope::Dynamic {
2397continue;
2398 }
23992400let name = match symbol.name() {
2401Ok(n) => n,
2402Err(_) => continue,
2403 };
24042405let export_kind = match symbol.kind() {
2406 object::SymbolKind::Text => SymbolExportKind::Text,
2407 object::SymbolKind::Data => SymbolExportKind::Data,
2408_ => continue,
2409 };
24102411// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2412 // Need to be resolved.
2413out.push((name.to_string(), export_kind));
2414 }
2415 }
24162417Ok(())
2418}
24192420/// Produce the linker command line containing linker path and arguments.
2421///
2422/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2423/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2424/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2425/// to the linking process as a whole.
2426/// Order-independent options may still override each other in order-dependent fashion,
2427/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2428fn linker_with_args(
2429 path: &Path,
2430 flavor: LinkerFlavor,
2431 sess: &Session,
2432 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2433 crate_type: CrateType,
2434 tmpdir: &Path,
2435 out_filename: &Path,
2436 compiled_modules: &CompiledModules,
2437 crate_info: &CrateInfo,
2438 metadata: &EncodedMetadata,
2439 self_contained_components: LinkSelfContainedComponents,
2440 codegen_backend: &'static str,
2441) -> Command {
2442let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2443let cmd = &mut *super::linker::get_linker(
2444sess,
2445path,
2446flavor,
2447self_contained_components.are_any_components_enabled(),
2448&crate_info.target_cpu,
2449codegen_backend,
2450 );
2451let link_output_kind = link_output_kind(sess, crate_type);
24522453let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
24542455if crate_type == CrateType::Cdylib {
2456let mut seen = FxHashSet::default();
24572458for lib in &crate_info.used_libraries {
2459if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2460 && seen.insert((lib.name, lib.verbatim))
2461 {
2462if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2463 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2464"failed to process C static library `{}`: {}",
2465 lib.name, err
2466 ));
2467 }
2468 }
2469 }
2470 }
24712472// ------------ Early order-dependent options ------------
24732474 // If we're building something like a dynamic library then some platforms
2475 // need to make sure that all symbols are exported correctly from the
2476 // dynamic library.
2477 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2478 // at least on some platforms (e.g. windows-gnu).
2479cmd.export_symbols(tmpdir, crate_type, &export_symbols);
24802481// Can be used for adding custom CRT objects or overriding order-dependent options above.
2482 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2483 // introduce a target spec option for order-independent linker options and migrate built-in
2484 // specs to it.
2485add_pre_link_args(cmd, sess, flavor);
24862487// ------------ Object code and libraries, order-dependent ------------
24882489 // Pre-link CRT objects.
2490add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
24912492add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
24932494// Sanitizer libraries.
2495add_sanitizer_libraries(sess, flavor, crate_type, cmd);
24962497// Object code from the current crate.
2498 // Take careful note of the ordering of the arguments we pass to the linker
2499 // here. Linkers will assume that things on the left depend on things to the
2500 // right. Things on the right cannot depend on things on the left. This is
2501 // all formally implemented in terms of resolving symbols (libs on the right
2502 // resolve unknown symbols of libs on the left, but not vice versa).
2503 //
2504 // For this reason, we have organized the arguments we pass to the linker as
2505 // such:
2506 //
2507 // 1. The local object that LLVM just generated
2508 // 2. Local native libraries
2509 // 3. Upstream rust libraries
2510 // 4. Upstream native libraries
2511 //
2512 // The rationale behind this ordering is that those items lower down in the
2513 // list can't depend on items higher up in the list. For example nothing can
2514 // depend on what we just generated (e.g., that'd be a circular dependency).
2515 // Upstream rust libraries are not supposed to depend on our local native
2516 // libraries as that would violate the structure of the DAG, in that
2517 // scenario they are required to link to them as well in a shared fashion.
2518 //
2519 // Note that upstream rust libraries may contain native dependencies as
2520 // well, but they also can't depend on what we just started to add to the
2521 // link line. And finally upstream native libraries can't depend on anything
2522 // in this DAG so far because they can only depend on other native libraries
2523 // and such dependencies are also required to be specified.
2524add_local_crate_regular_objects(cmd, compiled_modules);
2525add_local_crate_metadata_objects(
2526cmd,
2527sess,
2528archive_builder_builder,
2529crate_type,
2530tmpdir,
2531crate_info,
2532metadata,
2533 );
2534add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
25352536// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2537 // at the point at which they are specified on the command line.
2538 // Must be passed before any (dynamic) libraries to have effect on them.
2539 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2540 // so it will ignore unreferenced ELF sections from relocatable objects.
2541 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2542 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2543 // and move this option back to the top.
2544cmd.add_as_needed();
25452546// Local native libraries of all kinds.
2547add_local_native_libraries(
2548cmd,
2549sess,
2550archive_builder_builder,
2551crate_info,
2552tmpdir,
2553link_output_kind,
2554 );
25552556// Upstream rust crates and their non-dynamic native libraries.
2557add_upstream_rust_crates(
2558cmd,
2559sess,
2560archive_builder_builder,
2561crate_info,
2562crate_type,
2563tmpdir,
2564link_output_kind,
2565 );
25662567// Dynamic native libraries from upstream crates.
2568add_upstream_native_libraries(
2569cmd,
2570sess,
2571archive_builder_builder,
2572crate_info,
2573tmpdir,
2574link_output_kind,
2575 );
25762577// Raw-dylibs from all crates.
2578let raw_dylib_dir = tmpdir.join("raw-dylibs");
2579if sess.target.binary_format == BinaryFormat::Elf {
2580// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2581 // instead we need to pass them via -l. To find the stub, we need to add
2582 // the directory of the stub to the linker search path.
2583 // We make an extra directory for this to avoid polluting the search path.
2584if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2585sess.dcx().emit_fatal(errors::CreateTempDir { error })
2586 }
2587cmd.include_path(&raw_dylib_dir);
2588 }
25892590// Link with the import library generated for any raw-dylib functions.
2591if sess.target.is_like_windows {
2592for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2593 sess,
2594 archive_builder_builder,
2595 crate_info.used_libraries.iter(),
2596 tmpdir,
2597true,
2598 ) {
2599 cmd.add_object(&output_path);
2600 }
2601 } else {
2602for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2603 sess,
2604 crate_info.used_libraries.iter(),
2605&raw_dylib_dir,
2606 ) {
2607// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2608cmd.link_dylib_by_name(&link_path, true, as_needed);
2609 }
2610 }
2611// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2612 // they are used within inlined functions or instantiated generic functions. We do this *after*
2613 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2614 // by the linker.
2615let dependency_linkage = crate_info2616 .dependency_formats
2617 .get(&crate_type)
2618 .expect("failed to find crate type in dependency format list");
26192620// We sort the libraries below
2621#[allow(rustc::potential_query_instability)]
2622let mut native_libraries_from_nonstatics = crate_info2623 .native_libraries
2624 .iter()
2625 .filter_map(|(&cnum, libraries)| {
2626if sess.target.is_like_windows {
2627 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2628 } else {
2629Some(libraries)
2630 }
2631 })
2632 .flatten()
2633 .collect::<Vec<_>>();
2634native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
26352636if sess.target.is_like_windows {
2637for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2638 sess,
2639 archive_builder_builder,
2640 native_libraries_from_nonstatics,
2641 tmpdir,
2642false,
2643 ) {
2644 cmd.add_object(&output_path);
2645 }
2646 } else {
2647for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2648 sess,
2649 native_libraries_from_nonstatics,
2650&raw_dylib_dir,
2651 ) {
2652// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2653cmd.link_dylib_by_name(&link_path, true, as_needed);
2654 }
2655 }
26562657// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2658 // command line shorter, reset it to default here before adding more libraries.
2659cmd.reset_per_library_state();
26602661// FIXME: Built-in target specs occasionally use this for linking system libraries,
2662 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2663 // and remove the option.
2664add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
26652666// ------------ Arbitrary order-independent options ------------
26672668 // Add order-independent options determined by rustc from its compiler options,
2669 // target properties and source code.
2670add_order_independent_options(
2671cmd,
2672sess,
2673link_output_kind,
2674self_contained_components,
2675flavor,
2676crate_type,
2677crate_info,
2678out_filename,
2679tmpdir,
2680 );
26812682// Can be used for arbitrary order-independent options.
2683 // In practice may also be occasionally used for linking native libraries.
2684 // Passed after compiler-generated options to support manual overriding when necessary.
2685add_user_defined_link_args(cmd, sess);
26862687// ------------ Builtin configurable linker scripts ------------
2688 // The user's link args should be able to overwrite symbols in the compiler's
2689 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2690 // to work correctly, the user needs to be able to specify linker arguments like
2691 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2692add_link_script(cmd, sess, tmpdir, crate_type);
26932694// ------------ Object code and libraries, order-dependent ------------
26952696 // Post-link CRT objects.
2697add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
26982699// ------------ Late order-dependent options ------------
27002701 // Doesn't really make sense.
2702 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2703 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2704 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2705add_post_link_args(cmd, sess, flavor);
27062707cmd.take_cmd()
2708}
27092710fn add_order_independent_options(
2711 cmd: &mut dyn Linker,
2712 sess: &Session,
2713 link_output_kind: LinkOutputKind,
2714 self_contained_components: LinkSelfContainedComponents,
2715 flavor: LinkerFlavor,
2716 crate_type: CrateType,
2717 crate_info: &CrateInfo,
2718 out_filename: &Path,
2719 tmpdir: &Path,
2720) {
2721// Take care of the flavors and CLI options requesting the `lld` linker.
2722add_lld_args(cmd, sess, flavor, self_contained_components);
27232724add_apple_link_args(cmd, sess, flavor);
27252726let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
27272728if sess.target.os == Os::Fuchsia2729 && crate_type == CrateType::Executable2730 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2731 {
2732let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2733cmd.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"));
2734 }
27352736if sess.target.eh_frame_header {
2737cmd.add_eh_frame_header();
2738 }
27392740// Make the binary compatible with data execution prevention schemes.
2741cmd.add_no_exec();
27422743if self_contained_components.is_crt_objects_enabled() {
2744cmd.no_crt_objects();
2745 }
27462747if sess.target.os == Os::Emscripten {
2748cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2749"-fwasm-exceptions"
2750} else if sess.panic_strategy().unwinds() {
2751"-sDISABLE_EXCEPTION_CATCHING=0"
2752} else {
2753"-sDISABLE_EXCEPTION_CATCHING=1"
2754});
2755 }
27562757if flavor == LinkerFlavor::Llbc {
2758cmd.link_args(&[
2759"--target",
2760&versioned_llvm_target(sess),
2761"--target-cpu",
2762&crate_info.target_cpu,
2763 ]);
2764if crate_info.target_features.len() > 0 {
2765cmd.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(",")));
2766 }
2767 } else if flavor == LinkerFlavor::Ptx {
2768cmd.link_args(&["--fallback-arch", &crate_info.target_cpu]);
2769 } else if flavor == LinkerFlavor::Bpf {
2770cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2771if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2772 .into_iter()
2773 .find(|feat| !feat.is_empty())
2774 {
2775cmd.link_args(&["--cpu-features", feat]);
2776 }
2777 }
27782779cmd.linker_plugin_lto();
27802781add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
27822783cmd.output_filename(out_filename);
27842785if crate_type == CrateType::Executable2786 && sess.target.is_like_windows
2787 && let Some(s) = &crate_info.windows_subsystem
2788 {
2789cmd.windows_subsystem(*s);
2790 }
27912792// Try to strip as much out of the generated object by removing unused
2793 // sections if possible. See more comments in linker.rs
2794if !sess.link_dead_code() {
2795// If PGO is enabled sometimes gc_sections will remove the profile data section
2796 // as it appears to be unused. This can then cause the PGO profile file to lose
2797 // some functions. If we are generating a profile we shouldn't strip those metadata
2798 // sections to ensure we have all the data for PGO.
2799let keep_metadata =
2800crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2801cmd.gc_sections(keep_metadata);
2802 }
28032804cmd.set_output_kind(link_output_kind, crate_type, out_filename);
28052806add_relro_args(cmd, sess);
28072808// Pass optimization flags down to the linker.
2809cmd.optimize();
28102811// Gather the set of NatVis files, if any, and write them out to a temp directory.
2812let natvis_visualizers = collect_natvis_visualizers(
2813tmpdir,
2814sess,
2815&crate_info.local_crate_name,
2816&crate_info.natvis_debugger_visualizers,
2817 );
28182819// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2820cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
28212822// We want to prevent the compiler from accidentally leaking in any system libraries,
2823 // so by default we tell linkers not to link to any default libraries.
2824if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2825cmd.no_default_libraries();
2826 }
28272828if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2829cmd.pgo_gen();
2830 }
28312832if sess.opts.unstable_opts.instrument_mcount {
2833cmd.enable_profiling();
2834 }
28352836if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2837cmd.control_flow_guard();
2838 }
28392840// OBJECT-FILES-NO, AUDIT-ORDER
2841if sess.opts.unstable_opts.ehcont_guard {
2842cmd.ehcont_guard();
2843 }
28442845add_rpath_args(cmd, sess, crate_info, out_filename);
2846}
28472848// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2849fn collect_natvis_visualizers(
2850 tmpdir: &Path,
2851 sess: &Session,
2852 crate_name: &Symbol,
2853 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2854) -> Vec<PathBuf> {
2855let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
28562857for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2858let 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));
28592860match fs::write(&visualizer_out_file, &visualizer.src) {
2861Ok(()) => {
2862 visualizer_paths.push(visualizer_out_file);
2863 }
2864Err(error) => {
2865 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2866 path: visualizer_out_file,
2867 error,
2868 });
2869 }
2870 };
2871 }
2872visualizer_paths2873}
28742875fn add_native_libs_from_crate(
2876 cmd: &mut dyn Linker,
2877 sess: &Session,
2878 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2879 crate_info: &CrateInfo,
2880 tmpdir: &Path,
2881 bundled_libs: &FxIndexSet<Symbol>,
2882 cnum: CrateNum,
2883 link_static: bool,
2884 link_dynamic: bool,
2885 link_output_kind: LinkOutputKind,
2886) {
2887if !sess.opts.unstable_opts.link_native_libraries {
2888// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2889 // external build system already has the native dependencies defined, and it
2890 // will provide them to the linker itself.
2891return;
2892 }
28932894if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2895// If rlib contains native libs as archives, unpack them to tmpdir.
2896let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2897archive_builder_builder2898 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2899 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2900 }
29012902let native_libs = match cnum {
2903LOCAL_CRATE => &crate_info.used_libraries,
2904_ => &crate_info.native_libraries[&cnum],
2905 };
29062907let mut last = (None, NativeLibKind::Unspecified, false);
2908for lib in native_libs {
2909if !relevant_lib(sess, lib) {
2910continue;
2911 }
29122913// Skip if this library is the same as the last.
2914last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2915continue;
2916 } else {
2917 (Some(lib.name), lib.kind, lib.verbatim)
2918 };
29192920let name = lib.name.as_str();
2921let verbatim = lib.verbatim;
2922match lib.kind {
2923 NativeLibKind::Static { bundle, whole_archive, .. } => {
2924if link_static {
2925let bundle = bundle.unwrap_or(true);
2926let whole_archive = whole_archive == Some(true);
2927if bundle && cnum != LOCAL_CRATE {
2928if let Some(filename) = lib.filename {
2929// If rlib contains native libs as archives, they are unpacked to tmpdir.
2930let path = tmpdir.join(filename.as_str());
2931 cmd.link_staticlib_by_path(&path, whole_archive);
2932 }
2933 } else {
2934 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2935 }
2936 }
2937 }
2938 NativeLibKind::Dylib { as_needed } => {
2939if link_dynamic {
2940 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2941 }
2942 }
2943 NativeLibKind::Unspecified => {
2944// If we are generating a static binary, prefer static library when the
2945 // link kind is unspecified.
2946if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2947if link_static {
2948 cmd.link_staticlib_by_name(name, verbatim, false);
2949 }
2950 } else if link_dynamic {
2951 cmd.link_dylib_by_name(name, verbatim, true);
2952 }
2953 }
2954 NativeLibKind::Framework { as_needed } => {
2955if link_dynamic {
2956 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2957 }
2958 }
2959 NativeLibKind::RawDylib { as_needed: _ } => {
2960// Handled separately in `linker_with_args`.
2961}
2962 NativeLibKind::WasmImportModule => {}
2963 NativeLibKind::LinkArg => {
2964if link_static {
2965if verbatim {
2966 cmd.verbatim_arg(name);
2967 } else {
2968 cmd.link_arg(name);
2969 }
2970 }
2971 }
2972 }
2973 }
2974}
29752976fn add_local_native_libraries(
2977 cmd: &mut dyn Linker,
2978 sess: &Session,
2979 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2980 crate_info: &CrateInfo,
2981 tmpdir: &Path,
2982 link_output_kind: LinkOutputKind,
2983) {
2984// All static and dynamic native library dependencies are linked to the local crate.
2985let link_static = true;
2986let link_dynamic = true;
2987add_native_libs_from_crate(
2988cmd,
2989sess,
2990archive_builder_builder,
2991crate_info,
2992tmpdir,
2993&Default::default(),
2994LOCAL_CRATE,
2995link_static,
2996link_dynamic,
2997link_output_kind,
2998 );
2999}
30003001fn add_upstream_rust_crates(
3002 cmd: &mut dyn Linker,
3003 sess: &Session,
3004 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3005 crate_info: &CrateInfo,
3006 crate_type: CrateType,
3007 tmpdir: &Path,
3008 link_output_kind: LinkOutputKind,
3009) {
3010// All of the heavy lifting has previously been accomplished by the
3011 // dependency_format module of the compiler. This is just crawling the
3012 // output of that module, adding crates as necessary.
3013 //
3014 // Linking to a rlib involves just passing it to the linker (the linker
3015 // will slurp up the object files inside), and linking to a dynamic library
3016 // involves just passing the right -l flag.
3017let data = crate_info3018 .dependency_formats
3019 .get(&crate_type)
3020 .expect("failed to find crate type in dependency format list");
30213022if sess.target.is_like_aix {
3023// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3024 // the dependency name when outputting a shared library. Thus, `ld` will
3025 // use the full path to shared libraries as the dependency if passed it
3026 // by default unless `noipath` is passed.
3027 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3028cmd.link_or_cc_arg("-bnoipath");
3029 }
30303031for &cnum in &crate_info.used_crates {
3032// We may not pass all crates through to the linker. Some crates may appear statically in
3033 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3034 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3035 // Even if they were already included into a dylib
3036 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3037 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3038 // See the comment in inject_profiler_runtime for why this is the case.
3039let linkage = data[cnum];
3040let link_static_crate = linkage == Linkage::Static
3041 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3042 && (crate_info.compiler_builtins == Some(cnum)
3043 || crate_info.profiler_runtime == Some(cnum));
30443045let mut bundled_libs = Default::default();
3046match linkage {
3047 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3048if link_static_crate {
3049 bundled_libs = crate_info.native_libraries[&cnum]
3050 .iter()
3051 .filter_map(|lib| lib.filename)
3052 .collect();
3053 add_static_crate(
3054 cmd,
3055 sess,
3056 archive_builder_builder,
3057 crate_info,
3058 tmpdir,
3059 cnum,
3060&bundled_libs,
3061 );
3062 }
3063 }
3064 Linkage::Dynamic => {
3065let src = &crate_info.used_crate_source[&cnum];
3066 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3067 }
3068 }
30693070// Static libraries are linked for a subset of linked upstream crates.
3071 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3072 // because the rlib is just an archive.
3073 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3074 // the native library because it is already linked into the dylib, and even if
3075 // inline/const/generic functions from the dylib can refer to symbols from the native
3076 // library, those symbols should be exported and available from the dylib anyway.
3077 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3078let link_static = link_static_crate;
3079// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3080let link_dynamic = false;
3081 add_native_libs_from_crate(
3082 cmd,
3083 sess,
3084 archive_builder_builder,
3085 crate_info,
3086 tmpdir,
3087&bundled_libs,
3088 cnum,
3089 link_static,
3090 link_dynamic,
3091 link_output_kind,
3092 );
3093 }
3094}
30953096fn add_upstream_native_libraries(
3097 cmd: &mut dyn Linker,
3098 sess: &Session,
3099 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3100 crate_info: &CrateInfo,
3101 tmpdir: &Path,
3102 link_output_kind: LinkOutputKind,
3103) {
3104for &cnum in &crate_info.used_crates {
3105// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3106 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3107 // are linked together with their respective upstream crates, and in their originally
3108 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3109 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3110let link_static = false;
3111// Dynamic libraries are linked for all linked upstream crates.
3112 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3113 // because the rlib is just an archive.
3114 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3115 // the native library too because inline/const/generic functions from the dylib can refer
3116 // to symbols from the native library, so the native library providing those symbols should
3117 // be available when linking our final binary.
3118let link_dynamic = true;
3119 add_native_libs_from_crate(
3120 cmd,
3121 sess,
3122 archive_builder_builder,
3123 crate_info,
3124 tmpdir,
3125&Default::default(),
3126 cnum,
3127 link_static,
3128 link_dynamic,
3129 link_output_kind,
3130 );
3131 }
3132}
31333134// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3135// to be relative to the sysroot directory, which may be a relative path specified by the user.
3136//
3137// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3138// linker command line can be non-deterministic due to the paths including the current working
3139// directory. The linker command line needs to be deterministic since it appears inside the PDB
3140// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3141//
3142// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3143fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3144let sysroot_lib_path = &sess.target_tlib_path.dir;
3145let canonical_sysroot_lib_path =
3146 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
31473148let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3149if canonical_lib_dir == canonical_sysroot_lib_path {
3150// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3151sysroot_lib_path.clone()
3152 } else {
3153fix_windows_verbatim_for_gcc(lib_dir)
3154 }
3155}
31563157fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3158if let Some(dir) = path.parent() {
3159let file_name = path.file_name().expect("library path has no file name component");
3160rehome_sysroot_lib_dir(sess, dir).join(file_name)
3161 } else {
3162fix_windows_verbatim_for_gcc(path)
3163 }
3164}
31653166// Adds the static "rlib" versions of all crates to the command line.
3167// There's a bit of magic which happens here specifically related to LTO,
3168// namely that we remove upstream object files.
3169//
3170// When performing LTO, almost(*) all of the bytecode from the upstream
3171// libraries has already been included in our object file output. As a
3172// result we need to remove the object files in the upstream libraries so
3173// the linker doesn't try to include them twice (or whine about duplicate
3174// symbols). We must continue to include the rest of the rlib, however, as
3175// it may contain static native libraries which must be linked in.
3176//
3177// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3178// their bytecode wasn't included. The object files in those libraries must
3179// still be passed to the linker.
3180//
3181// Note, however, that if we're not doing LTO we can just pass the rlib
3182// blindly to the linker (fast) because it's fine if it's not actually
3183// included as we're at the end of the dependency chain.
3184fn add_static_crate(
3185 cmd: &mut dyn Linker,
3186 sess: &Session,
3187 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3188 crate_info: &CrateInfo,
3189 tmpdir: &Path,
3190 cnum: CrateNum,
3191 bundled_lib_file_names: &FxIndexSet<Symbol>,
3192) {
3193let src = &crate_info.used_crate_source[&cnum];
3194let cratepath = src.rlib.as_ref().unwrap();
31953196let mut link_upstream =
3197 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
31983199if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3200 {
3201link_upstream(cratepath);
3202return;
3203 }
32043205let dst = tmpdir.join(cratepath.file_name().unwrap());
3206let name = cratepath.file_name().unwrap().to_str().unwrap();
3207let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3208let bundled_lib_file_names = bundled_lib_file_names.clone();
32093210sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3211let upstream_rust_objects_already_included =
3212are_upstream_rust_objects_already_included(sess);
3213let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
32143215let mut archive = archive_builder_builder.new_archive_builder(sess);
3216if let Err(error) = archive.add_archive(
3217cratepath,
3218Some(Box::new(move |f, metadata_link| {
3219if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3220return true;
3221 }
32223223let is_rust_object =
3224metadata_link.is_some_and(|m| m.rust_object_files.iter().any(|rf| rf == f));
32253226// If we're performing LTO and this is a rust-generated object
3227 // file, then we don't need the object file as it's part of the
3228 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3229 // though, so we let that object file slide.
3230if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3231return true;
3232 }
32333234// We skip native libraries because:
3235 // 1. This native libraries won't be used from the generated rlib,
3236 // so we can throw them away to avoid the copying work.
3237 // 2. We can't allow it to be a single remaining entry in archive
3238 // as some linkers may complain on that.
3239if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3240return true;
3241 }
32423243false
3244})),
3245 ) {
3246sess.dcx()
3247 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3248 }
3249if archive.build(&dst) {
3250link_upstream(&dst);
3251 }
3252 });
3253}
32543255// Same thing as above, but for dynamic crates instead of static crates.
3256fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3257cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3258}
32593260fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3261match lib.cfg {
3262Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3263None => true,
3264 }
3265}
32663267pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3268match sess.lto() {
3269 config::Lto::Fat => true,
3270 config::Lto::Thin => {
3271// If we defer LTO to the linker, we haven't run LTO ourselves, so
3272 // any upstream object files have not been copied yet.
3273!sess.opts.cg.linker_plugin_lto.enabled()
3274 }
3275 config::Lto::No | config::Lto::ThinLocal => false,
3276 }
3277}
32783279/// We need to communicate five things to the linker on Apple/Darwin targets:
3280/// - The architecture.
3281/// - The operating system (and that it's an Apple platform).
3282/// - The environment.
3283/// - The deployment target.
3284/// - The SDK version.
3285fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3286if !sess.target.is_like_darwin {
3287return;
3288 }
3289let LinkerFlavor::Darwin(cc, _) = flavorelse {
3290return;
3291 };
32923293// `sess.target.arch` (`target_arch`) is not detailed enough.
3294let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3295let target_os = &sess.target.os;
3296let target_env = &sess.target.env;
32973298// The architecture name to forward to the linker.
3299 //
3300 // Supported architecture names can be found in the source:
3301 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3302 //
3303 // Intentionally verbose to ensure that the list always matches correctly
3304 // with the list in the source above.
3305let ld64_arch = match llvm_arch {
3306"armv7k" => "armv7k",
3307"armv7s" => "armv7s",
3308"arm64" => "arm64",
3309"arm64e" => "arm64e",
3310"arm64_32" => "arm64_32",
3311// ld64 doesn't understand i686, so fall back to i386 instead.
3312 //
3313 // Same story when linking with cc, since that ends up invoking ld64.
3314"i386" | "i686" => "i386",
3315"x86_64" => "x86_64",
3316"x86_64h" => "x86_64h",
3317_ => ::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),
3318 };
33193320if cc == Cc::No {
3321// From the man page for ld64 (`man ld`):
3322 // > The linker accepts universal (multiple-architecture) input files,
3323 // > but always creates a "thin" (single-architecture), standard
3324 // > Mach-O output file. The architecture for the output file is
3325 // > specified using the -arch option.
3326 //
3327 // The linker has heuristics to determine the desired architecture,
3328 // but to be safe, and to avoid a warning, we set the architecture
3329 // explicitly.
3330cmd.link_args(&["-arch", ld64_arch]);
33313332// Man page says that ld64 supports the following platform names:
3333 // > - macos
3334 // > - ios
3335 // > - tvos
3336 // > - watchos
3337 // > - bridgeos
3338 // > - visionos
3339 // > - xros
3340 // > - mac-catalyst
3341 // > - ios-simulator
3342 // > - tvos-simulator
3343 // > - watchos-simulator
3344 // > - visionos-simulator
3345 // > - xros-simulator
3346 // > - driverkit
3347let platform_name = match (target_os, target_env) {
3348 (os, Env::Unspecified) => os.desc(),
3349 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3350 (Os::IOs, Env::Sim) => "ios-simulator",
3351 (Os::TvOs, Env::Sim) => "tvos-simulator",
3352 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3353 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3354_ => ::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}"),
3355 };
33563357let min_version = sess.apple_deployment_target().fmt_full().to_string();
33583359// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3360 // - By dyld to give extra warnings and errors, see e.g.:
3361 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3362 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3363 // - By system frameworks to change certain behaviour. For example, the default value of
3364 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3365 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3366 //
3367 // We do not currently know the actual SDK version though, so we have a few options:
3368 // 1. Use the minimum version supported by rustc.
3369 // 2. Use the same as the deployment target.
3370 // 3. Use an arbitrary recent version.
3371 // 4. Omit the version.
3372 //
3373 // The first option is too low / too conservative, and means that users will not get the
3374 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3375 //
3376 // The second option is similarly conservative, and also wrong since if the user specified a
3377 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3378 // make invalid assumptions about the capabilities of the binary.
3379 //
3380 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3381 // version, and is also wrong for similar reasons as above.
3382 //
3383 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3384 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3385 // it as 0.0, which is again too low/conservative.
3386 //
3387 // Currently, we lie about the SDK version, and choose the second option.
3388 //
3389 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3390 // <https://github.com/rust-lang/rust/issues/129432>
3391let sdk_version = &*min_version;
33923393// From the man page for ld64 (`man ld`):
3394 // > This is set to indicate the platform, oldest supported version of
3395 // > that platform that output is to be used on, and the SDK that the
3396 // > output was built against.
3397 //
3398 // Like with `-arch`, the linker can figure out the platform versions
3399 // itself from the binaries being linked, but to be safe, we specify
3400 // the desired versions here explicitly.
3401cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3402 } else {
3403// cc == Cc::Yes
3404 //
3405 // We'd _like_ to use `-target` everywhere, since that can uniquely
3406 // communicate all the required details except for the SDK version
3407 // (which is read by Clang itself from the SDKROOT), but that doesn't
3408 // work on GCC, and since we don't know whether the `cc` compiler is
3409 // Clang, GCC, or something else, we fall back to other options that
3410 // also work on GCC when compiling for macOS.
3411 //
3412 // Targets other than macOS are ill-supported by GCC (it doesn't even
3413 // support e.g. `-miphoneos-version-min`), so in those cases we can
3414 // fairly safely use `-target`. See also the following, where it is
3415 // made explicit that the recommendation by LLVM developers is to use
3416 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3417if *target_os == Os::MacOs {
3418// `-arch` communicates the architecture.
3419 //
3420 // CC forwards the `-arch` to the linker, so we use the same value
3421 // here intentionally.
3422cmd.cc_args(&["-arch", ld64_arch]);
34233424// The presence of `-mmacosx-version-min` makes CC default to
3425 // macOS, and it sets the deployment target.
3426let version = sess.apple_deployment_target().fmt_full();
3427// Intentionally pass this as a single argument, Clang doesn't
3428 // seem to like it otherwise.
3429cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
34303431// macOS has no environment, so with these two, we've told CC the
3432 // four desired parameters.
3433 //
3434 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3435} else {
3436cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3437 }
3438 }
3439}
34403441fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3442if !sess.target.is_like_darwin {
3443return None;
3444 }
3445let LinkerFlavor::Darwin(cc, _) = flavorelse {
3446return None;
3447 };
34483449// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3450 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3451 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3452 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3453 // instead we invoke `xcrun` manually.
3454 //
3455 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3456 // cause the trampoline binary to skip looking up the SDK itself).
3457let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
34583459if cc == Cc::Yes {
3460// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3461 // - The `--sysroot` flag.
3462 // - The `-isysroot` flag.
3463 // - The `SDKROOT` environment variable.
3464 //
3465 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3466 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3467 // only applies to include header files, but on Apple targets it also applies to libraries
3468 // and frameworks.
3469 //
3470 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3471 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3472 // primarily because that is the same interface that is used when invoking the tool under
3473 // `xcrun -sdk macosx $tool`.
3474 //
3475 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3476 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3477 //
3478 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3479 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3480 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3481 //
3482 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3483 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3484 // ignoring the value we set here, and instead use their built-in sysroot).
3485cmd.cmd().env("SDKROOT", &sdkroot);
3486 } else {
3487// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3488 // read by the linker, so it's really the only option.
3489 //
3490 // This is also what Clang does.
3491cmd.link_arg("-syslibroot");
3492cmd.link_arg(&sdkroot);
3493 }
34943495Some(sdkroot)
3496}
34973498fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3499if let Ok(sdkroot) = env::var("SDKROOT") {
3500let p = PathBuf::from(&sdkroot);
35013502// Ignore invalid SDKs, similar to what clang does:
3503 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3504 //
3505 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3506 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3507 // clearly set for the wrong platform.
3508 //
3509 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3510match &*apple::sdk_name(&sess.target).to_lowercase() {
3511"appletvos"
3512if sdkroot.contains("TVSimulator.platform")
3513 || sdkroot.contains("MacOSX.platform") => {}
3514"appletvsimulator"
3515if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3516"iphoneos"
3517if sdkroot.contains("iPhoneSimulator.platform")
3518 || sdkroot.contains("MacOSX.platform") => {}
3519"iphonesimulator"
3520if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3521 }
3522"macosx"
3523if sdkroot.contains("iPhoneOS.platform")
3524 || sdkroot.contains("iPhoneSimulator.platform")
3525 || sdkroot.contains("AppleTVOS.platform")
3526 || sdkroot.contains("AppleTVSimulator.platform")
3527 || sdkroot.contains("WatchOS.platform")
3528 || sdkroot.contains("WatchSimulator.platform")
3529 || sdkroot.contains("XROS.platform")
3530 || sdkroot.contains("XRSimulator.platform") => {}
3531"watchos"
3532if sdkroot.contains("WatchSimulator.platform")
3533 || sdkroot.contains("MacOSX.platform") => {}
3534"watchsimulator"
3535if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3536"xros"
3537if sdkroot.contains("XRSimulator.platform")
3538 || sdkroot.contains("MacOSX.platform") => {}
3539"xrsimulator"
3540if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3541// Ignore `SDKROOT` if it's not a valid path.
3542_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3543_ => return Some(p),
3544 }
3545 }
35463547 apple::get_sdk_root(sess)
3548}
35493550/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3551/// invoke it:
3552/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3553/// - or any `lld` available to `cc`.
3554fn add_lld_args(
3555 cmd: &mut dyn Linker,
3556 sess: &Session,
3557 flavor: LinkerFlavor,
3558 self_contained_components: LinkSelfContainedComponents,
3559) {
3560{
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:3560",
"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(3560u32),
::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!(
3561"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3562 flavor, self_contained_components,
3563 );
35643565// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3566 // we don't need to do anything.
3567if !(flavor.uses_cc() && flavor.uses_lld()) {
3568return;
3569 }
35703571// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3572 // directories to the tool's search path, depending on a mix between what users can specify on
3573 // the CLI, and what the target spec enables (as it can't disable components):
3574 // - if the self-contained linker is enabled on the CLI or by the target spec,
3575 // - and if the self-contained linker is not disabled on the CLI.
3576let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3577let self_contained_target = self_contained_components.is_linker_enabled();
35783579let self_contained_linker = self_contained_cli || self_contained_target;
3580if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3581let mut linker_path_exists = false;
3582for path in sess.get_tools_search_paths(false) {
3583let linker_path = path.join("gcc-ld");
3584 linker_path_exists |= linker_path.exists();
3585 cmd.cc_arg({
3586let mut arg = OsString::from("-B");
3587 arg.push(linker_path);
3588 arg
3589 });
3590 }
3591if !linker_path_exists {
3592// As a sanity check, we emit an error if none of these paths exist: we want
3593 // self-contained linking and have no linker.
3594sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3595 }
3596 }
35973598// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3599 // `lld` as the linker.
3600 //
3601 // Note that wasm targets skip this step since the only option there anyway
3602 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3603 // this, `wasm-component-ld`, which is overridden if this option is passed.
3604if !sess.target.is_like_wasm {
3605cmd.cc_arg("-fuse-ld=lld");
3606 }
36073608if !flavor.is_gnu() {
3609// Tell clang to use a non-default LLD flavor.
3610 // Gcc doesn't understand the target option, but we currently assume
3611 // that gcc is not used for Apple and Wasm targets (#97402).
3612 //
3613 // Note that we don't want to do that by default on macOS: e.g. passing a
3614 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3615 // shown in issue #101653 and the discussion in PR #101792.
3616 //
3617 // It could be required in some cases of cross-compiling with
3618 // LLD, but this is generally unspecified, and we don't know
3619 // which specific versions of clang, macOS SDK, host and target OS
3620 // combinations impact us here.
3621 //
3622 // So we do a simple first-approximation until we know more of what the
3623 // Apple targets require (and which would be handled prior to hitting this
3624 // LLD codepath anyway), but the expectation is that until then
3625 // this should be manually passed if needed. We specify the target when
3626 // targeting a different linker flavor on macOS, and that's also always
3627 // the case when targeting WASM.
3628if sess.target.linker_flavor != sess.host.linker_flavor {
3629cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3630 }
3631 }
3632}
36333634// gold has been deprecated with binutils 2.44
3635// and is known to behave incorrectly around Rust programs.
3636// There have been reports of being unable to bootstrap with gold:
3637// https://github.com/rust-lang/rust/issues/139425
3638// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3639// emitted with `#[used(linker)]`.
3640fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3641use object::read::elf::{FileHeader, SectionHeader};
3642use object::read::{ReadCache, ReadRef, Result};
3643use object::{Endianness, elf};
36443645fn elf_has_gold_version_note<'a>(
3646 elf: &impl FileHeader,
3647 data: impl ReadRef<'a>,
3648 ) -> Result<bool> {
3649let endian = elf.endian()?;
36503651let section =
3652 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3653if let Some((_, section)) = section3654 && let Some(mut notes) = section.notes(endian, data)?
3655{
3656return Ok(notes.any(|note| {
3657note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3658 }));
3659 }
36603661Ok(false)
3662 }
36633664let data = ReadCache::new(BufReader::new(File::open(path)?));
36653666let was_linked_with_gold = if sess.target.pointer_width == 64 {
3667let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3668 elf_has_gold_version_note(elf, &data)?
3669} else if sess.target.pointer_width == 32 {
3670let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3671 elf_has_gold_version_note(elf, &data)?
3672} else {
3673return Ok(());
3674 };
36753676if was_linked_with_gold {
3677let mut warn =
3678sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3679warn.help("consider using LLD or ld from GNU binutils instead");
3680warn.emit();
3681 }
3682Ok(())
3683}