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, LintDiagnostic};
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_macros::LintDiagnostic;
26use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
27use rustc_metadata::{
28 EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
29 walk_native_lib_search_dirs,
30};
31use rustc_middle::bug;
32use rustc_middle::lint::lint_level;
33use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
34use rustc_middle::middle::dependency_format::Linkage;
35use rustc_middle::middle::exported_symbols::SymbolExportKind;
36use rustc_session::config::{
37self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
38OutputType, PrintKind, SplitDwarfKind, Strip,
39};
40use rustc_session::lint::builtin::LINKER_MESSAGES;
41use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
42use rustc_session::search_paths::PathKind;
43/// For all the linkers we support, and information they might
44/// need out of the shared crate context before we get rid of it.
45use rustc_session::{Session, filesearch};
46use rustc_span::Symbol;
47use rustc_target::spec::crt_objects::CrtObjects;
48use rustc_target::spec::{
49Abi, BinaryFormat, Cc, Env, LinkOutputKind, LinkSelfContainedComponents,
50LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
51RelroLevel, SanitizerSet, SplitDebuginfo,
52};
53use tracing::{debug, info, warn};
5455use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
56use super::command::Command;
57use super::linker::{self, Linker};
58use super::metadata::{MetadataPosition, create_wrapper_file};
59use super::rpath::{self, RPathConfig};
60use super::{apple, versioned_llvm_target};
61use crate::base::needs_allocator_shim_for_linking;
62use crate::{
63CodegenResults, CompiledModule, CrateInfo, NativeLib, errors, looks_like_rust_object_file,
64};
6566pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
67if let Err(e) = fs::remove_file(path) {
68if e.kind() != io::ErrorKind::NotFound {
69dcx.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));
70 }
71 }
72}
7374/// Performs the linkage portion of the compilation phase. This will generate all
75/// of the requested outputs for this compilation session.
76pub fn link_binary(
77 sess: &Session,
78 archive_builder_builder: &dyn ArchiveBuilderBuilder,
79 codegen_results: CodegenResults,
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 &codegen_results.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 codegen_results.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(
108 sess,
109 crate_type,
110 outputs,
111 codegen_results.crate_info.local_crate_name,
112 );
113let tmpdir = TempDirBuilder::new()
114 .prefix("rustc")
115 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
116 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
117let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
118119let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
codegen_results.crate_info.local_crate_name))
})format!("{}", codegen_results.crate_info.local_crate_name);
120let out_filename = output.file_for_writing(
121 outputs,
122 OutputType::Exe,
123&crate_name,
124 sess.invocation_temp.as_deref(),
125 );
126match crate_type {
127 CrateType::Rlib => {
128let _timer = sess.timer("link_rlib");
129{
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:129",
"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(129u32),
::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);
130 link_rlib(
131 sess,
132 archive_builder_builder,
133&codegen_results,
134&metadata,
135 RlibFlavor::Normal,
136&path,
137 )
138 .build(&out_filename);
139 }
140 CrateType::StaticLib => {
141 link_staticlib(
142 sess,
143 archive_builder_builder,
144&codegen_results,
145&metadata,
146&out_filename,
147&path,
148 );
149 }
150_ => {
151 link_natively(
152 sess,
153 archive_builder_builder,
154 crate_type,
155&out_filename,
156&codegen_results,
157&metadata,
158 path.as_ref(),
159 codegen_backend,
160 );
161 }
162 }
163if sess.opts.json_artifact_notifications {
164 sess.dcx().emit_artifact_notification(&out_filename, "link");
165 }
166167if sess.prof.enabled()
168 && let Some(artifact_name) = out_filename.file_name()
169 {
170// Record size for self-profiling
171let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
172173 sess.prof.artifact_size(
174"linked_artifact",
175 artifact_name.to_string_lossy(),
176 file_size,
177 );
178 }
179180if sess.target.binary_format == BinaryFormat::Elf {
181if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
182{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:182",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(182u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message", "err"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Error while checking if gold was the linker")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&err) as
&dyn Value))])
});
} else { ; }
};info!(?err, "Error while checking if gold was the linker");
183 }
184 }
185186if output.is_stdout() {
187if output.is_tty() {
188 sess.dcx().emit_err(errors::BinaryOutputToTty {
189 shorthand: OutputType::Exe.shorthand(),
190 });
191 } else if let Err(e) = copy_to_stdout(&out_filename) {
192 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
193 }
194 tempfiles_for_stdout_output.push(out_filename);
195 }
196 }
197 }
198199// Remove the temporary object file and metadata if we aren't saving temps.
200sess.time("link_binary_remove_temps", || {
201// If the user requests that temporaries are saved, don't delete any.
202if sess.opts.cg.save_temps {
203return;
204 }
205206let maybe_remove_temps_from_module =
207 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
208if !preserve_objects && let Some(ref obj) = module.object {
209ensure_removed(sess.dcx(), obj);
210 }
211212if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
213ensure_removed(sess.dcx(), dwo_obj);
214 }
215 };
216217let remove_temps_from_module =
218 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
219220// Otherwise, always remove the allocator module temporaries.
221if let Some(ref allocator_module) = codegen_results.allocator_module {
222remove_temps_from_module(allocator_module);
223 }
224225// Remove the temporary files if output goes to stdout
226for temp in tempfiles_for_stdout_output {
227 ensure_removed(sess.dcx(), &temp);
228 }
229230// If no requested outputs require linking, then the object temporaries should
231 // be kept.
232if !sess.opts.output_types.should_link() {
233return;
234 }
235236// Potentially keep objects for their debuginfo.
237let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
238{
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:238",
"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(238u32),
::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);
239240for module in &codegen_results.modules {
241 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
242 }
243 });
244}
245246// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
247// crate types must use the same dependency formats.
248pub fn each_linked_rlib(
249 info: &CrateInfo,
250 crate_type: Option<CrateType>,
251 f: &mut dyn FnMut(CrateNum, &Path),
252) -> Result<(), errors::LinkRlibError> {
253let fmts = if let Some(crate_type) = crate_type {
254let Some(fmts) = info.dependency_formats.get(&crate_type) else {
255return Err(errors::LinkRlibError::MissingFormat);
256 };
257258fmts259 } else {
260let mut dep_formats = info.dependency_formats.iter();
261let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
262if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
263return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
264 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
265 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
266 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
267 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
268 });
269 }
270list1271 };
272273let used_dep_crates = info.used_crates.iter();
274for &cnum in used_dep_crates {
275match fmts.get(cnum) {
276Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
277Some(_) => {}
278None => return Err(errors::LinkRlibError::MissingFormat),
279 }
280let crate_name = info.crate_name[&cnum];
281let used_crate_source = &info.used_crate_source[&cnum];
282if let Some(path) = &used_crate_source.rlib {
283 f(cnum, path);
284 } else if used_crate_source.rmeta.is_some() {
285return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
286 } else {
287return Err(errors::LinkRlibError::NotFound { crate_name });
288 }
289 }
290Ok(())
291}
292293/// Create an 'rlib'.
294///
295/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
296/// The rlib primarily contains the object file of the crate, but it also some of the object files
297/// from native libraries.
298fn link_rlib<'a>(
299 sess: &'a Session,
300 archive_builder_builder: &dyn ArchiveBuilderBuilder,
301 codegen_results: &CodegenResults,
302 metadata: &EncodedMetadata,
303 flavor: RlibFlavor,
304 tmpdir: &MaybeTempDir,
305) -> Box<dyn ArchiveBuilder + 'a> {
306let mut ab = archive_builder_builder.new_archive_builder(sess);
307308let trailing_metadata = match flavor {
309 RlibFlavor::Normal => {
310let (metadata, metadata_position) =
311create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
312let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
313match metadata_position {
314 MetadataPosition::First => {
315// Most of the time metadata in rlib files is wrapped in a "dummy" object
316 // file for the target platform so the rlib can be processed entirely by
317 // normal linkers for the platform. Sometimes this is not possible however.
318 // If it is possible however, placing the metadata object first improves
319 // performance of getting metadata from rlibs.
320ab.add_file(&metadata);
321None322 }
323 MetadataPosition::Last => Some(metadata),
324 }
325 }
326327 RlibFlavor::StaticlibBase => None,
328 };
329330for m in &codegen_results.modules {
331if let Some(obj) = m.object.as_ref() {
332 ab.add_file(obj);
333 }
334335if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
336 ab.add_file(dwarf_obj);
337 }
338 }
339340match flavor {
341 RlibFlavor::Normal => {}
342 RlibFlavor::StaticlibBase => {
343let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
344if let Some(obj) = obj {
345ab.add_file(obj);
346 }
347 }
348 }
349350// Used if packed_bundled_libs flag enabled.
351let mut packed_bundled_libs = Vec::new();
352353// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
354 // we may not be configured to actually include a static library if we're
355 // adding it here. That's because later when we consume this rlib we'll
356 // decide whether we actually needed the static library or not.
357 //
358 // To do this "correctly" we'd need to keep track of which libraries added
359 // which object files to the archive. We don't do that here, however. The
360 // #[link(cfg(..))] feature is unstable, though, and only intended to get
361 // liblibc working. In that sense the check below just indicates that if
362 // there are any libraries we want to omit object files for at link time we
363 // just exclude all custom object files.
364 //
365 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
366 // feature then we'll need to figure out how to record what objects were
367 // loaded from the libraries found here and then encode that into the
368 // metadata of the rlib we're generating somehow.
369for lib in codegen_results.crate_info.used_libraries.iter() {
370let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
371continue;
372 };
373if flavor == RlibFlavor::Normal
374 && let Some(filename) = lib.filename
375 {
376let path = find_native_static_library(filename.as_str(), true, sess);
377let src = read(path)
378 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
379let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
380let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
381 packed_bundled_libs.push(wrapper_file);
382 } else {
383let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
384 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
385 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
386 });
387 }
388 }
389390// On Windows, we add the raw-dylib import libraries to the rlibs already.
391 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
392 // Instead, we add all raw-dylibs to the final link on ELF.
393if sess.target.is_like_windows {
394for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
395 sess,
396 archive_builder_builder,
397 codegen_results.crate_info.used_libraries.iter(),
398 tmpdir.as_ref(),
399true,
400 ) {
401 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
402 sess.dcx()
403 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
404 });
405 }
406 }
407408if let Some(trailing_metadata) = trailing_metadata {
409// Note that it is important that we add all of our non-object "magical
410 // files" *after* all of the object files in the archive. The reason for
411 // this is as follows:
412 //
413 // * When performing LTO, this archive will be modified to remove
414 // objects from above. The reason for this is described below.
415 //
416 // * When the system linker looks at an archive, it will attempt to
417 // determine the architecture of the archive in order to see whether its
418 // linkable.
419 //
420 // The algorithm for this detection is: iterate over the files in the
421 // archive. Skip magical SYMDEF names. Interpret the first file as an
422 // object file. Read architecture from the object file.
423 //
424 // * As one can probably see, if "metadata" and "foo.bc" were placed
425 // before all of the objects, then the architecture of this archive would
426 // not be correctly inferred once 'foo.o' is removed.
427 //
428 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
429 // file for the target platform so the rlib can be processed entirely by
430 // normal linkers for the platform. Sometimes this is not possible however.
431 //
432 // Basically, all this means is that this code should not move above the
433 // code above.
434ab.add_file(&trailing_metadata);
435 }
436437// Add all bundled static native library dependencies.
438 // Archives added to the end of .rlib archive, see comment above for the reason.
439for lib in packed_bundled_libs {
440 ab.add_file(&lib)
441 }
442443ab444}
445446/// Create a static archive.
447///
448/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
449/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
450/// dependencies as well.
451///
452/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
453/// library dependencies that they're not linked in.
454///
455/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
456/// object file (and also don't prepare the archive with a metadata file).
457fn link_staticlib(
458 sess: &Session,
459 archive_builder_builder: &dyn ArchiveBuilderBuilder,
460 codegen_results: &CodegenResults,
461 metadata: &EncodedMetadata,
462 out_filename: &Path,
463 tempdir: &MaybeTempDir,
464) {
465{
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:465",
"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(465u32),
::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);
466let mut ab = link_rlib(
467sess,
468archive_builder_builder,
469codegen_results,
470metadata,
471 RlibFlavor::StaticlibBase,
472tempdir,
473 );
474let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
475476let res = each_linked_rlib(
477&codegen_results.crate_info,
478Some(CrateType::StaticLib),
479&mut |cnum, path| {
480let lto = are_upstream_rust_objects_already_included(sess)
481 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
482483let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
484let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
485let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
486487let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
488ab.add_archive(
489path,
490Box::new(move |fname: &str| {
491// Ignore metadata files, no matter the name.
492if fname == METADATA_FILENAME {
493return true;
494 }
495496// Don't include Rust objects if LTO is enabled
497if lto && looks_like_rust_object_file(fname) {
498return true;
499 }
500501// Skip objects for bundled libs.
502if bundled_libs.contains(&Symbol::intern(fname)) {
503return true;
504 }
505506false
507}),
508 )
509 .unwrap();
510511archive_builder_builder512 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
513 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
514515for filename in relevant_libs.iter() {
516let joined = tempdir.as_ref().join(filename.as_str());
517let path = joined.as_path();
518 ab.add_archive(path, Box::new(|_| false)).unwrap();
519 }
520521all_native_libs522 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
523 },
524 );
525if let Err(e) = res {
526sess.dcx().emit_fatal(e);
527 }
528529ab.build(out_filename);
530531let crates = codegen_results.crate_info.used_crates.iter();
532533let fmts = codegen_results534 .crate_info
535 .dependency_formats
536 .get(&CrateType::StaticLib)
537 .expect("no dependency formats for staticlib");
538539let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
540for &cnum in crates {
541let Some(Linkage::Dynamic) = fmts.get(cnum) else {
542continue;
543 };
544let crate_name = codegen_results.crate_info.crate_name[&cnum];
545let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
546if let Some(path) = &used_crate_source.dylib {
547 all_rust_dylibs.push(&**path);
548 } else if used_crate_source.rmeta.is_some() {
549 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
550 } else {
551 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
552 }
553 }
554555all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
556557for print in &sess.opts.prints {
558if print.kind == PrintKind::NativeStaticLibs {
559 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
560 }
561 }
562}
563564/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
565/// DWARF package.
566fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
567let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
568dwp_out_filename.push(".dwp");
569{
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:569",
"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(569u32),
::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);
570571#[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)]
572struct ThorinSession<Relocations> {
573 arena_data: TypedArena<Vec<u8>>,
574 arena_mmap: TypedArena<Mmap>,
575 arena_relocations: TypedArena<Relocations>,
576 }
577578impl<Relocations> ThorinSession<Relocations> {
579fn alloc_mmap(&self, data: Mmap) -> &Mmap {
580&*self.arena_mmap.alloc(data)
581 }
582 }
583584impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
585fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
586&*self.arena_data.alloc(data)
587 }
588589fn alloc_relocation(&self, data: Relocations) -> &Relocations {
590&*self.arena_relocations.alloc(data)
591 }
592593fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
594let file = File::open(&path)?;
595let mmap = (unsafe { Mmap::map(file) })?;
596Ok(self.alloc_mmap(mmap))
597 }
598 }
599600match sess.time("run_thorin", || -> Result<(), thorin::Error> {
601let thorin_sess = ThorinSession::default();
602let mut package = thorin::DwarfPackage::new(&thorin_sess);
603604// Input objs contain .o/.dwo files from the current crate.
605match sess.opts.unstable_opts.split_dwarf_kind {
606 SplitDwarfKind::Single => {
607for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
608 package.add_input_object(input_obj)?;
609 }
610 }
611 SplitDwarfKind::Split => {
612for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
613 package.add_input_object(input_obj)?;
614 }
615 }
616 }
617618// Input rlibs contain .o/.dwo files from dependencies.
619let input_rlibs = cg_results620 .crate_info
621 .used_crate_source
622 .items()
623 .filter_map(|(_, csource)| csource.rlib.as_ref())
624 .into_sorted_stable_ord();
625626for input_rlib in input_rlibs {
627{
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:627",
"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(627u32),
::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);
628 package.add_input_object(input_rlib)?;
629 }
630631// Failing to read the referenced objects is expected for dependencies where the path in the
632 // executable will have been cleaned by Cargo, but the referenced objects will be contained
633 // within rlibs provided as inputs.
634 //
635 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
636 // found, but are provided explicitly above.
637 //
638 // Adding an executable is primarily done to make `thorin` check that all the referenced
639 // dwarf objects are found in the end.
640package.add_executable(
641executable_out_filename,
642 thorin::MissingReferencedObjectBehaviour::Skip,
643 )?;
644645let output_stream = BufWriter::new(
646OpenOptions::new()
647 .read(true)
648 .write(true)
649 .create(true)
650 .truncate(true)
651 .open(dwp_out_filename)?,
652 );
653let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
654package.finish()?.emit(&mut output_stream)?;
655output_stream.result()?;
656output_stream.into_inner().flush()?;
657658Ok(())
659 }) {
660Ok(()) => {}
661Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
662 }
663}
664665#[derive(const _: () =
{
impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for LinkerOutput {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
LinkerOutput { inner: __binding_0 } => {
diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$inner}")));
;
diag.arg("inner", __binding_0);
diag
}
};
}
}
};LintDiagnostic)]
666#[diag("{$inner}")]
667/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
668/// end up with inconsistent languages within the same diagnostic.
669struct LinkerOutput {
670 inner: String,
671}
672673/// Create a dynamic library or executable.
674///
675/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
676/// files as well.
677fn link_natively(
678 sess: &Session,
679 archive_builder_builder: &dyn ArchiveBuilderBuilder,
680 crate_type: CrateType,
681 out_filename: &Path,
682 codegen_results: &CodegenResults,
683 metadata: &EncodedMetadata,
684 tmpdir: &Path,
685 codegen_backend: &'static str,
686) {
687{
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:687",
"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(687u32),
::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);
688let (linker_path, flavor) = linker_and_flavor(sess);
689let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
690691// On AIX, we ship all libraries as .a big_af archive
692 // the expected format is lib<name>.a(libname.so) for the actual
693 // dynamic library. So we link to a temporary .so file to be archived
694 // at the final out_filename location
695let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
696let archive_member =
697should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
698let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
699700let mut cmd = linker_with_args(
701&linker_path,
702flavor,
703sess,
704archive_builder_builder,
705crate_type,
706tmpdir,
707temp_filename,
708codegen_results,
709metadata,
710self_contained_components,
711codegen_backend,
712 );
713714 linker::disable_localization(&mut cmd);
715716for (k, v) in sess.target.link_env.as_ref() {
717 cmd.env(k.as_ref(), v.as_ref());
718 }
719for k in sess.target.link_env_remove.as_ref() {
720 cmd.env_remove(k.as_ref());
721 }
722723for print in &sess.opts.prints {
724if print.kind == PrintKind::LinkArgs {
725let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
726 print.out.overwrite(&content, sess);
727 }
728 }
729730// May have not found libraries in the right formats.
731sess.dcx().abort_if_errors();
732733// Invoke the system linker
734{
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:734",
"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(734u32),
::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:?}");
735let unknown_arg_regex =
736Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
737let mut prog;
738loop {
739prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
740let Ok(ref output) = progelse {
741break;
742 };
743if output.status.success() {
744break;
745 }
746let mut out = output.stderr.clone();
747out.extend(&output.stdout);
748let out = String::from_utf8_lossy(&out);
749750// Check to see if the link failed with an error message that indicates it
751 // doesn't recognize the -no-pie option. If so, re-perform the link step
752 // without it. This is safe because if the linker doesn't support -no-pie
753 // then it should not default to linking executables as pie. Different
754 // versions of gcc seem to use different quotes in the error message so
755 // don't check for them.
756if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))757 && unknown_arg_regex.is_match(&out)
758 && out.contains("-no-pie")
759 && cmd.get_args().iter().any(|e| e == "-no-pie")
760 {
761{
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:761",
"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(761u32),
::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);
762{
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:762",
"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(762u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::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.");
763for arg in cmd.take_args() {
764if arg != "-no-pie" {
765 cmd.arg(arg);
766 }
767 }
768{
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:768",
"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(768u32),
::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:?}");
769continue;
770 }
771772// Check if linking failed with an error message that indicates the driver didn't recognize
773 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
774 // to spawn multiple instances on the happy path to do version checking, and ensures things
775 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
776 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
777if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))778 && unknown_arg_regex.is_match(&out)
779 && out.contains("-fuse-ld=lld")
780 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
781 {
782{
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:782",
"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(782u32),
::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);
783{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:783",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(783u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("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.");
784for arg in cmd.take_args() {
785if arg.to_string_lossy() != "-fuse-ld=lld" {
786 cmd.arg(arg);
787 }
788 }
789{
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:789",
"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(789u32),
::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:?}");
790continue;
791 }
792793// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
794 // Fallback from '-static-pie' to '-static' in that case.
795if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))796 && unknown_arg_regex.is_match(&out)
797 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
798 && cmd.get_args().iter().any(|e| e == "-static-pie")
799 {
800{
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:800",
"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(800u32),
::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);
801{
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:801",
"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(801u32),
::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!(
802"Linker does not support -static-pie command line option. Retrying with -static instead."
803);
804// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
805let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
806let opts = &sess.target;
807let pre_objects = if self_contained_crt_objects {
808&opts.pre_link_objects_self_contained
809 } else {
810&opts.pre_link_objects
811 };
812let post_objects = if self_contained_crt_objects {
813&opts.post_link_objects_self_contained
814 } else {
815&opts.post_link_objects
816 };
817let get_objects = |objects: &CrtObjects, kind| {
818objects819 .get(&kind)
820 .iter()
821 .copied()
822 .flatten()
823 .map(|obj| {
824get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
825 })
826 .collect::<Vec<_>>()
827 };
828let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
829let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
830let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
831let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
832// Assume that we know insertion positions for the replacement arguments from replaced
833 // arguments, which is true for all supported targets.
834if !(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());
835if !(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());
836for arg in cmd.take_args() {
837if arg == "-static-pie" {
838// Replace the output kind.
839cmd.arg("-static");
840 } else if pre_objects_static_pie.contains(&arg) {
841// Replace the pre-link objects (replace the first and remove the rest).
842cmd.args(mem::take(&mut pre_objects_static));
843 } else if post_objects_static_pie.contains(&arg) {
844// Replace the post-link objects (replace the first and remove the rest).
845cmd.args(mem::take(&mut post_objects_static));
846 } else {
847 cmd.arg(arg);
848 }
849 }
850{
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:850",
"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(850u32),
::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:?}");
851continue;
852 }
853854break;
855 }
856857match prog {
858Ok(prog) => {
859let is_msvc_link_exe = sess.target.is_like_msvc
860 && flavor == LinkerFlavor::Msvc(Lld::No)
861// Match exactly "link.exe"
862&& linker_path.to_str() == Some("link.exe");
863864if !prog.status.success() {
865let mut output = prog.stderr.clone();
866output.extend_from_slice(&prog.stdout);
867let escaped_output = escape_linker_output(&output, flavor);
868let err = errors::LinkingFailed {
869 linker_path: &linker_path,
870 exit_status: prog.status,
871 command: cmd,
872escaped_output,
873 verbose: sess.opts.verbose,
874 sysroot_dir: sess.opts.sysroot.path().to_owned(),
875 };
876sess.dcx().emit_err(err);
877// If MSVC's `link.exe` was expected but the return code
878 // is not a Microsoft LNK error then suggest a way to fix or
879 // install the Visual Studio build tools.
880if let Some(code) = prog.status.code() {
881// All Microsoft `link.exe` linking ror codes are
882 // four digit numbers in the range 1000 to 9999 inclusive
883if is_msvc_link_exe && (code < 1000 || code > 9999) {
884let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
885let has_linker =
886 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
887 .is_some();
888889sess.dcx().emit_note(errors::LinkExeUnexpectedError);
890891// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
892 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
893const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
894if code == STATUS_STACK_BUFFER_OVERRUN {
895sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
896 }
897898if is_vs_installed && has_linker {
899// the linker is broken
900sess.dcx().emit_note(errors::RepairVSBuildTools);
901sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
902 } else if is_vs_installed {
903// the linker is not installed
904sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
905 } else {
906// visual studio is not installed
907sess.dcx().emit_note(errors::VisualStudioNotInstalled);
908 }
909 }
910 }
911912sess.dcx().abort_if_errors();
913 }
914915let stderr = escape_string(&prog.stderr);
916let mut stdout = escape_string(&prog.stdout);
917{
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:917",
"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(917u32),
::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}",
&stderr) as &dyn Value))])
});
} else { ; }
};info!("linker stderr:\n{}", &stderr);
918{
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:918",
"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(918u32),
::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}",
&stdout) as &dyn Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &stdout);
919920// Hide some progress messages from link.exe that we don't care about.
921 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
922if is_msvc_link_exe {
923if let Ok(str) = str::from_utf8(&prog.stdout) {
924let mut output = String::with_capacity(str.len());
925for line in stdout.lines() {
926if line.starts_with(" Creating library")
927 || line.starts_with("Generating code")
928 || line.starts_with("Finished generating code")
929 {
930continue;
931 }
932 output += line;
933 output += "\r\n"
934}
935stdout = escape_string(output.trim().as_bytes())
936 }
937 }
938939let level = codegen_results.crate_info.lint_levels.linker_messages;
940let lint = |msg| {
941lint_level(sess, LINKER_MESSAGES, level, None, |diag| {
942LinkerOutput { inner: msg }.decorate_lint(diag)
943 })
944 };
945946if !prog.stderr.is_empty() {
947// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
948let stderr = stderr949 .strip_prefix("warning: ")
950 .unwrap_or(&stderr)
951 .replace(": warning: ", ": ");
952lint(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}", stderr))
})format!("linker stderr: {stderr}"));
953 }
954if !stdout.is_empty() {
955lint(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}", stdout))
})format!("linker stdout: {}", stdout))
956 }
957 }
958Err(e) => {
959let linker_not_found = e.kind() == io::ErrorKind::NotFound;
960961let err = if linker_not_found {
962sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
963 } else {
964sess.dcx().emit_err(errors::UnableToExeLinker {
965linker_path,
966 error: e,
967 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
968 })
969 };
970971if sess.target.is_like_msvc && linker_not_found {
972sess.dcx().emit_note(errors::MsvcMissingLinker);
973sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
974sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
975 }
976err.raise_fatal();
977 }
978 }
979980match sess.split_debuginfo() {
981// If split debug information is disabled or located in individual files
982 // there's nothing to do here.
983SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
984985// If packed split-debuginfo is requested, but the final compilation
986 // doesn't actually have any debug information, then we skip this step.
987SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
988989// On macOS the external `dsymutil` tool is used to create the packed
990 // debug information. Note that this will read debug information from
991 // the objects on the filesystem which we'll clean up later.
992SplitDebuginfo::Packedif sess.target.is_like_darwin => {
993let prog = Command::new("dsymutil").arg(out_filename).output();
994match prog {
995Ok(prog) => {
996if !prog.status.success() {
997let mut output = prog.stderr.clone();
998output.extend_from_slice(&prog.stdout);
999sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1000 status: prog.status,
1001 output: escape_string(&output),
1002 });
1003 }
1004 }
1005Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1006 }
1007 }
10081009// On MSVC packed debug information is produced by the linker itself so
1010 // there's no need to do anything else here.
1011SplitDebuginfo::Packedif sess.target.is_like_windows => {}
10121013// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1014 //
1015 // We cannot rely on the .o paths in the executable because they may have been
1016 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1017 // the .o/.dwo paths explicitly.
1018SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1019 }
10201021let strip = sess.opts.cg.strip;
10221023if sess.target.is_like_darwin {
1024let stripcmd = "rust-objcopy";
1025match (strip, crate_type) {
1026 (Strip::Debuginfo, _) => {
1027strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1028 }
10291030// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1031(
1032 Strip::Symbols,
1033 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1034 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1035 (Strip::Symbols, _) => {
1036strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1037 }
1038 (Strip::None, _) => {}
1039 }
1040 }
10411042if sess.target.is_like_solaris {
1043// Many illumos systems will have both the native 'strip' utility and
1044 // the GNU one. Use the native version explicitly and do not rely on
1045 // what's in the path.
1046 //
1047 // If cross-compiling and there is not a native version, then use
1048 // `llvm-strip` and hope.
1049let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1050match strip {
1051// Always preserve the symbol table (-x).
1052Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1053// Strip::Symbols is handled via the --strip-all linker option.
1054Strip::Symbols => {}
1055 Strip::None => {}
1056 }
1057 }
10581059if sess.target.is_like_aix {
1060// `llvm-strip` doesn't work for AIX - their strip must be used.
1061if !sess.host.is_like_aix {
1062sess.dcx().emit_warn(errors::AixStripNotUsed);
1063 }
1064let stripcmd = "/usr/bin/strip";
1065match strip {
1066 Strip::Debuginfo => {
1067// FIXME: AIX's strip utility only offers option to strip line number information.
1068strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1069 }
1070 Strip::Symbols => {
1071// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1072strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1073 }
1074 Strip::None => {}
1075 }
1076 }
10771078if should_archive {
1079let mut ab = archive_builder_builder.new_archive_builder(sess);
1080ab.add_file(temp_filename);
1081ab.build(out_filename);
1082 }
1083}
10841085fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1086let mut cmd = Command::new(util);
1087cmd.args(options);
10881089let mut new_path = sess.get_tools_search_paths(false);
1090if let Some(path) = env::var_os("PATH") {
1091new_path.extend(env::split_paths(&path));
1092 }
1093cmd.env("PATH", env::join_paths(new_path).unwrap());
10941095let prog = cmd.arg(out_filename).output();
1096match prog {
1097Ok(prog) => {
1098if !prog.status.success() {
1099let mut output = prog.stderr.clone();
1100output.extend_from_slice(&prog.stdout);
1101sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1102util,
1103 status: prog.status,
1104 output: escape_string(&output),
1105 });
1106 }
1107 }
1108Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1109 }
1110}
11111112fn escape_string(s: &[u8]) -> String {
1113match str::from_utf8(s) {
1114Ok(s) => s.to_owned(),
1115Err(_) => ::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()),
1116 }
1117}
11181119#[cfg(not(windows))]
1120fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1121escape_string(s)
1122}
11231124/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1125/// then try to convert the string from the OEM encoding.
1126#[cfg(windows)]
1127fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1128// This only applies to the actual MSVC linker.
1129if flavour != LinkerFlavor::Msvc(Lld::No) {
1130return escape_string(s);
1131 }
1132match str::from_utf8(s) {
1133Ok(s) => return s.to_owned(),
1134Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1135Some(s) => s,
1136// The string is not UTF-8 and isn't valid for the OEM code page
1137None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1138 },
1139 }
1140}
11411142/// Wrappers around the Windows API.
1143#[cfg(windows)]
1144mod win {
1145use windows::Win32::Globalization::{
1146 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1147 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1148 };
11491150/// Get the Windows system OEM code page. This is most notably the code page
1151 /// used for link.exe's output.
1152pub(super) fn oem_code_page() -> u32 {
1153unsafe {
1154let mut cp: u32 = 0;
1155// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1156 // But the API requires us to pass the data as though it's a [u16] string.
1157let len = size_of::<u32>() / size_of::<u16>();
1158let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1159let len_written = GetLocaleInfoEx(
1160 LOCALE_NAME_SYSTEM_DEFAULT,
1161 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1162Some(data),
1163 );
1164if len_written as usize == len { cp } else { CP_OEMCP }
1165 }
1166 }
1167/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1168 /// The string does not need to be null terminated.
1169 ///
1170 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1171 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1172 ///
1173 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1174 /// any invalid bytes for the expected encoding.
1175pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1176// `MultiByteToWideChar` requires a length to be a "positive integer".
1177if s.len() > isize::MAX as usize {
1178return None;
1179 }
1180// Error if the string is not valid for the expected code page.
1181let flags = MB_ERR_INVALID_CHARS;
1182// Call MultiByteToWideChar twice.
1183 // First to calculate the length then to convert the string.
1184let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1185if len > 0 {
1186let mut utf16 = vec![0; len as usize];
1187 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1188if len > 0 {
1189return utf16.get(..len as usize).map(String::from_utf16_lossy);
1190 }
1191 }
1192None
1193}
1194}
11951196fn add_sanitizer_libraries(
1197 sess: &Session,
1198 flavor: LinkerFlavor,
1199 crate_type: CrateType,
1200 linker: &mut dyn Linker,
1201) {
1202if sess.target.is_like_android {
1203// Sanitizer runtime libraries are provided dynamically on Android
1204 // targets.
1205return;
1206 }
12071208if sess.opts.unstable_opts.external_clangrt {
1209// Linking against in-tree sanitizer runtimes is disabled via
1210 // `-Z external-clangrt`
1211return;
1212 }
12131214if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1215return;
1216 }
12171218// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1219 // which should be linked to both executables and dynamic libraries.
1220 // Everywhere else the runtimes are currently distributed as static
1221 // libraries which should be linked to executables only.
1222if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1223 crate_type,
1224 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1225 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1226 {
1227return;
1228 }
12291230let sanitizer = sess.sanitizers();
1231if sanitizer.contains(SanitizerSet::ADDRESS) {
1232link_sanitizer_runtime(sess, flavor, linker, "asan");
1233 }
1234if sanitizer.contains(SanitizerSet::DATAFLOW) {
1235link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1236 }
1237if sanitizer.contains(SanitizerSet::LEAK)
1238 && !sanitizer.contains(SanitizerSet::ADDRESS)
1239 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1240 {
1241link_sanitizer_runtime(sess, flavor, linker, "lsan");
1242 }
1243if sanitizer.contains(SanitizerSet::MEMORY) {
1244link_sanitizer_runtime(sess, flavor, linker, "msan");
1245 }
1246if sanitizer.contains(SanitizerSet::THREAD) {
1247link_sanitizer_runtime(sess, flavor, linker, "tsan");
1248 }
1249if sanitizer.contains(SanitizerSet::HWADDRESS) {
1250link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1251 }
1252if sanitizer.contains(SanitizerSet::SAFESTACK) {
1253link_sanitizer_runtime(sess, flavor, linker, "safestack");
1254 }
1255if sanitizer.contains(SanitizerSet::REALTIME) {
1256link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1257 }
1258}
12591260fn link_sanitizer_runtime(
1261 sess: &Session,
1262 flavor: LinkerFlavor,
1263 linker: &mut dyn Linker,
1264 name: &str,
1265) {
1266fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1267let path = sess.target_tlib_path.dir.join(filename);
1268if path.exists() {
1269sess.target_tlib_path.dir.clone()
1270 } else {
1271 filesearch::make_target_lib_path(
1272&sess.opts.sysroot.default,
1273sess.opts.target_triple.tuple(),
1274 )
1275 }
1276 }
12771278let channel =
1279::core::option::Option::Some("nightly")option_env!("CFG_RELEASE_CHANNEL").map(|channel| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-{0}", channel))
})format!("-{channel}")).unwrap_or_default();
12801281if sess.target.is_like_darwin {
1282// On Apple platforms, the sanitizer is always built as a dylib, and
1283 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1284 // rpath to the library as well (the rpath should be absolute, see
1285 // PR #41352 for details).
1286let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1287let path = find_sanitizer_runtime(sess, &filename);
1288let rpath = path.to_str().expect("non-utf8 component in path");
1289linker.link_args(&["-rpath", rpath]);
1290linker.link_dylib_by_name(&filename, false, true);
1291 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1292// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1293 // compatible ASAN library.
1294linker.link_arg("/INFERASANLIBS");
1295 } else {
1296let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1297let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1298linker.link_staticlib_by_path(&path, true);
1299 }
1300}
13011302/// Returns a boolean indicating whether the specified crate should be ignored
1303/// during LTO.
1304///
1305/// Crates ignored during LTO are not lumped together in the "massive object
1306/// file" that we create and are linked in their normal rlib states. See
1307/// comments below for what crates do not participate in LTO.
1308///
1309/// It's unusual for a crate to not participate in LTO. Typically only
1310/// compiler-specific and unstable crates have a reason to not participate in
1311/// LTO.
1312pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1313// If our target enables builtin function lowering in LLVM then the
1314 // crates providing these functions don't participate in LTO (e.g.
1315 // no_builtins or compiler builtins crates).
1316!sess.target.no_builtins
1317 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1318}
13191320/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1321pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1322fn infer_from(
1323 sess: &Session,
1324 linker: Option<PathBuf>,
1325 flavor: Option<LinkerFlavor>,
1326 features: LinkerFeaturesCli,
1327 ) -> Option<(PathBuf, LinkerFlavor)> {
1328let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1329match (linker, flavor) {
1330 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1331// only the linker flavor is known; use the default linker for the selected flavor
1332(None, Some(flavor)) => Some((
1333PathBuf::from(match flavor {
1334 LinkerFlavor::Gnu(Cc::Yes, _)
1335 | LinkerFlavor::Darwin(Cc::Yes, _)
1336 | LinkerFlavor::WasmLld(Cc::Yes)
1337 | LinkerFlavor::Unix(Cc::Yes) => {
1338if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1339// On historical Solaris systems, "cc" may have
1340 // been Sun Studio, which is not flag-compatible
1341 // with "gcc". This history casts a long shadow,
1342 // and many modern illumos distributions today
1343 // ship GCC as "gcc" without also making it
1344 // available as "cc".
1345"gcc"
1346} else {
1347"cc"
1348}
1349 }
1350 LinkerFlavor::Gnu(_, Lld::Yes)
1351 | LinkerFlavor::Darwin(_, Lld::Yes)
1352 | LinkerFlavor::WasmLld(..)
1353 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1354 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1355"ld"
1356}
1357 LinkerFlavor::Msvc(..) => "link.exe",
1358 LinkerFlavor::EmCc => {
1359if falsecfg!(windows) {
1360"emcc.bat"
1361} else {
1362"emcc"
1363}
1364 }
1365 LinkerFlavor::Bpf => "bpf-linker",
1366 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1367 LinkerFlavor::Ptx => "rust-ptx-linker",
1368 }),
1369flavor,
1370 )),
1371 (Some(linker), None) => {
1372let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1373sess.dcx().emit_fatal(errors::LinkerFileStem);
1374 });
1375let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1376let flavor = adjust_flavor_to_features(flavor, features);
1377Some((linker, flavor))
1378 }
1379 (None, None) => None,
1380 }
1381 }
13821383// While linker flavors and linker features are isomorphic (and thus targets don't need to
1384 // define features separately), we use the flavor as the root piece of data and have the
1385 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1386 // both yet.
1387fn adjust_flavor_to_features(
1388 flavor: LinkerFlavor,
1389 features: LinkerFeaturesCli,
1390 ) -> LinkerFlavor {
1391// Note: a linker feature cannot be both enabled and disabled on the CLI.
1392if features.enabled.contains(LinkerFeatures::LLD) {
1393flavor.with_lld_enabled()
1394 } else if features.disabled.contains(LinkerFeatures::LLD) {
1395flavor.with_lld_disabled()
1396 } else {
1397flavor1398 }
1399 }
14001401let features = sess.opts.cg.linker_features;
14021403// linker and linker flavor specified via command line have precedence over what the target
1404 // specification specifies
1405let linker_flavor = match sess.opts.cg.linker_flavor {
1406// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1407Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1408Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1409// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1410linker_flavor => {
1411linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1412 }
1413 };
1414if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1415return ret;
1416 }
14171418if let Some(ret) = infer_from(
1419sess,
1420sess.target.linker.as_deref().map(PathBuf::from),
1421Some(sess.target.linker_flavor),
1422features,
1423 ) {
1424return ret;
1425 }
14261427::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");
1428}
14291430/// Returns a pair of boolean indicating whether we should preserve the object and
1431/// dwarf object files on the filesystem for their debug information. This is often
1432/// useful with split-dwarf like schemes.
1433fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1434// If the objects don't have debuginfo there's nothing to preserve.
1435if sess.opts.debuginfo == config::DebugInfo::None {
1436return (false, false);
1437 }
14381439match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1440// If there is no split debuginfo then do not preserve objects.
1441(SplitDebuginfo::Off, _) => (false, false),
1442// If there is packed split debuginfo, then the debuginfo in the objects
1443 // has been packaged and the objects can be deleted.
1444(SplitDebuginfo::Packed, _) => (false, false),
1445// If there is unpacked split debuginfo and the current target can not use
1446 // split dwarf, then keep objects.
1447(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1448// If there is unpacked split debuginfo and the target can use split dwarf, then
1449 // keep the object containing that debuginfo (whether that is an object file or
1450 // dwarf object file depends on the split dwarf kind).
1451(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1452 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1453 }
1454}
14551456#[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)]
1457enum RlibFlavor {
1458 Normal,
1459 StaticlibBase,
1460}
14611462fn print_native_static_libs(
1463 sess: &Session,
1464 out: &OutFileName,
1465 all_native_libs: &[NativeLib],
1466 all_rust_dylibs: &[&Path],
1467) {
1468let mut lib_args: Vec<_> = all_native_libs1469 .iter()
1470 .filter(|l| relevant_lib(sess, l))
1471 .filter_map(|lib| {
1472let name = lib.name;
1473match lib.kind {
1474 NativeLibKind::Static { bundle: Some(false), .. }
1475 | NativeLibKind::Dylib { .. }
1476 | NativeLibKind::Unspecified => {
1477let verbatim = lib.verbatim;
1478if sess.target.is_like_msvc {
1479let (prefix, suffix) = sess.staticlib_components(verbatim);
1480Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1481 } else if sess.target.linker_flavor.is_gnu() {
1482Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1483 } else {
1484Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1485 }
1486 }
1487 NativeLibKind::Framework { .. } => {
1488// ld-only syntax, since there are no frameworks in MSVC
1489Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1490 }
1491// These are included, no need to print them
1492NativeLibKind::Static { bundle: None | Some(true), .. }
1493 | NativeLibKind::LinkArg1494 | NativeLibKind::WasmImportModule1495 | NativeLibKind::RawDylib { .. } => None,
1496 }
1497 })
1498// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1499.dedup()
1500 .collect();
1501for path in all_rust_dylibs {
1502// FIXME deduplicate with add_dynamic_crate
15031504 // Just need to tell the linker about where the library lives and
1505 // what its name is
1506let parent = path.parent();
1507if let Some(dir) = parent {
1508let dir = fix_windows_verbatim_for_gcc(dir);
1509if sess.target.is_like_msvc {
1510let mut arg = String::from("/LIBPATH:");
1511 arg.push_str(&dir.display().to_string());
1512 lib_args.push(arg);
1513 } else {
1514 lib_args.push("-L".to_owned());
1515 lib_args.push(dir.display().to_string());
1516 }
1517 }
1518let stem = path.file_stem().unwrap().to_str().unwrap();
1519// Convert library file-stem into a cc -l argument.
1520let lib = if let Some(lib) = stem.strip_prefix("lib")
1521 && !sess.target.is_like_windows
1522 {
1523 lib
1524 } else {
1525 stem
1526 };
1527let path = parent.unwrap_or_else(|| Path::new(""));
1528if sess.target.is_like_msvc {
1529// When producing a dll, the MSVC linker may not actually emit a
1530 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1531 // check to see if the file is there and just omit linking to it if it's
1532 // not present.
1533let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1534if path.join(&name).exists() {
1535 lib_args.push(name);
1536 }
1537 } else {
1538 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1539 }
1540 }
15411542match out {
1543 OutFileName::Real(path) => {
1544out.overwrite(&lib_args.join(" "), sess);
1545sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1546 }
1547 OutFileName::Stdout => {
1548sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1549// Prefix for greppability
1550 // Note: This must not be translated as tools are allowed to depend on this exact string.
1551sess.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(" ")));
1552 }
1553 }
1554}
15551556fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1557let file_path = sess.target_tlib_path.dir.join(name);
1558if file_path.exists() {
1559return file_path;
1560 }
1561// Special directory with objects used only in self-contained linkage mode
1562if self_contained {
1563let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1564if file_path.exists() {
1565return file_path;
1566 }
1567 }
1568for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1569let file_path = search_path.dir.join(name);
1570if file_path.exists() {
1571return file_path;
1572 }
1573 }
1574PathBuf::from(name)
1575}
15761577fn exec_linker(
1578 sess: &Session,
1579 cmd: &Command,
1580 out_filename: &Path,
1581 flavor: LinkerFlavor,
1582 tmpdir: &Path,
1583) -> io::Result<Output> {
1584// When attempting to spawn the linker we run a risk of blowing out the
1585 // size limits for spawning a new process with respect to the arguments
1586 // we pass on the command line.
1587 //
1588 // Here we attempt to handle errors from the OS saying "your list of
1589 // arguments is too big" by reinvoking the linker again with an `@`-file
1590 // that contains all the arguments (aka 'response' files).
1591 // The theory is that this is then accepted on all linkers and the linker
1592 // will read all its options out of there instead of looking at the command line.
1593if !cmd.very_likely_to_exceed_some_spawn_limit() {
1594match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1595Ok(child) => {
1596let output = child.wait_with_output();
1597flush_linked_file(&output, out_filename)?;
1598return output;
1599 }
1600Err(ref e) if command_line_too_big(e) => {
1601{
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:1601",
"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(1601u32),
::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);
1602 }
1603Err(e) => return Err(e),
1604 }
1605 }
16061607{
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:1607",
"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(1607u32),
::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");
1608let mut cmd2 = cmd.clone();
1609let mut args = String::new();
1610for arg in cmd2.take_args() {
1611 args.push_str(
1612&Escape {
1613 arg: arg.to_str().unwrap(),
1614// Windows-style escaping for @-files is used by
1615 // - all linkers targeting MSVC-like targets, including LLD
1616 // - all LLD flavors running on Windows hosts
1617 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1618is_like_msvc: sess.target.is_like_msvc
1619 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1620 }
1621 .to_string(),
1622 );
1623 args.push('\n');
1624 }
1625let file = tmpdir.join("linker-arguments");
1626let bytes = if sess.target.is_like_msvc {
1627let mut out = Vec::with_capacity((1 + args.len()) * 2);
1628// start the stream with a UTF-16 BOM
1629for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1630// encode in little endian
1631out.push(c as u8);
1632 out.push((c >> 8) as u8);
1633 }
1634out1635 } else {
1636args.into_bytes()
1637 };
1638 fs::write(&file, &bytes)?;
1639cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1640{
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:1640",
"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(1640u32),
::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);
1641let output = cmd2.output();
1642flush_linked_file(&output, out_filename)?;
1643return output;
16441645#[cfg(not(windows))]
1646fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1647Ok(())
1648 }
16491650#[cfg(windows)]
1651fn flush_linked_file(
1652 command_output: &io::Result<Output>,
1653 out_filename: &Path,
1654 ) -> io::Result<()> {
1655// On Windows, under high I/O load, output buffers are sometimes not flushed,
1656 // even long after process exit, causing nasty, non-reproducible output bugs.
1657 //
1658 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1659 //
1660 // А full writeup of the original Chrome bug can be found at
1661 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
16621663if let &Ok(ref out) = command_output {
1664if out.status.success() {
1665if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1666 of.sync_all()?;
1667 }
1668 }
1669 }
16701671Ok(())
1672 }
16731674#[cfg(unix)]
1675fn command_line_too_big(err: &io::Error) -> bool {
1676err.raw_os_error() == Some(::libc::E2BIG)
1677 }
16781679#[cfg(windows)]
1680fn command_line_too_big(err: &io::Error) -> bool {
1681const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1682 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1683 }
16841685#[cfg(not(any(unix, windows)))]
1686fn command_line_too_big(_: &io::Error) -> bool {
1687false
1688}
16891690struct Escape<'a> {
1691 arg: &'a str,
1692 is_like_msvc: bool,
1693 }
16941695impl<'a> fmt::Displayfor Escape<'a> {
1696fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1697if self.is_like_msvc {
1698// This is "documented" at
1699 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1700 //
1701 // Unfortunately there's not a great specification of the
1702 // syntax I could find online (at least) but some local
1703 // testing showed that this seemed sufficient-ish to catch
1704 // at least a few edge cases.
1705f.write_fmt(format_args!("\""))write!(f, "\"")?;
1706for c in self.arg.chars() {
1707match c {
1708'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1709 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1710 }
1711 }
1712f.write_fmt(format_args!("\""))write!(f, "\"")?;
1713 } else {
1714// This is documented at https://linux.die.net/man/1/ld, namely:
1715 //
1716 // > Options in file are separated by whitespace. A whitespace
1717 // > character may be included in an option by surrounding the
1718 // > entire option in either single or double quotes. Any
1719 // > character (including a backslash) may be included by
1720 // > prefixing the character to be included with a backslash.
1721 //
1722 // We put an argument on each line, so all we need to do is
1723 // ensure the line is interpreted as one whole argument.
1724for c in self.arg.chars() {
1725match c {
1726'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1727 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1728 }
1729 }
1730 }
1731Ok(())
1732 }
1733 }
1734}
17351736fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1737let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1738 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1739 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1740 LinkOutputKind::DynamicPicExe1741 }
1742 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1743 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1744 LinkOutputKind::StaticPicExe1745 }
1746 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1747 (_, true, _) => LinkOutputKind::StaticDylib,
1748 (_, false, _) => LinkOutputKind::DynamicDylib,
1749 };
17501751// Adjust the output kind to target capabilities.
1752let opts = &sess.target;
1753let pic_exe_supported = opts.position_independent_executables;
1754let static_pic_exe_supported = opts.static_position_independent_executables;
1755let static_dylib_supported = opts.crt_static_allows_dylibs;
1756match kind {
1757 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1758 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1759 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1760_ => kind,
1761 }
1762}
17631764// Returns true if linker is located within sysroot
1765fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1766let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1767linker.with_extension("exe")
1768 } else {
1769linker.to_path_buf()
1770 };
1771for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1772let full_path = dir.join(&linker_with_extension);
1773// If linker comes from sysroot assume self-contained mode
1774if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1775return false;
1776 }
1777 }
1778true
1779}
17801781/// Various toolchain components used during linking are used from rustc distribution
1782/// instead of being found somewhere on the host system.
1783/// We only provide such support for a very limited number of targets.
1784fn self_contained_components(
1785 sess: &Session,
1786 crate_type: CrateType,
1787 linker: &Path,
1788) -> LinkSelfContainedComponents {
1789// Turn the backwards compatible bool values for `self_contained` into fully inferred
1790 // `LinkSelfContainedComponents`.
1791let self_contained =
1792if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1793// Emit an error if the user requested self-contained mode on the CLI but the target
1794 // explicitly refuses it.
1795if sess.target.link_self_contained.is_disabled() {
1796sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1797 }
1798self_contained1799 } else {
1800match sess.target.link_self_contained {
1801 LinkSelfContainedDefault::False => false,
1802 LinkSelfContainedDefault::True => true,
18031804 LinkSelfContainedDefault::WithComponents(components) => {
1805// For target specs with explicitly enabled components, we can return them
1806 // directly.
1807return components;
1808 }
18091810// FIXME: Find a better heuristic for "native musl toolchain is available",
1811 // based on host and linker path, for example.
1812 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1813LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1814 LinkSelfContainedDefault::InferredForMingw => {
1815sess.host == sess.target
1816 && sess.target.abi != Abi::Uwp1817 && detect_self_contained_mingw(sess, linker)
1818 }
1819 }
1820 };
1821if self_contained {
1822LinkSelfContainedComponents::all()
1823 } else {
1824LinkSelfContainedComponents::empty()
1825 }
1826}
18271828/// Add pre-link object files defined by the target spec.
1829fn add_pre_link_objects(
1830 cmd: &mut dyn Linker,
1831 sess: &Session,
1832 flavor: LinkerFlavor,
1833 link_output_kind: LinkOutputKind,
1834 self_contained: bool,
1835) {
1836// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1837 // so Fuchsia has to be special-cased.
1838let opts = &sess.target;
1839let empty = Default::default();
1840let objects = if self_contained {
1841&opts.pre_link_objects_self_contained
1842 } 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, _))) {
1843&opts.pre_link_objects
1844 } else {
1845&empty1846 };
1847for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1848 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1849 }
1850}
18511852/// Add post-link object files defined by the target spec.
1853fn add_post_link_objects(
1854 cmd: &mut dyn Linker,
1855 sess: &Session,
1856 link_output_kind: LinkOutputKind,
1857 self_contained: bool,
1858) {
1859let objects = if self_contained {
1860&sess.target.post_link_objects_self_contained
1861 } else {
1862&sess.target.post_link_objects
1863 };
1864for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1865 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1866 }
1867}
18681869/// Add arbitrary "pre-link" args defined by the target spec or from command line.
1870/// FIXME: Determine where exactly these args need to be inserted.
1871fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1872if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1873cmd.verbatim_args(args.iter().map(Deref::deref));
1874 }
18751876cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1877}
18781879/// Add a link script embedded in the target, if applicable.
1880fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1881match (crate_type, &sess.target.link_script) {
1882 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1883if !sess.target.linker_flavor.is_gnu() {
1884sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1885 }
18861887let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
18881889let path = tmpdir.join(file_name);
1890if let Err(error) = fs::write(&path, script.as_ref()) {
1891sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1892 }
18931894cmd.link_arg("--script").link_arg(path);
1895 }
1896_ => {}
1897 }
1898}
18991900/// Add arbitrary "user defined" args defined from command line.
1901/// FIXME: Determine where exactly these args need to be inserted.
1902fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1903cmd.verbatim_args(&sess.opts.cg.link_args);
1904}
19051906/// Add arbitrary "late link" args defined by the target spec.
1907/// FIXME: Determine where exactly these args need to be inserted.
1908fn add_late_link_args(
1909 cmd: &mut dyn Linker,
1910 sess: &Session,
1911 flavor: LinkerFlavor,
1912 crate_type: CrateType,
1913 codegen_results: &CodegenResults,
1914) {
1915let any_dynamic_crate = crate_type == CrateType::Dylib1916 || crate_type == CrateType::Sdylib1917 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1918*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1919 });
1920if any_dynamic_crate {
1921if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1922cmd.verbatim_args(args.iter().map(Deref::deref));
1923 }
1924 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1925cmd.verbatim_args(args.iter().map(Deref::deref));
1926 }
1927if let Some(args) = sess.target.late_link_args.get(&flavor) {
1928cmd.verbatim_args(args.iter().map(Deref::deref));
1929 }
1930}
19311932/// Add arbitrary "post-link" args defined by the target spec.
1933/// FIXME: Determine where exactly these args need to be inserted.
1934fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1935if let Some(args) = sess.target.post_link_args.get(&flavor) {
1936cmd.verbatim_args(args.iter().map(Deref::deref));
1937 }
1938}
19391940/// Add a synthetic object file that contains reference to all symbols that we want to expose to
1941/// the linker.
1942///
1943/// Background: we implement rlibs as static library (archives). Linkers treat archives
1944/// differently from object files: all object files participate in linking, while archives will
1945/// only participate in linking if they can satisfy at least one undefined reference (version
1946/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1947/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1948/// can't keep them either. This causes #47384.
1949///
1950/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
1951/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
1952/// we instead just introduce an undefined reference to them. This could be done by `-u` command
1953/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1954/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1955/// from removing them, and this is especially problematic for embedded programming where every
1956/// byte counts.
1957///
1958/// This method creates a synthetic object file, which contains undefined references to all symbols
1959/// that are necessary for the linking. They are only present in symbol table but not actually
1960/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1961/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
1962///
1963/// There's a few internal crates in the standard library (aka libcore and
1964/// libstd) which actually have a circular dependence upon one another. This
1965/// currently arises through "weak lang items" where libcore requires things
1966/// like `rust_begin_unwind` but libstd ends up defining it. To get this
1967/// circular dependence to work correctly we declare some of these things
1968/// in this synthetic object.
1969fn add_linked_symbol_object(
1970 cmd: &mut dyn Linker,
1971 sess: &Session,
1972 tmpdir: &Path,
1973 symbols: &[(String, SymbolExportKind)],
1974) {
1975if symbols.is_empty() {
1976return;
1977 }
19781979let Some(mut file) = super::metadata::create_object_file(sess) else {
1980return;
1981 };
19821983if file.format() == object::BinaryFormat::Coff {
1984// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1985 // so add an empty section.
1986file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
19871988// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1989 // default mangler in `object` crate.
1990file.set_mangling(object::write::Mangling::None);
1991 }
19921993if file.format() == object::BinaryFormat::MachO {
1994// Divide up the sections into sub-sections via symbols for dead code stripping.
1995 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
1996 // discard on MachO targets.
1997file.set_subsections_via_symbols();
1998 }
19992000// ld64 requires a relocation to load undefined symbols, see below.
2001 // Not strictly needed if linking with lld, but might as well do it there too.
2002let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2003Some(file.add_section(
2004file.segment_name(object::write::StandardSegment::Data).to_vec(),
2005"__data".into(),
2006 object::SectionKind::Data,
2007 ))
2008 } else {
2009None2010 };
20112012for (sym, kind) in symbols.iter() {
2013let symbol = file.add_symbol(object::write::Symbol {
2014 name: sym.clone().into(),
2015 value: 0,
2016 size: 0,
2017 kind: match kind {
2018 SymbolExportKind::Text => object::SymbolKind::Text,
2019 SymbolExportKind::Data => object::SymbolKind::Data,
2020 SymbolExportKind::Tls => object::SymbolKind::Tls,
2021 },
2022 scope: object::SymbolScope::Unknown,
2023 weak: false,
2024 section: object::write::SymbolSection::Undefined,
2025 flags: object::SymbolFlags::None,
2026 });
20272028// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2029 //
2030 // Code-wise, the relevant parts of ld64 are roughly:
2031 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2032 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2033 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2034 //
2035 // 2. Read the archive table of contents (__.SYMDEF file).
2036 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2037 //
2038 // 3. Begin linking by loading "atoms" from input files.
2039 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2040 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2041 //
2042 // a. Directly specified object files (`.o`) are parsed immediately.
2043 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2044 //
2045 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2046 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2047 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2048 //
2049 // - Relocations/fixups are atoms.
2050 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2051 //
2052 // b. Archives are not parsed yet.
2053 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2054 //
2055 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2056 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2057 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2058 //
2059 // All of the steps above are fairly similar to other linkers, except that **it completely
2060 // ignores undefined symbols**.
2061 //
2062 // So to make this trick work on ld64, we need to do something else to load the relevant
2063 // object files. We do this by inserting a relocation (fixup) for each symbol.
2064if let Some(section) = ld64_section_helper {
2065 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2066 .expect("failed adding relocation");
2067 }
2068 }
20692070let path = tmpdir.join("symbols.o");
2071let result = std::fs::write(&path, file.write().unwrap());
2072if let Err(error) = result {
2073sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2074 }
2075cmd.add_object(&path);
2076}
20772078/// Add object files containing code from the current crate.
2079fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2080for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2081 cmd.add_object(obj);
2082 }
2083}
20842085/// Add object files for allocator code linked once for the whole crate tree.
2086fn add_local_crate_allocator_objects(
2087 cmd: &mut dyn Linker,
2088 codegen_results: &CodegenResults,
2089 crate_type: CrateType,
2090) {
2091if needs_allocator_shim_for_linking(&codegen_results.crate_info.dependency_formats, crate_type)
2092 {
2093if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref())
2094 {
2095cmd.add_object(obj);
2096 }
2097 }
2098}
20992100/// Add object files containing metadata for the current crate.
2101fn add_local_crate_metadata_objects(
2102 cmd: &mut dyn Linker,
2103 sess: &Session,
2104 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2105 crate_type: CrateType,
2106 tmpdir: &Path,
2107 codegen_results: &CodegenResults,
2108 metadata: &EncodedMetadata,
2109) {
2110// When linking a dynamic library, we put the metadata into a section of the
2111 // executable. This metadata is in a separate object file from the main
2112 // object file, so we create and link it in here.
2113if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2114let data = archive_builder_builder.create_dylib_metadata_wrapper(
2115sess,
2116&metadata,
2117&codegen_results.crate_info.metadata_symbol,
2118 );
2119let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
21202121cmd.add_object(&obj);
2122 }
2123}
21242125/// Add sysroot and other globally set directories to the directory search list.
2126fn add_library_search_dirs(
2127 cmd: &mut dyn Linker,
2128 sess: &Session,
2129 self_contained_components: LinkSelfContainedComponents,
2130 apple_sdk_root: Option<&Path>,
2131) {
2132if !sess.opts.unstable_opts.link_native_libraries {
2133return;
2134 }
21352136let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2137let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2138if is_framework {
2139cmd.framework_path(dir);
2140 } else {
2141cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2142 }
2143 ControlFlow::<()>::Continue(())
2144 });
2145}
21462147/// Add options making relocation sections in the produced ELF files read-only
2148/// and suppressing lazy binding.
2149fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2150match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2151 RelroLevel::Full => cmd.full_relro(),
2152 RelroLevel::Partial => cmd.partial_relro(),
2153 RelroLevel::Off => cmd.no_relro(),
2154 RelroLevel::None => {}
2155 }
2156}
21572158/// Add library search paths used at runtime by dynamic linkers.
2159fn add_rpath_args(
2160 cmd: &mut dyn Linker,
2161 sess: &Session,
2162 codegen_results: &CodegenResults,
2163 out_filename: &Path,
2164) {
2165if !sess.target.has_rpath {
2166return;
2167 }
21682169// FIXME (#2397): At some point we want to rpath our guesses as to
2170 // where extern libraries might live, based on the
2171 // add_lib_search_paths
2172if sess.opts.cg.rpath {
2173let libs = codegen_results2174 .crate_info
2175 .used_crates
2176 .iter()
2177 .filter_map(|cnum| codegen_results.crate_info.used_crate_source[cnum].dylib.as_deref())
2178 .collect::<Vec<_>>();
2179let rpath_config = RPathConfig {
2180 libs: &*libs,
2181 out_filename: out_filename.to_path_buf(),
2182 is_like_darwin: sess.target.is_like_darwin,
2183 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2184 };
2185cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2186 }
2187}
21882189fn add_c_staticlib_symbols(
2190 sess: &Session,
2191 lib: &NativeLib,
2192 out: &mut Vec<(String, SymbolExportKind)>,
2193) -> io::Result<()> {
2194let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
21952196let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
21972198let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2199 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22002201for member in archive.members() {
2202let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22032204let data = member
2205 .data(&*archive_map)
2206 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22072208// clang LTO: raw LLVM bitcode
2209if data.starts_with(b"BC\xc0\xde") {
2210return Err(io::Error::new(
2211 io::ErrorKind::InvalidData,
2212"LLVM bitcode object in C static library (LTO not supported)",
2213 ));
2214 }
22152216let object = object::File::parse(&*data)
2217 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22182219// gcc / clang ELF / Mach-O LTO
2220if object.sections().any(|s| {
2221 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2222 }) {
2223return Err(io::Error::new(
2224 io::ErrorKind::InvalidData,
2225"LTO object in C static library is not supported",
2226 ));
2227 }
22282229for symbol in object.symbols() {
2230if symbol.scope() != object::SymbolScope::Dynamic {
2231continue;
2232 }
22332234let name = match symbol.name() {
2235Ok(n) => n,
2236Err(_) => continue,
2237 };
22382239let export_kind = match symbol.kind() {
2240 object::SymbolKind::Text => SymbolExportKind::Text,
2241 object::SymbolKind::Data => SymbolExportKind::Data,
2242_ => continue,
2243 };
22442245// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2246 // Need to be resolved.
2247out.push((name.to_string(), export_kind));
2248 }
2249 }
22502251Ok(())
2252}
22532254/// Produce the linker command line containing linker path and arguments.
2255///
2256/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2257/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2258/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2259/// to the linking process as a whole.
2260/// Order-independent options may still override each other in order-dependent fashion,
2261/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2262fn linker_with_args(
2263 path: &Path,
2264 flavor: LinkerFlavor,
2265 sess: &Session,
2266 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2267 crate_type: CrateType,
2268 tmpdir: &Path,
2269 out_filename: &Path,
2270 codegen_results: &CodegenResults,
2271 metadata: &EncodedMetadata,
2272 self_contained_components: LinkSelfContainedComponents,
2273 codegen_backend: &'static str,
2274) -> Command {
2275let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2276let cmd = &mut *super::linker::get_linker(
2277sess,
2278path,
2279flavor,
2280self_contained_components.are_any_components_enabled(),
2281&codegen_results.crate_info.target_cpu,
2282codegen_backend,
2283 );
2284let link_output_kind = link_output_kind(sess, crate_type);
22852286let mut export_symbols = codegen_results.crate_info.exported_symbols[&crate_type].clone();
22872288if crate_type == CrateType::Cdylib {
2289let mut seen = FxHashSet::default();
22902291for lib in &codegen_results.crate_info.used_libraries {
2292if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2293 && seen.insert((lib.name, lib.verbatim))
2294 {
2295if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2296 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2297"failed to process C static library `{}`: {}",
2298 lib.name, err
2299 ));
2300 }
2301 }
2302 }
2303 }
23042305// ------------ Early order-dependent options ------------
23062307 // If we're building something like a dynamic library then some platforms
2308 // need to make sure that all symbols are exported correctly from the
2309 // dynamic library.
2310 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2311 // at least on some platforms (e.g. windows-gnu).
2312cmd.export_symbols(tmpdir, crate_type, &export_symbols);
23132314// Can be used for adding custom CRT objects or overriding order-dependent options above.
2315 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2316 // introduce a target spec option for order-independent linker options and migrate built-in
2317 // specs to it.
2318add_pre_link_args(cmd, sess, flavor);
23192320// ------------ Object code and libraries, order-dependent ------------
23212322 // Pre-link CRT objects.
2323add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
23242325add_linked_symbol_object(
2326cmd,
2327sess,
2328tmpdir,
2329&codegen_results.crate_info.linked_symbols[&crate_type],
2330 );
23312332// Sanitizer libraries.
2333add_sanitizer_libraries(sess, flavor, crate_type, cmd);
23342335// Object code from the current crate.
2336 // Take careful note of the ordering of the arguments we pass to the linker
2337 // here. Linkers will assume that things on the left depend on things to the
2338 // right. Things on the right cannot depend on things on the left. This is
2339 // all formally implemented in terms of resolving symbols (libs on the right
2340 // resolve unknown symbols of libs on the left, but not vice versa).
2341 //
2342 // For this reason, we have organized the arguments we pass to the linker as
2343 // such:
2344 //
2345 // 1. The local object that LLVM just generated
2346 // 2. Local native libraries
2347 // 3. Upstream rust libraries
2348 // 4. Upstream native libraries
2349 //
2350 // The rationale behind this ordering is that those items lower down in the
2351 // list can't depend on items higher up in the list. For example nothing can
2352 // depend on what we just generated (e.g., that'd be a circular dependency).
2353 // Upstream rust libraries are not supposed to depend on our local native
2354 // libraries as that would violate the structure of the DAG, in that
2355 // scenario they are required to link to them as well in a shared fashion.
2356 //
2357 // Note that upstream rust libraries may contain native dependencies as
2358 // well, but they also can't depend on what we just started to add to the
2359 // link line. And finally upstream native libraries can't depend on anything
2360 // in this DAG so far because they can only depend on other native libraries
2361 // and such dependencies are also required to be specified.
2362add_local_crate_regular_objects(cmd, codegen_results);
2363add_local_crate_metadata_objects(
2364cmd,
2365sess,
2366archive_builder_builder,
2367crate_type,
2368tmpdir,
2369codegen_results,
2370metadata,
2371 );
2372add_local_crate_allocator_objects(cmd, codegen_results, crate_type);
23732374// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2375 // at the point at which they are specified on the command line.
2376 // Must be passed before any (dynamic) libraries to have effect on them.
2377 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2378 // so it will ignore unreferenced ELF sections from relocatable objects.
2379 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2380 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2381 // and move this option back to the top.
2382cmd.add_as_needed();
23832384// Local native libraries of all kinds.
2385add_local_native_libraries(
2386cmd,
2387sess,
2388archive_builder_builder,
2389codegen_results,
2390tmpdir,
2391link_output_kind,
2392 );
23932394// Upstream rust crates and their non-dynamic native libraries.
2395add_upstream_rust_crates(
2396cmd,
2397sess,
2398archive_builder_builder,
2399codegen_results,
2400crate_type,
2401tmpdir,
2402link_output_kind,
2403 );
24042405// Dynamic native libraries from upstream crates.
2406add_upstream_native_libraries(
2407cmd,
2408sess,
2409archive_builder_builder,
2410codegen_results,
2411tmpdir,
2412link_output_kind,
2413 );
24142415// Raw-dylibs from all crates.
2416let raw_dylib_dir = tmpdir.join("raw-dylibs");
2417if sess.target.binary_format == BinaryFormat::Elf {
2418// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2419 // instead we need to pass them via -l. To find the stub, we need to add
2420 // the directory of the stub to the linker search path.
2421 // We make an extra directory for this to avoid polluting the search path.
2422if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2423sess.dcx().emit_fatal(errors::CreateTempDir { error })
2424 }
2425cmd.include_path(&raw_dylib_dir);
2426 }
24272428// Link with the import library generated for any raw-dylib functions.
2429if sess.target.is_like_windows {
2430for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2431 sess,
2432 archive_builder_builder,
2433 codegen_results.crate_info.used_libraries.iter(),
2434 tmpdir,
2435true,
2436 ) {
2437 cmd.add_object(&output_path);
2438 }
2439 } else {
2440for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2441 sess,
2442 codegen_results.crate_info.used_libraries.iter(),
2443&raw_dylib_dir,
2444 ) {
2445// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2446cmd.link_dylib_by_name(&link_path, true, as_needed);
2447 }
2448 }
2449// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2450 // they are used within inlined functions or instantiated generic functions. We do this *after*
2451 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2452 // by the linker.
2453let dependency_linkage = codegen_results2454 .crate_info
2455 .dependency_formats
2456 .get(&crate_type)
2457 .expect("failed to find crate type in dependency format list");
24582459// We sort the libraries below
2460#[allow(rustc::potential_query_instability)]
2461let mut native_libraries_from_nonstatics = codegen_results2462 .crate_info
2463 .native_libraries
2464 .iter()
2465 .filter_map(|(&cnum, libraries)| {
2466if sess.target.is_like_windows {
2467 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2468 } else {
2469Some(libraries)
2470 }
2471 })
2472 .flatten()
2473 .collect::<Vec<_>>();
2474native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
24752476if sess.target.is_like_windows {
2477for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2478 sess,
2479 archive_builder_builder,
2480 native_libraries_from_nonstatics,
2481 tmpdir,
2482false,
2483 ) {
2484 cmd.add_object(&output_path);
2485 }
2486 } else {
2487for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2488 sess,
2489 native_libraries_from_nonstatics,
2490&raw_dylib_dir,
2491 ) {
2492// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2493cmd.link_dylib_by_name(&link_path, true, as_needed);
2494 }
2495 }
24962497// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2498 // command line shorter, reset it to default here before adding more libraries.
2499cmd.reset_per_library_state();
25002501// FIXME: Built-in target specs occasionally use this for linking system libraries,
2502 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2503 // and remove the option.
2504add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
25052506// ------------ Arbitrary order-independent options ------------
25072508 // Add order-independent options determined by rustc from its compiler options,
2509 // target properties and source code.
2510add_order_independent_options(
2511cmd,
2512sess,
2513link_output_kind,
2514self_contained_components,
2515flavor,
2516crate_type,
2517codegen_results,
2518out_filename,
2519tmpdir,
2520 );
25212522// Can be used for arbitrary order-independent options.
2523 // In practice may also be occasionally used for linking native libraries.
2524 // Passed after compiler-generated options to support manual overriding when necessary.
2525add_user_defined_link_args(cmd, sess);
25262527// ------------ Builtin configurable linker scripts ------------
2528 // The user's link args should be able to overwrite symbols in the compiler's
2529 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2530 // to work correctly, the user needs to be able to specify linker arguments like
2531 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2532add_link_script(cmd, sess, tmpdir, crate_type);
25332534// ------------ Object code and libraries, order-dependent ------------
25352536 // Post-link CRT objects.
2537add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
25382539// ------------ Late order-dependent options ------------
25402541 // Doesn't really make sense.
2542 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2543 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2544 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2545add_post_link_args(cmd, sess, flavor);
25462547cmd.take_cmd()
2548}
25492550fn add_order_independent_options(
2551 cmd: &mut dyn Linker,
2552 sess: &Session,
2553 link_output_kind: LinkOutputKind,
2554 self_contained_components: LinkSelfContainedComponents,
2555 flavor: LinkerFlavor,
2556 crate_type: CrateType,
2557 codegen_results: &CodegenResults,
2558 out_filename: &Path,
2559 tmpdir: &Path,
2560) {
2561// Take care of the flavors and CLI options requesting the `lld` linker.
2562add_lld_args(cmd, sess, flavor, self_contained_components);
25632564add_apple_link_args(cmd, sess, flavor);
25652566let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
25672568if sess.target.os == Os::Fuchsia2569 && crate_type == CrateType::Executable2570 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2571 {
2572let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2573cmd.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"));
2574 }
25752576if sess.target.eh_frame_header {
2577cmd.add_eh_frame_header();
2578 }
25792580// Make the binary compatible with data execution prevention schemes.
2581cmd.add_no_exec();
25822583if self_contained_components.is_crt_objects_enabled() {
2584cmd.no_crt_objects();
2585 }
25862587if sess.target.os == Os::Emscripten {
2588cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2589"-fwasm-exceptions"
2590} else if sess.panic_strategy().unwinds() {
2591"-sDISABLE_EXCEPTION_CATCHING=0"
2592} else {
2593"-sDISABLE_EXCEPTION_CATCHING=1"
2594});
2595 }
25962597if flavor == LinkerFlavor::Llbc {
2598cmd.link_args(&[
2599"--target",
2600&versioned_llvm_target(sess),
2601"--target-cpu",
2602&codegen_results.crate_info.target_cpu,
2603 ]);
2604if codegen_results.crate_info.target_features.len() > 0 {
2605cmd.link_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target-feature={0}",
&codegen_results.crate_info.target_features.join(",")))
})format!(
2606"--target-feature={}",
2607&codegen_results.crate_info.target_features.join(",")
2608 ));
2609 }
2610 } else if flavor == LinkerFlavor::Ptx {
2611cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2612 } else if flavor == LinkerFlavor::Bpf {
2613cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2614if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2615 .into_iter()
2616 .find(|feat| !feat.is_empty())
2617 {
2618cmd.link_args(&["--cpu-features", feat]);
2619 }
2620 }
26212622cmd.linker_plugin_lto();
26232624add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
26252626cmd.output_filename(out_filename);
26272628if crate_type == CrateType::Executable2629 && sess.target.is_like_windows
2630 && let Some(s) = &codegen_results.crate_info.windows_subsystem
2631 {
2632cmd.windows_subsystem(*s);
2633 }
26342635// Try to strip as much out of the generated object by removing unused
2636 // sections if possible. See more comments in linker.rs
2637if !sess.link_dead_code() {
2638// If PGO is enabled sometimes gc_sections will remove the profile data section
2639 // as it appears to be unused. This can then cause the PGO profile file to lose
2640 // some functions. If we are generating a profile we shouldn't strip those metadata
2641 // sections to ensure we have all the data for PGO.
2642let keep_metadata =
2643crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2644cmd.gc_sections(keep_metadata);
2645 }
26462647cmd.set_output_kind(link_output_kind, crate_type, out_filename);
26482649add_relro_args(cmd, sess);
26502651// Pass optimization flags down to the linker.
2652cmd.optimize();
26532654// Gather the set of NatVis files, if any, and write them out to a temp directory.
2655let natvis_visualizers = collect_natvis_visualizers(
2656tmpdir,
2657sess,
2658&codegen_results.crate_info.local_crate_name,
2659&codegen_results.crate_info.natvis_debugger_visualizers,
2660 );
26612662// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2663cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
26642665// We want to prevent the compiler from accidentally leaking in any system libraries,
2666 // so by default we tell linkers not to link to any default libraries.
2667if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2668cmd.no_default_libraries();
2669 }
26702671if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2672cmd.pgo_gen();
2673 }
26742675if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2676cmd.control_flow_guard();
2677 }
26782679// OBJECT-FILES-NO, AUDIT-ORDER
2680if sess.opts.unstable_opts.ehcont_guard {
2681cmd.ehcont_guard();
2682 }
26832684add_rpath_args(cmd, sess, codegen_results, out_filename);
2685}
26862687// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2688fn collect_natvis_visualizers(
2689 tmpdir: &Path,
2690 sess: &Session,
2691 crate_name: &Symbol,
2692 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2693) -> Vec<PathBuf> {
2694let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
26952696for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2697let 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));
26982699match fs::write(&visualizer_out_file, &visualizer.src) {
2700Ok(()) => {
2701 visualizer_paths.push(visualizer_out_file);
2702 }
2703Err(error) => {
2704 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2705 path: visualizer_out_file,
2706 error,
2707 });
2708 }
2709 };
2710 }
2711visualizer_paths2712}
27132714fn add_native_libs_from_crate(
2715 cmd: &mut dyn Linker,
2716 sess: &Session,
2717 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2718 codegen_results: &CodegenResults,
2719 tmpdir: &Path,
2720 bundled_libs: &FxIndexSet<Symbol>,
2721 cnum: CrateNum,
2722 link_static: bool,
2723 link_dynamic: bool,
2724 link_output_kind: LinkOutputKind,
2725) {
2726if !sess.opts.unstable_opts.link_native_libraries {
2727// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2728 // external build system already has the native dependencies defined, and it
2729 // will provide them to the linker itself.
2730return;
2731 }
27322733if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2734// If rlib contains native libs as archives, unpack them to tmpdir.
2735let rlib = codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2736archive_builder_builder2737 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2738 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2739 }
27402741let native_libs = match cnum {
2742LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2743_ => &codegen_results.crate_info.native_libraries[&cnum],
2744 };
27452746let mut last = (None, NativeLibKind::Unspecified, false);
2747for lib in native_libs {
2748if !relevant_lib(sess, lib) {
2749continue;
2750 }
27512752// Skip if this library is the same as the last.
2753last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2754continue;
2755 } else {
2756 (Some(lib.name), lib.kind, lib.verbatim)
2757 };
27582759let name = lib.name.as_str();
2760let verbatim = lib.verbatim;
2761match lib.kind {
2762 NativeLibKind::Static { bundle, whole_archive, .. } => {
2763if link_static {
2764let bundle = bundle.unwrap_or(true);
2765let whole_archive = whole_archive == Some(true);
2766if bundle && cnum != LOCAL_CRATE {
2767if let Some(filename) = lib.filename {
2768// If rlib contains native libs as archives, they are unpacked to tmpdir.
2769let path = tmpdir.join(filename.as_str());
2770 cmd.link_staticlib_by_path(&path, whole_archive);
2771 }
2772 } else {
2773 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2774 }
2775 }
2776 }
2777 NativeLibKind::Dylib { as_needed } => {
2778if link_dynamic {
2779 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2780 }
2781 }
2782 NativeLibKind::Unspecified => {
2783// If we are generating a static binary, prefer static library when the
2784 // link kind is unspecified.
2785if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2786if link_static {
2787 cmd.link_staticlib_by_name(name, verbatim, false);
2788 }
2789 } else if link_dynamic {
2790 cmd.link_dylib_by_name(name, verbatim, true);
2791 }
2792 }
2793 NativeLibKind::Framework { as_needed } => {
2794if link_dynamic {
2795 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2796 }
2797 }
2798 NativeLibKind::RawDylib { as_needed: _ } => {
2799// Handled separately in `linker_with_args`.
2800}
2801 NativeLibKind::WasmImportModule => {}
2802 NativeLibKind::LinkArg => {
2803if link_static {
2804if verbatim {
2805 cmd.verbatim_arg(name);
2806 } else {
2807 cmd.link_arg(name);
2808 }
2809 }
2810 }
2811 }
2812 }
2813}
28142815fn add_local_native_libraries(
2816 cmd: &mut dyn Linker,
2817 sess: &Session,
2818 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2819 codegen_results: &CodegenResults,
2820 tmpdir: &Path,
2821 link_output_kind: LinkOutputKind,
2822) {
2823// All static and dynamic native library dependencies are linked to the local crate.
2824let link_static = true;
2825let link_dynamic = true;
2826add_native_libs_from_crate(
2827cmd,
2828sess,
2829archive_builder_builder,
2830codegen_results,
2831tmpdir,
2832&Default::default(),
2833LOCAL_CRATE,
2834link_static,
2835link_dynamic,
2836link_output_kind,
2837 );
2838}
28392840fn add_upstream_rust_crates(
2841 cmd: &mut dyn Linker,
2842 sess: &Session,
2843 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2844 codegen_results: &CodegenResults,
2845 crate_type: CrateType,
2846 tmpdir: &Path,
2847 link_output_kind: LinkOutputKind,
2848) {
2849// All of the heavy lifting has previously been accomplished by the
2850 // dependency_format module of the compiler. This is just crawling the
2851 // output of that module, adding crates as necessary.
2852 //
2853 // Linking to a rlib involves just passing it to the linker (the linker
2854 // will slurp up the object files inside), and linking to a dynamic library
2855 // involves just passing the right -l flag.
2856let data = codegen_results2857 .crate_info
2858 .dependency_formats
2859 .get(&crate_type)
2860 .expect("failed to find crate type in dependency format list");
28612862if sess.target.is_like_aix {
2863// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
2864 // the dependency name when outputting a shared library. Thus, `ld` will
2865 // use the full path to shared libraries as the dependency if passed it
2866 // by default unless `noipath` is passed.
2867 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
2868cmd.link_or_cc_arg("-bnoipath");
2869 }
28702871for &cnum in &codegen_results.crate_info.used_crates {
2872// We may not pass all crates through to the linker. Some crates may appear statically in
2873 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2874 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2875 // Even if they were already included into a dylib
2876 // (e.g. `libstd` when `-C prefer-dynamic` is used).
2877let linkage = data[cnum];
2878let link_static_crate = linkage == Linkage::Static
2879 || linkage == Linkage::IncludedFromDylib
2880 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2881 || codegen_results.crate_info.profiler_runtime == Some(cnum));
28822883let mut bundled_libs = Default::default();
2884match linkage {
2885 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2886if link_static_crate {
2887 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2888 .iter()
2889 .filter_map(|lib| lib.filename)
2890 .collect();
2891 add_static_crate(
2892 cmd,
2893 sess,
2894 archive_builder_builder,
2895 codegen_results,
2896 tmpdir,
2897 cnum,
2898&bundled_libs,
2899 );
2900 }
2901 }
2902 Linkage::Dynamic => {
2903let src = &codegen_results.crate_info.used_crate_source[&cnum];
2904 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
2905 }
2906 }
29072908// Static libraries are linked for a subset of linked upstream crates.
2909 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2910 // because the rlib is just an archive.
2911 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
2912 // the native library because it is already linked into the dylib, and even if
2913 // inline/const/generic functions from the dylib can refer to symbols from the native
2914 // library, those symbols should be exported and available from the dylib anyway.
2915 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
2916let link_static = link_static_crate;
2917// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
2918let link_dynamic = false;
2919 add_native_libs_from_crate(
2920 cmd,
2921 sess,
2922 archive_builder_builder,
2923 codegen_results,
2924 tmpdir,
2925&bundled_libs,
2926 cnum,
2927 link_static,
2928 link_dynamic,
2929 link_output_kind,
2930 );
2931 }
2932}
29332934fn add_upstream_native_libraries(
2935 cmd: &mut dyn Linker,
2936 sess: &Session,
2937 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2938 codegen_results: &CodegenResults,
2939 tmpdir: &Path,
2940 link_output_kind: LinkOutputKind,
2941) {
2942for &cnum in &codegen_results.crate_info.used_crates {
2943// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
2944 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
2945 // are linked together with their respective upstream crates, and in their originally
2946 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
2947 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
2948let link_static = false;
2949// Dynamic libraries are linked for all linked upstream crates.
2950 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2951 // because the rlib is just an archive.
2952 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
2953 // the native library too because inline/const/generic functions from the dylib can refer
2954 // to symbols from the native library, so the native library providing those symbols should
2955 // be available when linking our final binary.
2956let link_dynamic = true;
2957 add_native_libs_from_crate(
2958 cmd,
2959 sess,
2960 archive_builder_builder,
2961 codegen_results,
2962 tmpdir,
2963&Default::default(),
2964 cnum,
2965 link_static,
2966 link_dynamic,
2967 link_output_kind,
2968 );
2969 }
2970}
29712972// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
2973// to be relative to the sysroot directory, which may be a relative path specified by the user.
2974//
2975// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
2976// linker command line can be non-deterministic due to the paths including the current working
2977// directory. The linker command line needs to be deterministic since it appears inside the PDB
2978// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
2979//
2980// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
2981fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2982let sysroot_lib_path = &sess.target_tlib_path.dir;
2983let canonical_sysroot_lib_path =
2984 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
29852986let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2987if canonical_lib_dir == canonical_sysroot_lib_path {
2988// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
2989sysroot_lib_path.clone()
2990 } else {
2991fix_windows_verbatim_for_gcc(lib_dir)
2992 }
2993}
29942995fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2996if let Some(dir) = path.parent() {
2997let file_name = path.file_name().expect("library path has no file name component");
2998rehome_sysroot_lib_dir(sess, dir).join(file_name)
2999 } else {
3000fix_windows_verbatim_for_gcc(path)
3001 }
3002}
30033004// Adds the static "rlib" versions of all crates to the command line.
3005// There's a bit of magic which happens here specifically related to LTO,
3006// namely that we remove upstream object files.
3007//
3008// When performing LTO, almost(*) all of the bytecode from the upstream
3009// libraries has already been included in our object file output. As a
3010// result we need to remove the object files in the upstream libraries so
3011// the linker doesn't try to include them twice (or whine about duplicate
3012// symbols). We must continue to include the rest of the rlib, however, as
3013// it may contain static native libraries which must be linked in.
3014//
3015// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3016// their bytecode wasn't included. The object files in those libraries must
3017// still be passed to the linker.
3018//
3019// Note, however, that if we're not doing LTO we can just pass the rlib
3020// blindly to the linker (fast) because it's fine if it's not actually
3021// included as we're at the end of the dependency chain.
3022fn add_static_crate(
3023 cmd: &mut dyn Linker,
3024 sess: &Session,
3025 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3026 codegen_results: &CodegenResults,
3027 tmpdir: &Path,
3028 cnum: CrateNum,
3029 bundled_lib_file_names: &FxIndexSet<Symbol>,
3030) {
3031let src = &codegen_results.crate_info.used_crate_source[&cnum];
3032let cratepath = src.rlib.as_ref().unwrap();
30333034let mut link_upstream =
3035 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
30363037if !are_upstream_rust_objects_already_included(sess)
3038 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
3039 {
3040link_upstream(cratepath);
3041return;
3042 }
30433044let dst = tmpdir.join(cratepath.file_name().unwrap());
3045let name = cratepath.file_name().unwrap().to_str().unwrap();
3046let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3047let bundled_lib_file_names = bundled_lib_file_names.clone();
30483049sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3050let canonical_name = name.replace('-', "_");
3051let upstream_rust_objects_already_included =
3052are_upstream_rust_objects_already_included(sess);
3053let is_builtins =
3054sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
30553056let mut archive = archive_builder_builder.new_archive_builder(sess);
3057if let Err(error) = archive.add_archive(
3058cratepath,
3059Box::new(move |f| {
3060if f == METADATA_FILENAME {
3061return true;
3062 }
30633064let canonical = f.replace('-', "_");
30653066let is_rust_object =
3067canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
30683069// If we're performing LTO and this is a rust-generated object
3070 // file, then we don't need the object file as it's part of the
3071 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3072 // though, so we let that object file slide.
3073if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3074return true;
3075 }
30763077// We skip native libraries because:
3078 // 1. This native libraries won't be used from the generated rlib,
3079 // so we can throw them away to avoid the copying work.
3080 // 2. We can't allow it to be a single remaining entry in archive
3081 // as some linkers may complain on that.
3082if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3083return true;
3084 }
30853086false
3087}),
3088 ) {
3089sess.dcx()
3090 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3091 }
3092if archive.build(&dst) {
3093link_upstream(&dst);
3094 }
3095 });
3096}
30973098// Same thing as above, but for dynamic crates instead of static crates.
3099fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3100cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3101}
31023103fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3104match lib.cfg {
3105Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3106None => true,
3107 }
3108}
31093110pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3111match sess.lto() {
3112 config::Lto::Fat => true,
3113 config::Lto::Thin => {
3114// If we defer LTO to the linker, we haven't run LTO ourselves, so
3115 // any upstream object files have not been copied yet.
3116!sess.opts.cg.linker_plugin_lto.enabled()
3117 }
3118 config::Lto::No | config::Lto::ThinLocal => false,
3119 }
3120}
31213122/// We need to communicate five things to the linker on Apple/Darwin targets:
3123/// - The architecture.
3124/// - The operating system (and that it's an Apple platform).
3125/// - The environment.
3126/// - The deployment target.
3127/// - The SDK version.
3128fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3129if !sess.target.is_like_darwin {
3130return;
3131 }
3132let LinkerFlavor::Darwin(cc, _) = flavorelse {
3133return;
3134 };
31353136// `sess.target.arch` (`target_arch`) is not detailed enough.
3137let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3138let target_os = &sess.target.os;
3139let target_env = &sess.target.env;
31403141// The architecture name to forward to the linker.
3142 //
3143 // Supported architecture names can be found in the source:
3144 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3145 //
3146 // Intentionally verbose to ensure that the list always matches correctly
3147 // with the list in the source above.
3148let ld64_arch = match llvm_arch {
3149"armv7k" => "armv7k",
3150"armv7s" => "armv7s",
3151"arm64" => "arm64",
3152"arm64e" => "arm64e",
3153"arm64_32" => "arm64_32",
3154// ld64 doesn't understand i686, so fall back to i386 instead.
3155 //
3156 // Same story when linking with cc, since that ends up invoking ld64.
3157"i386" | "i686" => "i386",
3158"x86_64" => "x86_64",
3159"x86_64h" => "x86_64h",
3160_ => ::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),
3161 };
31623163if cc == Cc::No {
3164// From the man page for ld64 (`man ld`):
3165 // > The linker accepts universal (multiple-architecture) input files,
3166 // > but always creates a "thin" (single-architecture), standard
3167 // > Mach-O output file. The architecture for the output file is
3168 // > specified using the -arch option.
3169 //
3170 // The linker has heuristics to determine the desired architecture,
3171 // but to be safe, and to avoid a warning, we set the architecture
3172 // explicitly.
3173cmd.link_args(&["-arch", ld64_arch]);
31743175// Man page says that ld64 supports the following platform names:
3176 // > - macos
3177 // > - ios
3178 // > - tvos
3179 // > - watchos
3180 // > - bridgeos
3181 // > - visionos
3182 // > - xros
3183 // > - mac-catalyst
3184 // > - ios-simulator
3185 // > - tvos-simulator
3186 // > - watchos-simulator
3187 // > - visionos-simulator
3188 // > - xros-simulator
3189 // > - driverkit
3190let platform_name = match (target_os, target_env) {
3191 (os, Env::Unspecified) => os.desc(),
3192 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3193 (Os::IOs, Env::Sim) => "ios-simulator",
3194 (Os::TvOs, Env::Sim) => "tvos-simulator",
3195 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3196 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3197_ => ::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}"),
3198 };
31993200let min_version = sess.apple_deployment_target().fmt_full().to_string();
32013202// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3203 // - By dyld to give extra warnings and errors, see e.g.:
3204 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3205 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3206 // - By system frameworks to change certain behaviour. For example, the default value of
3207 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3208 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3209 //
3210 // We do not currently know the actual SDK version though, so we have a few options:
3211 // 1. Use the minimum version supported by rustc.
3212 // 2. Use the same as the deployment target.
3213 // 3. Use an arbitrary recent version.
3214 // 4. Omit the version.
3215 //
3216 // The first option is too low / too conservative, and means that users will not get the
3217 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3218 //
3219 // The second option is similarly conservative, and also wrong since if the user specified a
3220 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3221 // make invalid assumptions about the capabilities of the binary.
3222 //
3223 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3224 // version, and is also wrong for similar reasons as above.
3225 //
3226 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3227 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3228 // it as 0.0, which is again too low/conservative.
3229 //
3230 // Currently, we lie about the SDK version, and choose the second option.
3231 //
3232 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3233 // <https://github.com/rust-lang/rust/issues/129432>
3234let sdk_version = &*min_version;
32353236// From the man page for ld64 (`man ld`):
3237 // > This is set to indicate the platform, oldest supported version of
3238 // > that platform that output is to be used on, and the SDK that the
3239 // > output was built against.
3240 //
3241 // Like with `-arch`, the linker can figure out the platform versions
3242 // itself from the binaries being linked, but to be safe, we specify
3243 // the desired versions here explicitly.
3244cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3245 } else {
3246// cc == Cc::Yes
3247 //
3248 // We'd _like_ to use `-target` everywhere, since that can uniquely
3249 // communicate all the required details except for the SDK version
3250 // (which is read by Clang itself from the SDKROOT), but that doesn't
3251 // work on GCC, and since we don't know whether the `cc` compiler is
3252 // Clang, GCC, or something else, we fall back to other options that
3253 // also work on GCC when compiling for macOS.
3254 //
3255 // Targets other than macOS are ill-supported by GCC (it doesn't even
3256 // support e.g. `-miphoneos-version-min`), so in those cases we can
3257 // fairly safely use `-target`. See also the following, where it is
3258 // made explicit that the recommendation by LLVM developers is to use
3259 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3260if *target_os == Os::MacOs {
3261// `-arch` communicates the architecture.
3262 //
3263 // CC forwards the `-arch` to the linker, so we use the same value
3264 // here intentionally.
3265cmd.cc_args(&["-arch", ld64_arch]);
32663267// The presence of `-mmacosx-version-min` makes CC default to
3268 // macOS, and it sets the deployment target.
3269let version = sess.apple_deployment_target().fmt_full();
3270// Intentionally pass this as a single argument, Clang doesn't
3271 // seem to like it otherwise.
3272cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
32733274// macOS has no environment, so with these two, we've told CC the
3275 // four desired parameters.
3276 //
3277 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3278} else {
3279cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3280 }
3281 }
3282}
32833284fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3285if !sess.target.is_like_darwin {
3286return None;
3287 }
3288let LinkerFlavor::Darwin(cc, _) = flavorelse {
3289return None;
3290 };
32913292// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3293 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3294 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3295 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3296 // instead we invoke `xcrun` manually.
3297 //
3298 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3299 // cause the trampoline binary to skip looking up the SDK itself).
3300let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
33013302if cc == Cc::Yes {
3303// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3304 // - The `--sysroot` flag.
3305 // - The `-isysroot` flag.
3306 // - The `SDKROOT` environment variable.
3307 //
3308 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3309 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3310 // only applies to include header files, but on Apple targets it also applies to libraries
3311 // and frameworks.
3312 //
3313 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3314 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3315 // primarily because that is the same interface that is used when invoking the tool under
3316 // `xcrun -sdk macosx $tool`.
3317 //
3318 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3319 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3320 //
3321 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3322 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3323 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3324 //
3325 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3326 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3327 // ignoring the value we set here, and instead use their built-in sysroot).
3328cmd.cmd().env("SDKROOT", &sdkroot);
3329 } else {
3330// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3331 // read by the linker, so it's really the only option.
3332 //
3333 // This is also what Clang does.
3334cmd.link_arg("-syslibroot");
3335cmd.link_arg(&sdkroot);
3336 }
33373338Some(sdkroot)
3339}
33403341fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3342if let Ok(sdkroot) = env::var("SDKROOT") {
3343let p = PathBuf::from(&sdkroot);
33443345// Ignore invalid SDKs, similar to what clang does:
3346 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3347 //
3348 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3349 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3350 // clearly set for the wrong platform.
3351 //
3352 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3353match &*apple::sdk_name(&sess.target).to_lowercase() {
3354"appletvos"
3355if sdkroot.contains("TVSimulator.platform")
3356 || sdkroot.contains("MacOSX.platform") => {}
3357"appletvsimulator"
3358if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3359"iphoneos"
3360if sdkroot.contains("iPhoneSimulator.platform")
3361 || sdkroot.contains("MacOSX.platform") => {}
3362"iphonesimulator"
3363if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3364 }
3365"macosx"
3366if sdkroot.contains("iPhoneOS.platform")
3367 || sdkroot.contains("iPhoneSimulator.platform")
3368 || sdkroot.contains("AppleTVOS.platform")
3369 || sdkroot.contains("AppleTVSimulator.platform")
3370 || sdkroot.contains("WatchOS.platform")
3371 || sdkroot.contains("WatchSimulator.platform")
3372 || sdkroot.contains("XROS.platform")
3373 || sdkroot.contains("XRSimulator.platform") => {}
3374"watchos"
3375if sdkroot.contains("WatchSimulator.platform")
3376 || sdkroot.contains("MacOSX.platform") => {}
3377"watchsimulator"
3378if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3379"xros"
3380if sdkroot.contains("XRSimulator.platform")
3381 || sdkroot.contains("MacOSX.platform") => {}
3382"xrsimulator"
3383if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3384// Ignore `SDKROOT` if it's not a valid path.
3385_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3386_ => return Some(p),
3387 }
3388 }
33893390 apple::get_sdk_root(sess)
3391}
33923393/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3394/// invoke it:
3395/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3396/// - or any `lld` available to `cc`.
3397fn add_lld_args(
3398 cmd: &mut dyn Linker,
3399 sess: &Session,
3400 flavor: LinkerFlavor,
3401 self_contained_components: LinkSelfContainedComponents,
3402) {
3403{
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:3403",
"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(3403u32),
::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!(
3404"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3405 flavor, self_contained_components,
3406 );
34073408// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3409 // we don't need to do anything.
3410if !(flavor.uses_cc() && flavor.uses_lld()) {
3411return;
3412 }
34133414// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3415 // directories to the tool's search path, depending on a mix between what users can specify on
3416 // the CLI, and what the target spec enables (as it can't disable components):
3417 // - if the self-contained linker is enabled on the CLI or by the target spec,
3418 // - and if the self-contained linker is not disabled on the CLI.
3419let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3420let self_contained_target = self_contained_components.is_linker_enabled();
34213422let self_contained_linker = self_contained_cli || self_contained_target;
3423if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3424let mut linker_path_exists = false;
3425for path in sess.get_tools_search_paths(false) {
3426let linker_path = path.join("gcc-ld");
3427 linker_path_exists |= linker_path.exists();
3428 cmd.cc_arg({
3429let mut arg = OsString::from("-B");
3430 arg.push(linker_path);
3431 arg
3432 });
3433 }
3434if !linker_path_exists {
3435// As a sanity check, we emit an error if none of these paths exist: we want
3436 // self-contained linking and have no linker.
3437sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3438 }
3439 }
34403441// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3442 // `lld` as the linker.
3443 //
3444 // Note that wasm targets skip this step since the only option there anyway
3445 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3446 // this, `wasm-component-ld`, which is overridden if this option is passed.
3447if !sess.target.is_like_wasm {
3448cmd.cc_arg("-fuse-ld=lld");
3449 }
34503451if !flavor.is_gnu() {
3452// Tell clang to use a non-default LLD flavor.
3453 // Gcc doesn't understand the target option, but we currently assume
3454 // that gcc is not used for Apple and Wasm targets (#97402).
3455 //
3456 // Note that we don't want to do that by default on macOS: e.g. passing a
3457 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3458 // shown in issue #101653 and the discussion in PR #101792.
3459 //
3460 // It could be required in some cases of cross-compiling with
3461 // LLD, but this is generally unspecified, and we don't know
3462 // which specific versions of clang, macOS SDK, host and target OS
3463 // combinations impact us here.
3464 //
3465 // So we do a simple first-approximation until we know more of what the
3466 // Apple targets require (and which would be handled prior to hitting this
3467 // LLD codepath anyway), but the expectation is that until then
3468 // this should be manually passed if needed. We specify the target when
3469 // targeting a different linker flavor on macOS, and that's also always
3470 // the case when targeting WASM.
3471if sess.target.linker_flavor != sess.host.linker_flavor {
3472cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3473 }
3474 }
3475}
34763477// gold has been deprecated with binutils 2.44
3478// and is known to behave incorrectly around Rust programs.
3479// There have been reports of being unable to bootstrap with gold:
3480// https://github.com/rust-lang/rust/issues/139425
3481// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3482// emitted with `#[used(linker)]`.
3483fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3484use object::read::elf::{FileHeader, SectionHeader};
3485use object::read::{ReadCache, ReadRef, Result};
3486use object::{Endianness, elf};
34873488fn elf_has_gold_version_note<'a>(
3489 elf: &impl FileHeader,
3490 data: impl ReadRef<'a>,
3491 ) -> Result<bool> {
3492let endian = elf.endian()?;
34933494let section =
3495elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3496if let Some((_, section)) = section3497 && let Some(mut notes) = section.notes(endian, data)?
3498{
3499return Ok(notes.any(|note| {
3500note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3501 }));
3502 }
35033504Ok(false)
3505 }
35063507let data = ReadCache::new(BufReader::new(File::open(path)?));
35083509let was_linked_with_gold = if sess.target.pointer_width == 64 {
3510let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3511elf_has_gold_version_note(elf, &data)?
3512} else if sess.target.pointer_width == 32 {
3513let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3514elf_has_gold_version_note(elf, &data)?
3515} else {
3516return Ok(());
3517 };
35183519if was_linked_with_gold {
3520let mut warn =
3521sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3522warn.help("consider using LLD or ld from GNU binutils instead");
3523warn.emit();
3524 }
3525Ok(())
3526}