1mod raw_dylib;
23use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
1112use find_msvc_tools;
13use itertools::Itertools;
14use object::{Object, ObjectSection, ObjectSymbol};
15use regex::Regex;
16use rustc_arena::TypedArena;
17use rustc_attr_parsing::eval_config_entry;
18use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::DiagCtxtHandle;
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_macros::Diagnostic;
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::diag_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::{
63CompiledModule, CompiledModules, 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 compiled_modules: CompiledModules,
80 crate_info: CrateInfo,
81 metadata: EncodedMetadata,
82 outputs: &OutputFilenames,
83 codegen_backend: &'static str,
84) {
85let _timer = sess.timer("link_binary");
86let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
87let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
88for &crate_type in &crate_info.crate_types {
89// Ignore executable crates if we have -Z no-codegen, as they will error.
90if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
91 && !output_metadata
92 && crate_type == CrateType::Executable
93 {
94continue;
95 }
9697if invalid_output_for_target(sess, crate_type) {
98::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);
99 }
100101 sess.time("link_binary_check_files_are_writeable", || {
102for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
103 check_file_is_writeable(obj, sess);
104 }
105 });
106107if outputs.outputs.should_link() {
108let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
109let tmpdir = TempDirBuilder::new()
110 .prefix("rustc")
111 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
112 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
113let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
114115let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
116let out_filename = output.file_for_writing(
117 outputs,
118 OutputType::Exe,
119&crate_name,
120 sess.invocation_temp.as_deref(),
121 );
122match crate_type {
123 CrateType::Rlib => {
124let _timer = sess.timer("link_rlib");
125{
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:125",
"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(125u32),
::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);
126 link_rlib(
127 sess,
128 archive_builder_builder,
129&compiled_modules,
130&crate_info,
131&metadata,
132 RlibFlavor::Normal,
133&path,
134 )
135 .build(&out_filename);
136 }
137 CrateType::StaticLib => {
138 link_staticlib(
139 sess,
140 archive_builder_builder,
141&compiled_modules,
142&crate_info,
143&metadata,
144&out_filename,
145&path,
146 );
147 }
148_ => {
149 link_natively(
150 sess,
151 archive_builder_builder,
152 crate_type,
153&out_filename,
154&compiled_modules,
155&crate_info,
156&metadata,
157 path.as_ref(),
158 codegen_backend,
159 );
160 }
161 }
162if sess.opts.json_artifact_notifications {
163 sess.dcx().emit_artifact_notification(&out_filename, "link");
164 }
165166if sess.prof.enabled()
167 && let Some(artifact_name) = out_filename.file_name()
168 {
169// Record size for self-profiling
170let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
171172 sess.prof.artifact_size(
173"linked_artifact",
174 artifact_name.to_string_lossy(),
175 file_size,
176 );
177 }
178179if sess.target.binary_format == BinaryFormat::Elf {
180if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
181{
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:181",
"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(181u32),
::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");
182 }
183 }
184185if output.is_stdout() {
186if output.is_tty() {
187 sess.dcx().emit_err(errors::BinaryOutputToTty {
188 shorthand: OutputType::Exe.shorthand(),
189 });
190 } else if let Err(e) = copy_to_stdout(&out_filename) {
191 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
192 }
193 tempfiles_for_stdout_output.push(out_filename);
194 }
195 }
196 }
197198// Remove the temporary object file and metadata if we aren't saving temps.
199sess.time("link_binary_remove_temps", || {
200// If the user requests that temporaries are saved, don't delete any.
201if sess.opts.cg.save_temps {
202return;
203 }
204205let maybe_remove_temps_from_module =
206 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
207if !preserve_objects && let Some(ref obj) = module.object {
208ensure_removed(sess.dcx(), obj);
209 }
210211if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
212ensure_removed(sess.dcx(), dwo_obj);
213 }
214 };
215216let remove_temps_from_module =
217 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
218219// Otherwise, always remove the allocator module temporaries.
220if let Some(ref allocator_module) = compiled_modules.allocator_module {
221remove_temps_from_module(allocator_module);
222 }
223224// Remove the temporary files if output goes to stdout
225for temp in tempfiles_for_stdout_output {
226 ensure_removed(sess.dcx(), &temp);
227 }
228229// If no requested outputs require linking, then the object temporaries should
230 // be kept.
231if !sess.opts.output_types.should_link() {
232return;
233 }
234235// Potentially keep objects for their debuginfo.
236let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
237{
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:237",
"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(237u32),
::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);
238239for module in &compiled_modules.modules {
240 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
241 }
242 });
243}
244245// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
246// crate types must use the same dependency formats.
247pub fn each_linked_rlib(
248 info: &CrateInfo,
249 crate_type: Option<CrateType>,
250 f: &mut dyn FnMut(CrateNum, &Path),
251) -> Result<(), errors::LinkRlibError> {
252let fmts = if let Some(crate_type) = crate_type {
253let Some(fmts) = info.dependency_formats.get(&crate_type) else {
254return Err(errors::LinkRlibError::MissingFormat);
255 };
256257fmts258 } else {
259let mut dep_formats = info.dependency_formats.iter();
260let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
261if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
262return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
263 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
264 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
265 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
266 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
267 });
268 }
269list1270 };
271272let used_dep_crates = info.used_crates.iter();
273for &cnum in used_dep_crates {
274match fmts.get(cnum) {
275Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
276Some(_) => {}
277None => return Err(errors::LinkRlibError::MissingFormat),
278 }
279let crate_name = info.crate_name[&cnum];
280let used_crate_source = &info.used_crate_source[&cnum];
281if let Some(path) = &used_crate_source.rlib {
282 f(cnum, path);
283 } else if used_crate_source.rmeta.is_some() {
284return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
285 } else {
286return Err(errors::LinkRlibError::NotFound { crate_name });
287 }
288 }
289Ok(())
290}
291292/// Create an 'rlib'.
293///
294/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
295/// The rlib primarily contains the object file of the crate, but it also some of the object files
296/// from native libraries.
297fn link_rlib<'a>(
298 sess: &'a Session,
299 archive_builder_builder: &dyn ArchiveBuilderBuilder,
300 compiled_modules: &CompiledModules,
301 crate_info: &CrateInfo,
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 &compiled_modules.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 = compiled_modules.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 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 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 compiled_modules: &CompiledModules,
461 crate_info: &CrateInfo,
462 metadata: &EncodedMetadata,
463 out_filename: &Path,
464 tempdir: &MaybeTempDir,
465) {
466{
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:466",
"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(466u32),
::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);
467let mut ab = link_rlib(
468sess,
469archive_builder_builder,
470compiled_modules,
471crate_info,
472metadata,
473 RlibFlavor::StaticlibBase,
474tempdir,
475 );
476let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
477478let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
479let lto = are_upstream_rust_objects_already_included(sess)
480 && !ignored_for_lto(sess, crate_info, cnum);
481482let native_libs = crate_info.native_libraries[&cnum].iter();
483let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
484let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
485486let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
487ab.add_archive(
488path,
489Box::new(move |fname: &str| {
490// Ignore metadata files, no matter the name.
491if fname == METADATA_FILENAME {
492return true;
493 }
494495// Don't include Rust objects if LTO is enabled
496if lto && looks_like_rust_object_file(fname) {
497return true;
498 }
499500// Skip objects for bundled libs.
501if bundled_libs.contains(&Symbol::intern(fname)) {
502return true;
503 }
504505false
506}),
507 )
508 .unwrap();
509510archive_builder_builder511 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
512 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
513514for filename in relevant_libs.iter() {
515let joined = tempdir.as_ref().join(filename.as_str());
516let path = joined.as_path();
517 ab.add_archive(path, Box::new(|_| false)).unwrap();
518 }
519520all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
521 });
522if let Err(e) = res {
523sess.dcx().emit_fatal(e);
524 }
525526ab.build(out_filename);
527528let crates = crate_info.used_crates.iter();
529530let fmts = crate_info531 .dependency_formats
532 .get(&CrateType::StaticLib)
533 .expect("no dependency formats for staticlib");
534535let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
536for &cnum in crates {
537let Some(Linkage::Dynamic) = fmts.get(cnum) else {
538continue;
539 };
540let crate_name = crate_info.crate_name[&cnum];
541let used_crate_source = &crate_info.used_crate_source[&cnum];
542if let Some(path) = &used_crate_source.dylib {
543 all_rust_dylibs.push(&**path);
544 } else if used_crate_source.rmeta.is_some() {
545 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
546 } else {
547 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
548 }
549 }
550551all_native_libs.extend_from_slice(&crate_info.used_libraries);
552553for print in &sess.opts.prints {
554if print.kind == PrintKind::NativeStaticLibs {
555 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
556 }
557 }
558}
559560/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
561/// DWARF package.
562fn link_dwarf_object(
563 sess: &Session,
564 compiled_modules: &CompiledModules,
565 crate_info: &CrateInfo,
566 executable_out_filename: &Path,
567) {
568let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
569dwp_out_filename.push(".dwp");
570{
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:570",
"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(570u32),
::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);
571572#[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)]
573struct ThorinSession<Relocations> {
574 arena_data: TypedArena<Vec<u8>>,
575 arena_mmap: TypedArena<Mmap>,
576 arena_relocations: TypedArena<Relocations>,
577 }
578579impl<Relocations> ThorinSession<Relocations> {
580fn alloc_mmap(&self, data: Mmap) -> &Mmap {
581&*self.arena_mmap.alloc(data)
582 }
583 }
584585impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
586fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
587&*self.arena_data.alloc(data)
588 }
589590fn alloc_relocation(&self, data: Relocations) -> &Relocations {
591&*self.arena_relocations.alloc(data)
592 }
593594fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
595let file = File::open(&path)?;
596let mmap = (unsafe { Mmap::map(file) })?;
597Ok(self.alloc_mmap(mmap))
598 }
599 }
600601match sess.time("run_thorin", || -> Result<(), thorin::Error> {
602let thorin_sess = ThorinSession::default();
603let mut package = thorin::DwarfPackage::new(&thorin_sess);
604605// Input objs contain .o/.dwo files from the current crate.
606match sess.opts.unstable_opts.split_dwarf_kind {
607 SplitDwarfKind::Single => {
608for input_obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
609 package.add_input_object(input_obj)?;
610 }
611 }
612 SplitDwarfKind::Split => {
613for input_obj in
614compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
615 {
616 package.add_input_object(input_obj)?;
617 }
618 }
619 }
620621// Input rlibs contain .o/.dwo files from dependencies.
622let input_rlibs = crate_info623 .used_crate_source
624 .items()
625 .filter_map(|(_, csource)| csource.rlib.as_ref())
626 .into_sorted_stable_ord();
627628for input_rlib in input_rlibs {
629{
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:629",
"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(629u32),
::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);
630 package.add_input_object(input_rlib)?;
631 }
632633// Failing to read the referenced objects is expected for dependencies where the path in the
634 // executable will have been cleaned by Cargo, but the referenced objects will be contained
635 // within rlibs provided as inputs.
636 //
637 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
638 // found, but are provided explicitly above.
639 //
640 // Adding an executable is primarily done to make `thorin` check that all the referenced
641 // dwarf objects are found in the end.
642package.add_executable(
643executable_out_filename,
644 thorin::MissingReferencedObjectBehaviour::Skip,
645 )?;
646647let output_stream = BufWriter::new(
648OpenOptions::new()
649 .read(true)
650 .write(true)
651 .create(true)
652 .truncate(true)
653 .open(dwp_out_filename)?,
654 );
655let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
656package.finish()?.emit(&mut output_stream)?;
657output_stream.result()?;
658output_stream.into_inner().flush()?;
659660Ok(())
661 }) {
662Ok(()) => {}
663Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
664 }
665}
666667#[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for LinkerOutput
where G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
LinkerOutput { inner: __binding_0 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$inner}")));
;
diag.arg("inner", __binding_0);
diag
}
}
}
}
};Diagnostic)]
668#[diag("{$inner}")]
669/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
670/// end up with inconsistent languages within the same diagnostic.
671struct LinkerOutput {
672 inner: String,
673}
674675/// Create a dynamic library or executable.
676///
677/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
678/// files as well.
679fn link_natively(
680 sess: &Session,
681 archive_builder_builder: &dyn ArchiveBuilderBuilder,
682 crate_type: CrateType,
683 out_filename: &Path,
684 compiled_modules: &CompiledModules,
685 crate_info: &CrateInfo,
686 metadata: &EncodedMetadata,
687 tmpdir: &Path,
688 codegen_backend: &'static str,
689) {
690{
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:690",
"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(690u32),
::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);
691let (linker_path, flavor) = linker_and_flavor(sess);
692let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
693694// On AIX, we ship all libraries as .a big_af archive
695 // the expected format is lib<name>.a(libname.so) for the actual
696 // dynamic library. So we link to a temporary .so file to be archived
697 // at the final out_filename location
698let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
699let archive_member =
700should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
701let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
702703let mut cmd = linker_with_args(
704&linker_path,
705flavor,
706sess,
707archive_builder_builder,
708crate_type,
709tmpdir,
710temp_filename,
711compiled_modules,
712crate_info,
713metadata,
714self_contained_components,
715codegen_backend,
716 );
717718 linker::disable_localization(&mut cmd);
719720for (k, v) in sess.target.link_env.as_ref() {
721 cmd.env(k.as_ref(), v.as_ref());
722 }
723for k in sess.target.link_env_remove.as_ref() {
724 cmd.env_remove(k.as_ref());
725 }
726727for print in &sess.opts.prints {
728if print.kind == PrintKind::LinkArgs {
729let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
730 print.out.overwrite(&content, sess);
731 }
732 }
733734// May have not found libraries in the right formats.
735sess.dcx().abort_if_errors();
736737// Invoke the system linker
738{
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:738",
"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(738u32),
::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:?}");
739let unknown_arg_regex =
740Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
741let mut prog;
742loop {
743prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
744let Ok(ref output) = progelse {
745break;
746 };
747if output.status.success() {
748break;
749 }
750let mut out = output.stderr.clone();
751out.extend(&output.stdout);
752let out = String::from_utf8_lossy(&out);
753754// Check to see if the link failed with an error message that indicates it
755 // doesn't recognize the -no-pie option. If so, re-perform the link step
756 // without it. This is safe because if the linker doesn't support -no-pie
757 // then it should not default to linking executables as pie. Different
758 // versions of gcc seem to use different quotes in the error message so
759 // don't check for them.
760if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))761 && unknown_arg_regex.is_match(&out)
762 && out.contains("-no-pie")
763 && cmd.get_args().iter().any(|e| e == "-no-pie")
764 {
765{
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:765",
"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(765u32),
::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);
766{
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:766",
"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(766u32),
::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.");
767for arg in cmd.take_args() {
768if arg != "-no-pie" {
769 cmd.arg(arg);
770 }
771 }
772{
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:772",
"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(772u32),
::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:?}");
773continue;
774 }
775776// Check if linking failed with an error message that indicates the driver didn't recognize
777 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
778 // to spawn multiple instances on the happy path to do version checking, and ensures things
779 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
780 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
781if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))782 && unknown_arg_regex.is_match(&out)
783 && out.contains("-fuse-ld=lld")
784 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
785 {
786{
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:786",
"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(786u32),
::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);
787{
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:787",
"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(787u32),
::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.");
788for arg in cmd.take_args() {
789if arg.to_string_lossy() != "-fuse-ld=lld" {
790 cmd.arg(arg);
791 }
792 }
793{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:793",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(793u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
794continue;
795 }
796797// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
798 // Fallback from '-static-pie' to '-static' in that case.
799if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))800 && unknown_arg_regex.is_match(&out)
801 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
802 && cmd.get_args().iter().any(|e| e == "-static-pie")
803 {
804{
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:804",
"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(804u32),
::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);
805{
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:805",
"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(805u32),
::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!(
806"Linker does not support -static-pie command line option. Retrying with -static instead."
807);
808// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
809let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
810let opts = &sess.target;
811let pre_objects = if self_contained_crt_objects {
812&opts.pre_link_objects_self_contained
813 } else {
814&opts.pre_link_objects
815 };
816let post_objects = if self_contained_crt_objects {
817&opts.post_link_objects_self_contained
818 } else {
819&opts.post_link_objects
820 };
821let get_objects = |objects: &CrtObjects, kind| {
822objects823 .get(&kind)
824 .iter()
825 .copied()
826 .flatten()
827 .map(|obj| {
828get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
829 })
830 .collect::<Vec<_>>()
831 };
832let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
833let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
834let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
835let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
836// Assume that we know insertion positions for the replacement arguments from replaced
837 // arguments, which is true for all supported targets.
838if !(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());
839if !(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());
840for arg in cmd.take_args() {
841if arg == "-static-pie" {
842// Replace the output kind.
843cmd.arg("-static");
844 } else if pre_objects_static_pie.contains(&arg) {
845// Replace the pre-link objects (replace the first and remove the rest).
846cmd.args(mem::take(&mut pre_objects_static));
847 } else if post_objects_static_pie.contains(&arg) {
848// Replace the post-link objects (replace the first and remove the rest).
849cmd.args(mem::take(&mut post_objects_static));
850 } else {
851 cmd.arg(arg);
852 }
853 }
854{
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:854",
"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(854u32),
::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:?}");
855continue;
856 }
857858break;
859 }
860861match prog {
862Ok(prog) => {
863let is_msvc_link_exe = sess.target.is_like_msvc
864 && flavor == LinkerFlavor::Msvc(Lld::No)
865// Match exactly "link.exe"
866&& linker_path.to_str() == Some("link.exe");
867868if !prog.status.success() {
869let mut output = prog.stderr.clone();
870output.extend_from_slice(&prog.stdout);
871let escaped_output = escape_linker_output(&output, flavor);
872let err = errors::LinkingFailed {
873 linker_path: &linker_path,
874 exit_status: prog.status,
875 command: cmd,
876escaped_output,
877 verbose: sess.opts.verbose,
878 sysroot_dir: sess.opts.sysroot.path().to_owned(),
879 };
880sess.dcx().emit_err(err);
881// If MSVC's `link.exe` was expected but the return code
882 // is not a Microsoft LNK error then suggest a way to fix or
883 // install the Visual Studio build tools.
884if let Some(code) = prog.status.code() {
885// All Microsoft `link.exe` linking ror codes are
886 // four digit numbers in the range 1000 to 9999 inclusive
887if is_msvc_link_exe && (code < 1000 || code > 9999) {
888let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
889let has_linker =
890 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
891 .is_some();
892893sess.dcx().emit_note(errors::LinkExeUnexpectedError);
894895// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
896 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
897const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
898if code == STATUS_STACK_BUFFER_OVERRUN {
899sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
900 }
901902if is_vs_installed && has_linker {
903// the linker is broken
904sess.dcx().emit_note(errors::RepairVSBuildTools);
905sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
906 } else if is_vs_installed {
907// the linker is not installed
908sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
909 } else {
910// visual studio is not installed
911sess.dcx().emit_note(errors::VisualStudioNotInstalled);
912 }
913 }
914 }
915916sess.dcx().abort_if_errors();
917 }
918919let stderr = escape_string(&prog.stderr);
920let mut stdout = escape_string(&prog.stdout);
921{
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:921",
"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(921u32),
::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);
922{
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:922",
"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(922u32),
::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);
923924// Hide some progress messages from link.exe that we don't care about.
925 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
926if is_msvc_link_exe {
927if let Ok(str) = str::from_utf8(&prog.stdout) {
928let mut output = String::with_capacity(str.len());
929for line in stdout.lines() {
930if line.starts_with(" Creating library")
931 || line.starts_with("Generating code")
932 || line.starts_with("Finished generating code")
933 {
934continue;
935 }
936 output += line;
937 output += "\r\n"
938}
939stdout = escape_string(output.trim().as_bytes())
940 }
941 }
942943let level = crate_info.lint_levels.linker_messages;
944let lint = |msg| {
945diag_lint_level(sess, LINKER_MESSAGES, level, None, LinkerOutput { inner: msg });
946 };
947948if !prog.stderr.is_empty() {
949// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
950let stderr = stderr951 .strip_prefix("warning: ")
952 .unwrap_or(&stderr)
953 .replace(": warning: ", ": ");
954lint(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}", stderr))
})format!("linker stderr: {stderr}"));
955 }
956if !stdout.is_empty() {
957lint(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}", stdout))
})format!("linker stdout: {}", stdout))
958 }
959 }
960Err(e) => {
961let linker_not_found = e.kind() == io::ErrorKind::NotFound;
962963let err = if linker_not_found {
964sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
965 } else {
966sess.dcx().emit_err(errors::UnableToExeLinker {
967linker_path,
968 error: e,
969 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
970 })
971 };
972973if sess.target.is_like_msvc && linker_not_found {
974sess.dcx().emit_note(errors::MsvcMissingLinker);
975sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
976sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
977 }
978err.raise_fatal();
979 }
980 }
981982match sess.split_debuginfo() {
983// If split debug information is disabled or located in individual files
984 // there's nothing to do here.
985SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
986987// If packed split-debuginfo is requested, but the final compilation
988 // doesn't actually have any debug information, then we skip this step.
989SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
990991// On macOS the external `dsymutil` tool is used to create the packed
992 // debug information. Note that this will read debug information from
993 // the objects on the filesystem which we'll clean up later.
994SplitDebuginfo::Packedif sess.target.is_like_darwin => {
995let prog = Command::new("dsymutil").arg(out_filename).output();
996match prog {
997Ok(prog) => {
998if !prog.status.success() {
999let mut output = prog.stderr.clone();
1000output.extend_from_slice(&prog.stdout);
1001sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1002 status: prog.status,
1003 output: escape_string(&output),
1004 });
1005 }
1006 }
1007Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1008 }
1009 }
10101011// On MSVC packed debug information is produced by the linker itself so
1012 // there's no need to do anything else here.
1013SplitDebuginfo::Packedif sess.target.is_like_windows => {}
10141015// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1016 //
1017 // We cannot rely on the .o paths in the executable because they may have been
1018 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1019 // the .o/.dwo paths explicitly.
1020SplitDebuginfo::Packed => {
1021link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1022 }
1023 }
10241025let strip = sess.opts.cg.strip;
10261027if sess.target.is_like_darwin {
1028let stripcmd = "rust-objcopy";
1029match (strip, crate_type) {
1030 (Strip::Debuginfo, _) => {
1031strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1032 }
10331034// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1035(
1036 Strip::Symbols,
1037 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1038 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1039 (Strip::Symbols, _) => {
1040strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1041 }
1042 (Strip::None, _) => {}
1043 }
1044 }
10451046if sess.target.is_like_solaris {
1047// Many illumos systems will have both the native 'strip' utility and
1048 // the GNU one. Use the native version explicitly and do not rely on
1049 // what's in the path.
1050 //
1051 // If cross-compiling and there is not a native version, then use
1052 // `llvm-strip` and hope.
1053let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1054match strip {
1055// Always preserve the symbol table (-x).
1056Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1057// Strip::Symbols is handled via the --strip-all linker option.
1058Strip::Symbols => {}
1059 Strip::None => {}
1060 }
1061 }
10621063if sess.target.is_like_aix {
1064// `llvm-strip` doesn't work for AIX - their strip must be used.
1065if !sess.host.is_like_aix {
1066sess.dcx().emit_warn(errors::AixStripNotUsed);
1067 }
1068let stripcmd = "/usr/bin/strip";
1069match strip {
1070 Strip::Debuginfo => {
1071// FIXME: AIX's strip utility only offers option to strip line number information.
1072strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1073 }
1074 Strip::Symbols => {
1075// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1076strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1077 }
1078 Strip::None => {}
1079 }
1080 }
10811082if should_archive {
1083let mut ab = archive_builder_builder.new_archive_builder(sess);
1084ab.add_file(temp_filename);
1085ab.build(out_filename);
1086 }
1087}
10881089fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1090let mut cmd = Command::new(util);
1091cmd.args(options);
10921093let mut new_path = sess.get_tools_search_paths(false);
1094if let Some(path) = env::var_os("PATH") {
1095new_path.extend(env::split_paths(&path));
1096 }
1097cmd.env("PATH", env::join_paths(new_path).unwrap());
10981099let prog = cmd.arg(out_filename).output();
1100match prog {
1101Ok(prog) => {
1102if !prog.status.success() {
1103let mut output = prog.stderr.clone();
1104output.extend_from_slice(&prog.stdout);
1105sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1106util,
1107 status: prog.status,
1108 output: escape_string(&output),
1109 });
1110 }
1111 }
1112Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1113 }
1114}
11151116fn escape_string(s: &[u8]) -> String {
1117match str::from_utf8(s) {
1118Ok(s) => s.to_owned(),
1119Err(_) => ::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()),
1120 }
1121}
11221123#[cfg(not(windows))]
1124fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1125escape_string(s)
1126}
11271128/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1129/// then try to convert the string from the OEM encoding.
1130#[cfg(windows)]
1131fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1132// This only applies to the actual MSVC linker.
1133if flavour != LinkerFlavor::Msvc(Lld::No) {
1134return escape_string(s);
1135 }
1136match str::from_utf8(s) {
1137Ok(s) => return s.to_owned(),
1138Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1139Some(s) => s,
1140// The string is not UTF-8 and isn't valid for the OEM code page
1141None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1142 },
1143 }
1144}
11451146/// Wrappers around the Windows API.
1147#[cfg(windows)]
1148mod win {
1149use windows::Win32::Globalization::{
1150 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1151 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1152 };
11531154/// Get the Windows system OEM code page. This is most notably the code page
1155 /// used for link.exe's output.
1156pub(super) fn oem_code_page() -> u32 {
1157unsafe {
1158let mut cp: u32 = 0;
1159// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1160 // But the API requires us to pass the data as though it's a [u16] string.
1161let len = size_of::<u32>() / size_of::<u16>();
1162let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1163let len_written = GetLocaleInfoEx(
1164 LOCALE_NAME_SYSTEM_DEFAULT,
1165 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1166Some(data),
1167 );
1168if len_written as usize == len { cp } else { CP_OEMCP }
1169 }
1170 }
1171/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1172 /// The string does not need to be null terminated.
1173 ///
1174 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1175 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1176 ///
1177 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1178 /// any invalid bytes for the expected encoding.
1179pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1180// `MultiByteToWideChar` requires a length to be a "positive integer".
1181if s.len() > isize::MAX as usize {
1182return None;
1183 }
1184// Error if the string is not valid for the expected code page.
1185let flags = MB_ERR_INVALID_CHARS;
1186// Call MultiByteToWideChar twice.
1187 // First to calculate the length then to convert the string.
1188let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1189if len > 0 {
1190let mut utf16 = vec![0; len as usize];
1191 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1192if len > 0 {
1193return utf16.get(..len as usize).map(String::from_utf16_lossy);
1194 }
1195 }
1196None
1197}
1198}
11991200fn add_sanitizer_libraries(
1201 sess: &Session,
1202 flavor: LinkerFlavor,
1203 crate_type: CrateType,
1204 linker: &mut dyn Linker,
1205) {
1206if sess.target.is_like_android {
1207// Sanitizer runtime libraries are provided dynamically on Android
1208 // targets.
1209return;
1210 }
12111212if sess.opts.unstable_opts.external_clangrt {
1213// Linking against in-tree sanitizer runtimes is disabled via
1214 // `-Z external-clangrt`
1215return;
1216 }
12171218if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1219return;
1220 }
12211222// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1223 // which should be linked to both executables and dynamic libraries.
1224 // Everywhere else the runtimes are currently distributed as static
1225 // libraries which should be linked to executables only.
1226if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1227 crate_type,
1228 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1229 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1230 {
1231return;
1232 }
12331234let sanitizer = sess.sanitizers();
1235if sanitizer.contains(SanitizerSet::ADDRESS) {
1236link_sanitizer_runtime(sess, flavor, linker, "asan");
1237 }
1238if sanitizer.contains(SanitizerSet::DATAFLOW) {
1239link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1240 }
1241if sanitizer.contains(SanitizerSet::LEAK)
1242 && !sanitizer.contains(SanitizerSet::ADDRESS)
1243 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1244 {
1245link_sanitizer_runtime(sess, flavor, linker, "lsan");
1246 }
1247if sanitizer.contains(SanitizerSet::MEMORY) {
1248link_sanitizer_runtime(sess, flavor, linker, "msan");
1249 }
1250if sanitizer.contains(SanitizerSet::THREAD) {
1251link_sanitizer_runtime(sess, flavor, linker, "tsan");
1252 }
1253if sanitizer.contains(SanitizerSet::HWADDRESS) {
1254link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1255 }
1256if sanitizer.contains(SanitizerSet::SAFESTACK) {
1257link_sanitizer_runtime(sess, flavor, linker, "safestack");
1258 }
1259if sanitizer.contains(SanitizerSet::REALTIME) {
1260link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1261 }
1262}
12631264fn link_sanitizer_runtime(
1265 sess: &Session,
1266 flavor: LinkerFlavor,
1267 linker: &mut dyn Linker,
1268 name: &str,
1269) {
1270fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1271let path = sess.target_tlib_path.dir.join(filename);
1272if path.exists() {
1273sess.target_tlib_path.dir.clone()
1274 } else {
1275 filesearch::make_target_lib_path(
1276&sess.opts.sysroot.default,
1277sess.opts.target_triple.tuple(),
1278 )
1279 }
1280 }
12811282let channel =
1283::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();
12841285if sess.target.is_like_darwin {
1286// On Apple platforms, the sanitizer is always built as a dylib, and
1287 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1288 // rpath to the library as well (the rpath should be absolute, see
1289 // PR #41352 for details).
1290let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1291let path = find_sanitizer_runtime(sess, &filename);
1292let rpath = path.to_str().expect("non-utf8 component in path");
1293linker.link_args(&["-rpath", rpath]);
1294linker.link_dylib_by_name(&filename, false, true);
1295 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1296// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1297 // compatible ASAN library.
1298linker.link_arg("/INFERASANLIBS");
1299 } else {
1300let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1301let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1302linker.link_staticlib_by_path(&path, true);
1303 }
1304}
13051306/// Returns a boolean indicating whether the specified crate should be ignored
1307/// during LTO.
1308///
1309/// Crates ignored during LTO are not lumped together in the "massive object
1310/// file" that we create and are linked in their normal rlib states. See
1311/// comments below for what crates do not participate in LTO.
1312///
1313/// It's unusual for a crate to not participate in LTO. Typically only
1314/// compiler-specific and unstable crates have a reason to not participate in
1315/// LTO.
1316pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1317// If our target enables builtin function lowering in LLVM then the
1318 // crates providing these functions don't participate in LTO (e.g.
1319 // no_builtins or compiler builtins crates).
1320!sess.target.no_builtins
1321 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1322}
13231324/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1325pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1326fn infer_from(
1327 sess: &Session,
1328 linker: Option<PathBuf>,
1329 flavor: Option<LinkerFlavor>,
1330 features: LinkerFeaturesCli,
1331 ) -> Option<(PathBuf, LinkerFlavor)> {
1332let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1333match (linker, flavor) {
1334 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1335// only the linker flavor is known; use the default linker for the selected flavor
1336(None, Some(flavor)) => Some((
1337PathBuf::from(match flavor {
1338 LinkerFlavor::Gnu(Cc::Yes, _)
1339 | LinkerFlavor::Darwin(Cc::Yes, _)
1340 | LinkerFlavor::WasmLld(Cc::Yes)
1341 | LinkerFlavor::Unix(Cc::Yes) => {
1342if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1343// On historical Solaris systems, "cc" may have
1344 // been Sun Studio, which is not flag-compatible
1345 // with "gcc". This history casts a long shadow,
1346 // and many modern illumos distributions today
1347 // ship GCC as "gcc" without also making it
1348 // available as "cc".
1349"gcc"
1350} else {
1351"cc"
1352}
1353 }
1354 LinkerFlavor::Gnu(_, Lld::Yes)
1355 | LinkerFlavor::Darwin(_, Lld::Yes)
1356 | LinkerFlavor::WasmLld(..)
1357 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1358 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1359"ld"
1360}
1361 LinkerFlavor::Msvc(..) => "link.exe",
1362 LinkerFlavor::EmCc => {
1363if falsecfg!(windows) {
1364"emcc.bat"
1365} else {
1366"emcc"
1367}
1368 }
1369 LinkerFlavor::Bpf => "bpf-linker",
1370 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1371 LinkerFlavor::Ptx => "rust-ptx-linker",
1372 }),
1373flavor,
1374 )),
1375 (Some(linker), None) => {
1376let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1377sess.dcx().emit_fatal(errors::LinkerFileStem);
1378 });
1379let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1380let flavor = adjust_flavor_to_features(flavor, features);
1381Some((linker, flavor))
1382 }
1383 (None, None) => None,
1384 }
1385 }
13861387// While linker flavors and linker features are isomorphic (and thus targets don't need to
1388 // define features separately), we use the flavor as the root piece of data and have the
1389 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1390 // both yet.
1391fn adjust_flavor_to_features(
1392 flavor: LinkerFlavor,
1393 features: LinkerFeaturesCli,
1394 ) -> LinkerFlavor {
1395// Note: a linker feature cannot be both enabled and disabled on the CLI.
1396if features.enabled.contains(LinkerFeatures::LLD) {
1397flavor.with_lld_enabled()
1398 } else if features.disabled.contains(LinkerFeatures::LLD) {
1399flavor.with_lld_disabled()
1400 } else {
1401flavor1402 }
1403 }
14041405let features = sess.opts.cg.linker_features;
14061407// linker and linker flavor specified via command line have precedence over what the target
1408 // specification specifies
1409let linker_flavor = match sess.opts.cg.linker_flavor {
1410// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1411Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1412Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1413// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1414linker_flavor => {
1415linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1416 }
1417 };
1418if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1419return ret;
1420 }
14211422if let Some(ret) = infer_from(
1423sess,
1424sess.target.linker.as_deref().map(PathBuf::from),
1425Some(sess.target.linker_flavor),
1426features,
1427 ) {
1428return ret;
1429 }
14301431::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");
1432}
14331434/// Returns a pair of boolean indicating whether we should preserve the object and
1435/// dwarf object files on the filesystem for their debug information. This is often
1436/// useful with split-dwarf like schemes.
1437fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1438// If the objects don't have debuginfo there's nothing to preserve.
1439if sess.opts.debuginfo == config::DebugInfo::None {
1440return (false, false);
1441 }
14421443match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1444// If there is no split debuginfo then do not preserve objects.
1445(SplitDebuginfo::Off, _) => (false, false),
1446// If there is packed split debuginfo, then the debuginfo in the objects
1447 // has been packaged and the objects can be deleted.
1448(SplitDebuginfo::Packed, _) => (false, false),
1449// If there is unpacked split debuginfo and the current target can not use
1450 // split dwarf, then keep objects.
1451(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1452// If there is unpacked split debuginfo and the target can use split dwarf, then
1453 // keep the object containing that debuginfo (whether that is an object file or
1454 // dwarf object file depends on the split dwarf kind).
1455(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1456 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1457 }
1458}
14591460#[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)]
1461enum RlibFlavor {
1462 Normal,
1463 StaticlibBase,
1464}
14651466fn print_native_static_libs(
1467 sess: &Session,
1468 out: &OutFileName,
1469 all_native_libs: &[NativeLib],
1470 all_rust_dylibs: &[&Path],
1471) {
1472let mut lib_args: Vec<_> = all_native_libs1473 .iter()
1474 .filter(|l| relevant_lib(sess, l))
1475 .filter_map(|lib| {
1476let name = lib.name;
1477match lib.kind {
1478 NativeLibKind::Static { bundle: Some(false), .. }
1479 | NativeLibKind::Dylib { .. }
1480 | NativeLibKind::Unspecified => {
1481let verbatim = lib.verbatim;
1482if sess.target.is_like_msvc {
1483let (prefix, suffix) = sess.staticlib_components(verbatim);
1484Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1485 } else if sess.target.linker_flavor.is_gnu() {
1486Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1487 } else {
1488Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1489 }
1490 }
1491 NativeLibKind::Framework { .. } => {
1492// ld-only syntax, since there are no frameworks in MSVC
1493Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1494 }
1495// These are included, no need to print them
1496NativeLibKind::Static { bundle: None | Some(true), .. }
1497 | NativeLibKind::LinkArg1498 | NativeLibKind::WasmImportModule1499 | NativeLibKind::RawDylib { .. } => None,
1500 }
1501 })
1502// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1503.dedup()
1504 .collect();
1505for path in all_rust_dylibs {
1506// FIXME deduplicate with add_dynamic_crate
15071508 // Just need to tell the linker about where the library lives and
1509 // what its name is
1510let parent = path.parent();
1511if let Some(dir) = parent {
1512let dir = fix_windows_verbatim_for_gcc(dir);
1513if sess.target.is_like_msvc {
1514let mut arg = String::from("/LIBPATH:");
1515 arg.push_str(&dir.display().to_string());
1516 lib_args.push(arg);
1517 } else {
1518 lib_args.push("-L".to_owned());
1519 lib_args.push(dir.display().to_string());
1520 }
1521 }
1522let stem = path.file_stem().unwrap().to_str().unwrap();
1523// Convert library file-stem into a cc -l argument.
1524let lib = if let Some(lib) = stem.strip_prefix("lib")
1525 && !sess.target.is_like_windows
1526 {
1527 lib
1528 } else {
1529 stem
1530 };
1531let path = parent.unwrap_or_else(|| Path::new(""));
1532if sess.target.is_like_msvc {
1533// When producing a dll, the MSVC linker may not actually emit a
1534 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1535 // check to see if the file is there and just omit linking to it if it's
1536 // not present.
1537let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1538if path.join(&name).exists() {
1539 lib_args.push(name);
1540 }
1541 } else {
1542 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1543 }
1544 }
15451546match out {
1547 OutFileName::Real(path) => {
1548out.overwrite(&lib_args.join(" "), sess);
1549sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1550 }
1551 OutFileName::Stdout => {
1552sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1553// Prefix for greppability
1554 // Note: This must not be translated as tools are allowed to depend on this exact string.
1555sess.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(" ")));
1556 }
1557 }
1558}
15591560fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1561let file_path = sess.target_tlib_path.dir.join(name);
1562if file_path.exists() {
1563return file_path;
1564 }
1565// Special directory with objects used only in self-contained linkage mode
1566if self_contained {
1567let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1568if file_path.exists() {
1569return file_path;
1570 }
1571 }
1572for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1573let file_path = search_path.dir.join(name);
1574if file_path.exists() {
1575return file_path;
1576 }
1577 }
1578PathBuf::from(name)
1579}
15801581fn exec_linker(
1582 sess: &Session,
1583 cmd: &Command,
1584 out_filename: &Path,
1585 flavor: LinkerFlavor,
1586 tmpdir: &Path,
1587) -> io::Result<Output> {
1588// When attempting to spawn the linker we run a risk of blowing out the
1589 // size limits for spawning a new process with respect to the arguments
1590 // we pass on the command line.
1591 //
1592 // Here we attempt to handle errors from the OS saying "your list of
1593 // arguments is too big" by reinvoking the linker again with an `@`-file
1594 // that contains all the arguments (aka 'response' files).
1595 // The theory is that this is then accepted on all linkers and the linker
1596 // will read all its options out of there instead of looking at the command line.
1597if !cmd.very_likely_to_exceed_some_spawn_limit() {
1598match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1599Ok(child) => {
1600let output = child.wait_with_output();
1601flush_linked_file(&output, out_filename)?;
1602return output;
1603 }
1604Err(ref e) if command_line_too_big(e) => {
1605{
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:1605",
"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(1605u32),
::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);
1606 }
1607Err(e) => return Err(e),
1608 }
1609 }
16101611{
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:1611",
"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(1611u32),
::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");
1612let mut cmd2 = cmd.clone();
1613let mut args = String::new();
1614for arg in cmd2.take_args() {
1615 args.push_str(
1616&Escape {
1617 arg: arg.to_str().unwrap(),
1618// Windows-style escaping for @-files is used by
1619 // - all linkers targeting MSVC-like targets, including LLD
1620 // - all LLD flavors running on Windows hosts
1621 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1622is_like_msvc: sess.target.is_like_msvc
1623 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1624 }
1625 .to_string(),
1626 );
1627 args.push('\n');
1628 }
1629let file = tmpdir.join("linker-arguments");
1630let bytes = if sess.target.is_like_msvc {
1631let mut out = Vec::with_capacity((1 + args.len()) * 2);
1632// start the stream with a UTF-16 BOM
1633for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1634// encode in little endian
1635out.push(c as u8);
1636 out.push((c >> 8) as u8);
1637 }
1638out1639 } else {
1640args.into_bytes()
1641 };
1642 fs::write(&file, &bytes)?;
1643cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1644{
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:1644",
"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(1644u32),
::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);
1645let output = cmd2.output();
1646flush_linked_file(&output, out_filename)?;
1647return output;
16481649#[cfg(not(windows))]
1650fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1651Ok(())
1652 }
16531654#[cfg(windows)]
1655fn flush_linked_file(
1656 command_output: &io::Result<Output>,
1657 out_filename: &Path,
1658 ) -> io::Result<()> {
1659// On Windows, under high I/O load, output buffers are sometimes not flushed,
1660 // even long after process exit, causing nasty, non-reproducible output bugs.
1661 //
1662 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1663 //
1664 // А full writeup of the original Chrome bug can be found at
1665 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
16661667if let &Ok(ref out) = command_output {
1668if out.status.success() {
1669if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1670 of.sync_all()?;
1671 }
1672 }
1673 }
16741675Ok(())
1676 }
16771678#[cfg(unix)]
1679fn command_line_too_big(err: &io::Error) -> bool {
1680err.raw_os_error() == Some(::libc::E2BIG)
1681 }
16821683#[cfg(windows)]
1684fn command_line_too_big(err: &io::Error) -> bool {
1685const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1686 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1687 }
16881689#[cfg(not(any(unix, windows)))]
1690fn command_line_too_big(_: &io::Error) -> bool {
1691false
1692}
16931694struct Escape<'a> {
1695 arg: &'a str,
1696 is_like_msvc: bool,
1697 }
16981699impl<'a> fmt::Displayfor Escape<'a> {
1700fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1701if self.is_like_msvc {
1702// This is "documented" at
1703 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1704 //
1705 // Unfortunately there's not a great specification of the
1706 // syntax I could find online (at least) but some local
1707 // testing showed that this seemed sufficient-ish to catch
1708 // at least a few edge cases.
1709f.write_fmt(format_args!("\""))write!(f, "\"")?;
1710for c in self.arg.chars() {
1711match c {
1712'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1713 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1714 }
1715 }
1716f.write_fmt(format_args!("\""))write!(f, "\"")?;
1717 } else {
1718// This is documented at https://linux.die.net/man/1/ld, namely:
1719 //
1720 // > Options in file are separated by whitespace. A whitespace
1721 // > character may be included in an option by surrounding the
1722 // > entire option in either single or double quotes. Any
1723 // > character (including a backslash) may be included by
1724 // > prefixing the character to be included with a backslash.
1725 //
1726 // We put an argument on each line, so all we need to do is
1727 // ensure the line is interpreted as one whole argument.
1728for c in self.arg.chars() {
1729match c {
1730'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1731 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1732 }
1733 }
1734 }
1735Ok(())
1736 }
1737 }
1738}
17391740fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1741let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1742 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1743 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1744 LinkOutputKind::DynamicPicExe1745 }
1746 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1747 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1748 LinkOutputKind::StaticPicExe1749 }
1750 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1751 (_, true, _) => LinkOutputKind::StaticDylib,
1752 (_, false, _) => LinkOutputKind::DynamicDylib,
1753 };
17541755// Adjust the output kind to target capabilities.
1756let opts = &sess.target;
1757let pic_exe_supported = opts.position_independent_executables;
1758let static_pic_exe_supported = opts.static_position_independent_executables;
1759let static_dylib_supported = opts.crt_static_allows_dylibs;
1760match kind {
1761 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1762 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1763 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1764_ => kind,
1765 }
1766}
17671768// Returns true if linker is located within sysroot
1769fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1770let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1771linker.with_extension("exe")
1772 } else {
1773linker.to_path_buf()
1774 };
1775for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1776let full_path = dir.join(&linker_with_extension);
1777// If linker comes from sysroot assume self-contained mode
1778if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1779return false;
1780 }
1781 }
1782true
1783}
17841785/// Various toolchain components used during linking are used from rustc distribution
1786/// instead of being found somewhere on the host system.
1787/// We only provide such support for a very limited number of targets.
1788fn self_contained_components(
1789 sess: &Session,
1790 crate_type: CrateType,
1791 linker: &Path,
1792) -> LinkSelfContainedComponents {
1793// Turn the backwards compatible bool values for `self_contained` into fully inferred
1794 // `LinkSelfContainedComponents`.
1795let self_contained =
1796if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1797// Emit an error if the user requested self-contained mode on the CLI but the target
1798 // explicitly refuses it.
1799if sess.target.link_self_contained.is_disabled() {
1800sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1801 }
1802self_contained1803 } else {
1804match sess.target.link_self_contained {
1805 LinkSelfContainedDefault::False => false,
1806 LinkSelfContainedDefault::True => true,
18071808 LinkSelfContainedDefault::WithComponents(components) => {
1809// For target specs with explicitly enabled components, we can return them
1810 // directly.
1811return components;
1812 }
18131814// FIXME: Find a better heuristic for "native musl toolchain is available",
1815 // based on host and linker path, for example.
1816 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1817LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1818 LinkSelfContainedDefault::InferredForMingw => {
1819sess.host == sess.target
1820 && sess.target.abi != Abi::Uwp1821 && detect_self_contained_mingw(sess, linker)
1822 }
1823 }
1824 };
1825if self_contained {
1826LinkSelfContainedComponents::all()
1827 } else {
1828LinkSelfContainedComponents::empty()
1829 }
1830}
18311832/// Add pre-link object files defined by the target spec.
1833fn add_pre_link_objects(
1834 cmd: &mut dyn Linker,
1835 sess: &Session,
1836 flavor: LinkerFlavor,
1837 link_output_kind: LinkOutputKind,
1838 self_contained: bool,
1839) {
1840// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1841 // so Fuchsia has to be special-cased.
1842let opts = &sess.target;
1843let empty = Default::default();
1844let objects = if self_contained {
1845&opts.pre_link_objects_self_contained
1846 } 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, _))) {
1847&opts.pre_link_objects
1848 } else {
1849&empty1850 };
1851for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1852 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1853 }
1854}
18551856/// Add post-link object files defined by the target spec.
1857fn add_post_link_objects(
1858 cmd: &mut dyn Linker,
1859 sess: &Session,
1860 link_output_kind: LinkOutputKind,
1861 self_contained: bool,
1862) {
1863let objects = if self_contained {
1864&sess.target.post_link_objects_self_contained
1865 } else {
1866&sess.target.post_link_objects
1867 };
1868for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1869 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1870 }
1871}
18721873/// Add arbitrary "pre-link" args defined by the target spec or from command line.
1874/// FIXME: Determine where exactly these args need to be inserted.
1875fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1876if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1877cmd.verbatim_args(args.iter().map(Deref::deref));
1878 }
18791880cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1881}
18821883/// Add a link script embedded in the target, if applicable.
1884fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1885match (crate_type, &sess.target.link_script) {
1886 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1887if !sess.target.linker_flavor.is_gnu() {
1888sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1889 }
18901891let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
18921893let path = tmpdir.join(file_name);
1894if let Err(error) = fs::write(&path, script.as_ref()) {
1895sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1896 }
18971898cmd.link_arg("--script").link_arg(path);
1899 }
1900_ => {}
1901 }
1902}
19031904/// Add arbitrary "user defined" args defined from command line.
1905/// FIXME: Determine where exactly these args need to be inserted.
1906fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1907cmd.verbatim_args(&sess.opts.cg.link_args);
1908}
19091910/// Add arbitrary "late link" args defined by the target spec.
1911/// FIXME: Determine where exactly these args need to be inserted.
1912fn add_late_link_args(
1913 cmd: &mut dyn Linker,
1914 sess: &Session,
1915 flavor: LinkerFlavor,
1916 crate_type: CrateType,
1917 crate_info: &CrateInfo,
1918) {
1919let any_dynamic_crate = crate_type == CrateType::Dylib1920 || crate_type == CrateType::Sdylib1921 || crate_info.dependency_formats.iter().any(|(ty, list)| {
1922*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1923 });
1924if any_dynamic_crate {
1925if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1926cmd.verbatim_args(args.iter().map(Deref::deref));
1927 }
1928 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1929cmd.verbatim_args(args.iter().map(Deref::deref));
1930 }
1931if let Some(args) = sess.target.late_link_args.get(&flavor) {
1932cmd.verbatim_args(args.iter().map(Deref::deref));
1933 }
1934}
19351936/// Add arbitrary "post-link" args defined by the target spec.
1937/// FIXME: Determine where exactly these args need to be inserted.
1938fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1939if let Some(args) = sess.target.post_link_args.get(&flavor) {
1940cmd.verbatim_args(args.iter().map(Deref::deref));
1941 }
1942}
19431944/// Add a synthetic object file that contains reference to all symbols that we want to expose to
1945/// the linker.
1946///
1947/// Background: we implement rlibs as static library (archives). Linkers treat archives
1948/// differently from object files: all object files participate in linking, while archives will
1949/// only participate in linking if they can satisfy at least one undefined reference (version
1950/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1951/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1952/// can't keep them either. This causes #47384.
1953///
1954/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
1955/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
1956/// we instead just introduce an undefined reference to them. This could be done by `-u` command
1957/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1958/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1959/// from removing them, and this is especially problematic for embedded programming where every
1960/// byte counts.
1961///
1962/// This method creates a synthetic object file, which contains undefined references to all symbols
1963/// that are necessary for the linking. They are only present in symbol table but not actually
1964/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1965/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
1966///
1967/// There's a few internal crates in the standard library (aka libcore and
1968/// libstd) which actually have a circular dependence upon one another. This
1969/// currently arises through "weak lang items" where libcore requires things
1970/// like `rust_begin_unwind` but libstd ends up defining it. To get this
1971/// circular dependence to work correctly we declare some of these things
1972/// in this synthetic object.
1973fn add_linked_symbol_object(
1974 cmd: &mut dyn Linker,
1975 sess: &Session,
1976 tmpdir: &Path,
1977 symbols: &[(String, SymbolExportKind)],
1978) {
1979if symbols.is_empty() {
1980return;
1981 }
19821983let Some(mut file) = super::metadata::create_object_file(sess) else {
1984return;
1985 };
19861987if file.format() == object::BinaryFormat::Coff {
1988// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1989 // so add an empty section.
1990file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
19911992// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1993 // default mangler in `object` crate.
1994file.set_mangling(object::write::Mangling::None);
1995 }
19961997if file.format() == object::BinaryFormat::MachO {
1998// Divide up the sections into sub-sections via symbols for dead code stripping.
1999 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2000 // discard on MachO targets.
2001file.set_subsections_via_symbols();
2002 }
20032004// ld64 requires a relocation to load undefined symbols, see below.
2005 // Not strictly needed if linking with lld, but might as well do it there too.
2006let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2007Some(file.add_section(
2008file.segment_name(object::write::StandardSegment::Data).to_vec(),
2009"__data".into(),
2010 object::SectionKind::Data,
2011 ))
2012 } else {
2013None2014 };
20152016for (sym, kind) in symbols.iter() {
2017let symbol = file.add_symbol(object::write::Symbol {
2018 name: sym.clone().into(),
2019 value: 0,
2020 size: 0,
2021 kind: match kind {
2022 SymbolExportKind::Text => object::SymbolKind::Text,
2023 SymbolExportKind::Data => object::SymbolKind::Data,
2024 SymbolExportKind::Tls => object::SymbolKind::Tls,
2025 },
2026 scope: object::SymbolScope::Unknown,
2027 weak: false,
2028 section: object::write::SymbolSection::Undefined,
2029 flags: object::SymbolFlags::None,
2030 });
20312032// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2033 //
2034 // Code-wise, the relevant parts of ld64 are roughly:
2035 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2036 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2037 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2038 //
2039 // 2. Read the archive table of contents (__.SYMDEF file).
2040 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2041 //
2042 // 3. Begin linking by loading "atoms" from input files.
2043 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2044 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2045 //
2046 // a. Directly specified object files (`.o`) are parsed immediately.
2047 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2048 //
2049 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2050 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2051 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2052 //
2053 // - Relocations/fixups are atoms.
2054 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2055 //
2056 // b. Archives are not parsed yet.
2057 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2058 //
2059 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2060 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2061 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2062 //
2063 // All of the steps above are fairly similar to other linkers, except that **it completely
2064 // ignores undefined symbols**.
2065 //
2066 // So to make this trick work on ld64, we need to do something else to load the relevant
2067 // object files. We do this by inserting a relocation (fixup) for each symbol.
2068if let Some(section) = ld64_section_helper {
2069 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2070 .expect("failed adding relocation");
2071 }
2072 }
20732074let path = tmpdir.join("symbols.o");
2075let result = std::fs::write(&path, file.write().unwrap());
2076if let Err(error) = result {
2077sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2078 }
2079cmd.add_object(&path);
2080}
20812082/// Add object files containing code from the current crate.
2083fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2084for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
2085 cmd.add_object(obj);
2086 }
2087}
20882089/// Add object files for allocator code linked once for the whole crate tree.
2090fn add_local_crate_allocator_objects(
2091 cmd: &mut dyn Linker,
2092 compiled_modules: &CompiledModules,
2093 crate_info: &CrateInfo,
2094 crate_type: CrateType,
2095) {
2096if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type) {
2097if let Some(obj) =
2098compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref())
2099 {
2100cmd.add_object(obj);
2101 }
2102 }
2103}
21042105/// Add object files containing metadata for the current crate.
2106fn add_local_crate_metadata_objects(
2107 cmd: &mut dyn Linker,
2108 sess: &Session,
2109 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2110 crate_type: CrateType,
2111 tmpdir: &Path,
2112 crate_info: &CrateInfo,
2113 metadata: &EncodedMetadata,
2114) {
2115// When linking a dynamic library, we put the metadata into a section of the
2116 // executable. This metadata is in a separate object file from the main
2117 // object file, so we create and link it in here.
2118if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2119let data = archive_builder_builder.create_dylib_metadata_wrapper(
2120sess,
2121&metadata,
2122&crate_info.metadata_symbol,
2123 );
2124let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
21252126cmd.add_object(&obj);
2127 }
2128}
21292130/// Add sysroot and other globally set directories to the directory search list.
2131fn add_library_search_dirs(
2132 cmd: &mut dyn Linker,
2133 sess: &Session,
2134 self_contained_components: LinkSelfContainedComponents,
2135 apple_sdk_root: Option<&Path>,
2136) {
2137if !sess.opts.unstable_opts.link_native_libraries {
2138return;
2139 }
21402141let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2142let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2143if is_framework {
2144cmd.framework_path(dir);
2145 } else {
2146cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2147 }
2148 ControlFlow::<()>::Continue(())
2149 });
2150}
21512152/// Add options making relocation sections in the produced ELF files read-only
2153/// and suppressing lazy binding.
2154fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2155match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2156 RelroLevel::Full => cmd.full_relro(),
2157 RelroLevel::Partial => cmd.partial_relro(),
2158 RelroLevel::Off => cmd.no_relro(),
2159 RelroLevel::None => {}
2160 }
2161}
21622163/// Add library search paths used at runtime by dynamic linkers.
2164fn add_rpath_args(
2165 cmd: &mut dyn Linker,
2166 sess: &Session,
2167 crate_info: &CrateInfo,
2168 out_filename: &Path,
2169) {
2170if !sess.target.has_rpath {
2171return;
2172 }
21732174// FIXME (#2397): At some point we want to rpath our guesses as to
2175 // where extern libraries might live, based on the
2176 // add_lib_search_paths
2177if sess.opts.cg.rpath {
2178let libs = crate_info2179 .used_crates
2180 .iter()
2181 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2182 .collect::<Vec<_>>();
2183let rpath_config = RPathConfig {
2184 libs: &*libs,
2185 out_filename: out_filename.to_path_buf(),
2186 is_like_darwin: sess.target.is_like_darwin,
2187 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2188 };
2189cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2190 }
2191}
21922193fn add_c_staticlib_symbols(
2194 sess: &Session,
2195 lib: &NativeLib,
2196 out: &mut Vec<(String, SymbolExportKind)>,
2197) -> io::Result<()> {
2198let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
21992200let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
22012202let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2203 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22042205for member in archive.members() {
2206let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22072208let data = member
2209 .data(&*archive_map)
2210 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22112212// clang LTO: raw LLVM bitcode
2213if data.starts_with(b"BC\xc0\xde") {
2214return Err(io::Error::new(
2215 io::ErrorKind::InvalidData,
2216"LLVM bitcode object in C static library (LTO not supported)",
2217 ));
2218 }
22192220let object = object::File::parse(&*data)
2221 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
22222223// gcc / clang ELF / Mach-O LTO
2224if object.sections().any(|s| {
2225 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2226 }) {
2227return Err(io::Error::new(
2228 io::ErrorKind::InvalidData,
2229"LTO object in C static library is not supported",
2230 ));
2231 }
22322233for symbol in object.symbols() {
2234if symbol.scope() != object::SymbolScope::Dynamic {
2235continue;
2236 }
22372238let name = match symbol.name() {
2239Ok(n) => n,
2240Err(_) => continue,
2241 };
22422243let export_kind = match symbol.kind() {
2244 object::SymbolKind::Text => SymbolExportKind::Text,
2245 object::SymbolKind::Data => SymbolExportKind::Data,
2246_ => continue,
2247 };
22482249// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2250 // Need to be resolved.
2251out.push((name.to_string(), export_kind));
2252 }
2253 }
22542255Ok(())
2256}
22572258/// Produce the linker command line containing linker path and arguments.
2259///
2260/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2261/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2262/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2263/// to the linking process as a whole.
2264/// Order-independent options may still override each other in order-dependent fashion,
2265/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2266fn linker_with_args(
2267 path: &Path,
2268 flavor: LinkerFlavor,
2269 sess: &Session,
2270 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2271 crate_type: CrateType,
2272 tmpdir: &Path,
2273 out_filename: &Path,
2274 compiled_modules: &CompiledModules,
2275 crate_info: &CrateInfo,
2276 metadata: &EncodedMetadata,
2277 self_contained_components: LinkSelfContainedComponents,
2278 codegen_backend: &'static str,
2279) -> Command {
2280let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2281let cmd = &mut *super::linker::get_linker(
2282sess,
2283path,
2284flavor,
2285self_contained_components.are_any_components_enabled(),
2286&crate_info.target_cpu,
2287codegen_backend,
2288 );
2289let link_output_kind = link_output_kind(sess, crate_type);
22902291let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
22922293if crate_type == CrateType::Cdylib {
2294let mut seen = FxHashSet::default();
22952296for lib in &crate_info.used_libraries {
2297if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2298 && seen.insert((lib.name, lib.verbatim))
2299 {
2300if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2301 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2302"failed to process C static library `{}`: {}",
2303 lib.name, err
2304 ));
2305 }
2306 }
2307 }
2308 }
23092310// ------------ Early order-dependent options ------------
23112312 // If we're building something like a dynamic library then some platforms
2313 // need to make sure that all symbols are exported correctly from the
2314 // dynamic library.
2315 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2316 // at least on some platforms (e.g. windows-gnu).
2317cmd.export_symbols(tmpdir, crate_type, &export_symbols);
23182319// Can be used for adding custom CRT objects or overriding order-dependent options above.
2320 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2321 // introduce a target spec option for order-independent linker options and migrate built-in
2322 // specs to it.
2323add_pre_link_args(cmd, sess, flavor);
23242325// ------------ Object code and libraries, order-dependent ------------
23262327 // Pre-link CRT objects.
2328add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
23292330add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
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, compiled_modules);
2363add_local_crate_metadata_objects(
2364cmd,
2365sess,
2366archive_builder_builder,
2367crate_type,
2368tmpdir,
2369crate_info,
2370metadata,
2371 );
2372add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, 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,
2389crate_info,
2390tmpdir,
2391link_output_kind,
2392 );
23932394// Upstream rust crates and their non-dynamic native libraries.
2395add_upstream_rust_crates(
2396cmd,
2397sess,
2398archive_builder_builder,
2399crate_info,
2400crate_type,
2401tmpdir,
2402link_output_kind,
2403 );
24042405// Dynamic native libraries from upstream crates.
2406add_upstream_native_libraries(
2407cmd,
2408sess,
2409archive_builder_builder,
2410crate_info,
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 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 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 = crate_info2454 .dependency_formats
2455 .get(&crate_type)
2456 .expect("failed to find crate type in dependency format list");
24572458// We sort the libraries below
2459#[allow(rustc::potential_query_instability)]
2460let mut native_libraries_from_nonstatics = crate_info2461 .native_libraries
2462 .iter()
2463 .filter_map(|(&cnum, libraries)| {
2464if sess.target.is_like_windows {
2465 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2466 } else {
2467Some(libraries)
2468 }
2469 })
2470 .flatten()
2471 .collect::<Vec<_>>();
2472native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
24732474if sess.target.is_like_windows {
2475for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2476 sess,
2477 archive_builder_builder,
2478 native_libraries_from_nonstatics,
2479 tmpdir,
2480false,
2481 ) {
2482 cmd.add_object(&output_path);
2483 }
2484 } else {
2485for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2486 sess,
2487 native_libraries_from_nonstatics,
2488&raw_dylib_dir,
2489 ) {
2490// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2491cmd.link_dylib_by_name(&link_path, true, as_needed);
2492 }
2493 }
24942495// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2496 // command line shorter, reset it to default here before adding more libraries.
2497cmd.reset_per_library_state();
24982499// FIXME: Built-in target specs occasionally use this for linking system libraries,
2500 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2501 // and remove the option.
2502add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
25032504// ------------ Arbitrary order-independent options ------------
25052506 // Add order-independent options determined by rustc from its compiler options,
2507 // target properties and source code.
2508add_order_independent_options(
2509cmd,
2510sess,
2511link_output_kind,
2512self_contained_components,
2513flavor,
2514crate_type,
2515crate_info,
2516out_filename,
2517tmpdir,
2518 );
25192520// Can be used for arbitrary order-independent options.
2521 // In practice may also be occasionally used for linking native libraries.
2522 // Passed after compiler-generated options to support manual overriding when necessary.
2523add_user_defined_link_args(cmd, sess);
25242525// ------------ Builtin configurable linker scripts ------------
2526 // The user's link args should be able to overwrite symbols in the compiler's
2527 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2528 // to work correctly, the user needs to be able to specify linker arguments like
2529 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2530add_link_script(cmd, sess, tmpdir, crate_type);
25312532// ------------ Object code and libraries, order-dependent ------------
25332534 // Post-link CRT objects.
2535add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
25362537// ------------ Late order-dependent options ------------
25382539 // Doesn't really make sense.
2540 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2541 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2542 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2543add_post_link_args(cmd, sess, flavor);
25442545cmd.take_cmd()
2546}
25472548fn add_order_independent_options(
2549 cmd: &mut dyn Linker,
2550 sess: &Session,
2551 link_output_kind: LinkOutputKind,
2552 self_contained_components: LinkSelfContainedComponents,
2553 flavor: LinkerFlavor,
2554 crate_type: CrateType,
2555 crate_info: &CrateInfo,
2556 out_filename: &Path,
2557 tmpdir: &Path,
2558) {
2559// Take care of the flavors and CLI options requesting the `lld` linker.
2560add_lld_args(cmd, sess, flavor, self_contained_components);
25612562add_apple_link_args(cmd, sess, flavor);
25632564let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
25652566if sess.target.os == Os::Fuchsia2567 && crate_type == CrateType::Executable2568 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2569 {
2570let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2571cmd.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"));
2572 }
25732574if sess.target.eh_frame_header {
2575cmd.add_eh_frame_header();
2576 }
25772578// Make the binary compatible with data execution prevention schemes.
2579cmd.add_no_exec();
25802581if self_contained_components.is_crt_objects_enabled() {
2582cmd.no_crt_objects();
2583 }
25842585if sess.target.os == Os::Emscripten {
2586cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2587"-fwasm-exceptions"
2588} else if sess.panic_strategy().unwinds() {
2589"-sDISABLE_EXCEPTION_CATCHING=0"
2590} else {
2591"-sDISABLE_EXCEPTION_CATCHING=1"
2592});
2593 }
25942595if flavor == LinkerFlavor::Llbc {
2596cmd.link_args(&[
2597"--target",
2598&versioned_llvm_target(sess),
2599"--target-cpu",
2600&crate_info.target_cpu,
2601 ]);
2602if crate_info.target_features.len() > 0 {
2603cmd.link_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target-feature={0}",
&crate_info.target_features.join(",")))
})format!("--target-feature={}", &crate_info.target_features.join(",")));
2604 }
2605 } else if flavor == LinkerFlavor::Ptx {
2606cmd.link_args(&["--fallback-arch", &crate_info.target_cpu]);
2607 } else if flavor == LinkerFlavor::Bpf {
2608cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2609if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2610 .into_iter()
2611 .find(|feat| !feat.is_empty())
2612 {
2613cmd.link_args(&["--cpu-features", feat]);
2614 }
2615 }
26162617cmd.linker_plugin_lto();
26182619add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
26202621cmd.output_filename(out_filename);
26222623if crate_type == CrateType::Executable2624 && sess.target.is_like_windows
2625 && let Some(s) = &crate_info.windows_subsystem
2626 {
2627cmd.windows_subsystem(*s);
2628 }
26292630// Try to strip as much out of the generated object by removing unused
2631 // sections if possible. See more comments in linker.rs
2632if !sess.link_dead_code() {
2633// If PGO is enabled sometimes gc_sections will remove the profile data section
2634 // as it appears to be unused. This can then cause the PGO profile file to lose
2635 // some functions. If we are generating a profile we shouldn't strip those metadata
2636 // sections to ensure we have all the data for PGO.
2637let keep_metadata =
2638crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2639cmd.gc_sections(keep_metadata);
2640 }
26412642cmd.set_output_kind(link_output_kind, crate_type, out_filename);
26432644add_relro_args(cmd, sess);
26452646// Pass optimization flags down to the linker.
2647cmd.optimize();
26482649// Gather the set of NatVis files, if any, and write them out to a temp directory.
2650let natvis_visualizers = collect_natvis_visualizers(
2651tmpdir,
2652sess,
2653&crate_info.local_crate_name,
2654&crate_info.natvis_debugger_visualizers,
2655 );
26562657// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2658cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
26592660// We want to prevent the compiler from accidentally leaking in any system libraries,
2661 // so by default we tell linkers not to link to any default libraries.
2662if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2663cmd.no_default_libraries();
2664 }
26652666if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2667cmd.pgo_gen();
2668 }
26692670if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2671cmd.control_flow_guard();
2672 }
26732674// OBJECT-FILES-NO, AUDIT-ORDER
2675if sess.opts.unstable_opts.ehcont_guard {
2676cmd.ehcont_guard();
2677 }
26782679add_rpath_args(cmd, sess, crate_info, out_filename);
2680}
26812682// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2683fn collect_natvis_visualizers(
2684 tmpdir: &Path,
2685 sess: &Session,
2686 crate_name: &Symbol,
2687 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2688) -> Vec<PathBuf> {
2689let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
26902691for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2692let 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));
26932694match fs::write(&visualizer_out_file, &visualizer.src) {
2695Ok(()) => {
2696 visualizer_paths.push(visualizer_out_file);
2697 }
2698Err(error) => {
2699 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2700 path: visualizer_out_file,
2701 error,
2702 });
2703 }
2704 };
2705 }
2706visualizer_paths2707}
27082709fn add_native_libs_from_crate(
2710 cmd: &mut dyn Linker,
2711 sess: &Session,
2712 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2713 crate_info: &CrateInfo,
2714 tmpdir: &Path,
2715 bundled_libs: &FxIndexSet<Symbol>,
2716 cnum: CrateNum,
2717 link_static: bool,
2718 link_dynamic: bool,
2719 link_output_kind: LinkOutputKind,
2720) {
2721if !sess.opts.unstable_opts.link_native_libraries {
2722// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2723 // external build system already has the native dependencies defined, and it
2724 // will provide them to the linker itself.
2725return;
2726 }
27272728if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2729// If rlib contains native libs as archives, unpack them to tmpdir.
2730let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2731archive_builder_builder2732 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2733 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2734 }
27352736let native_libs = match cnum {
2737LOCAL_CRATE => &crate_info.used_libraries,
2738_ => &crate_info.native_libraries[&cnum],
2739 };
27402741let mut last = (None, NativeLibKind::Unspecified, false);
2742for lib in native_libs {
2743if !relevant_lib(sess, lib) {
2744continue;
2745 }
27462747// Skip if this library is the same as the last.
2748last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2749continue;
2750 } else {
2751 (Some(lib.name), lib.kind, lib.verbatim)
2752 };
27532754let name = lib.name.as_str();
2755let verbatim = lib.verbatim;
2756match lib.kind {
2757 NativeLibKind::Static { bundle, whole_archive, .. } => {
2758if link_static {
2759let bundle = bundle.unwrap_or(true);
2760let whole_archive = whole_archive == Some(true);
2761if bundle && cnum != LOCAL_CRATE {
2762if let Some(filename) = lib.filename {
2763// If rlib contains native libs as archives, they are unpacked to tmpdir.
2764let path = tmpdir.join(filename.as_str());
2765 cmd.link_staticlib_by_path(&path, whole_archive);
2766 }
2767 } else {
2768 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2769 }
2770 }
2771 }
2772 NativeLibKind::Dylib { as_needed } => {
2773if link_dynamic {
2774 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2775 }
2776 }
2777 NativeLibKind::Unspecified => {
2778// If we are generating a static binary, prefer static library when the
2779 // link kind is unspecified.
2780if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2781if link_static {
2782 cmd.link_staticlib_by_name(name, verbatim, false);
2783 }
2784 } else if link_dynamic {
2785 cmd.link_dylib_by_name(name, verbatim, true);
2786 }
2787 }
2788 NativeLibKind::Framework { as_needed } => {
2789if link_dynamic {
2790 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2791 }
2792 }
2793 NativeLibKind::RawDylib { as_needed: _ } => {
2794// Handled separately in `linker_with_args`.
2795}
2796 NativeLibKind::WasmImportModule => {}
2797 NativeLibKind::LinkArg => {
2798if link_static {
2799if verbatim {
2800 cmd.verbatim_arg(name);
2801 } else {
2802 cmd.link_arg(name);
2803 }
2804 }
2805 }
2806 }
2807 }
2808}
28092810fn add_local_native_libraries(
2811 cmd: &mut dyn Linker,
2812 sess: &Session,
2813 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2814 crate_info: &CrateInfo,
2815 tmpdir: &Path,
2816 link_output_kind: LinkOutputKind,
2817) {
2818// All static and dynamic native library dependencies are linked to the local crate.
2819let link_static = true;
2820let link_dynamic = true;
2821add_native_libs_from_crate(
2822cmd,
2823sess,
2824archive_builder_builder,
2825crate_info,
2826tmpdir,
2827&Default::default(),
2828LOCAL_CRATE,
2829link_static,
2830link_dynamic,
2831link_output_kind,
2832 );
2833}
28342835fn add_upstream_rust_crates(
2836 cmd: &mut dyn Linker,
2837 sess: &Session,
2838 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2839 crate_info: &CrateInfo,
2840 crate_type: CrateType,
2841 tmpdir: &Path,
2842 link_output_kind: LinkOutputKind,
2843) {
2844// All of the heavy lifting has previously been accomplished by the
2845 // dependency_format module of the compiler. This is just crawling the
2846 // output of that module, adding crates as necessary.
2847 //
2848 // Linking to a rlib involves just passing it to the linker (the linker
2849 // will slurp up the object files inside), and linking to a dynamic library
2850 // involves just passing the right -l flag.
2851let data = crate_info2852 .dependency_formats
2853 .get(&crate_type)
2854 .expect("failed to find crate type in dependency format list");
28552856if sess.target.is_like_aix {
2857// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
2858 // the dependency name when outputting a shared library. Thus, `ld` will
2859 // use the full path to shared libraries as the dependency if passed it
2860 // by default unless `noipath` is passed.
2861 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
2862cmd.link_or_cc_arg("-bnoipath");
2863 }
28642865for &cnum in &crate_info.used_crates {
2866// We may not pass all crates through to the linker. Some crates may appear statically in
2867 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2868 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2869 // Even if they were already included into a dylib
2870 // (e.g. `libstd` when `-C prefer-dynamic` is used).
2871let linkage = data[cnum];
2872let link_static_crate = linkage == Linkage::Static
2873 || linkage == Linkage::IncludedFromDylib
2874 && (crate_info.compiler_builtins == Some(cnum)
2875 || crate_info.profiler_runtime == Some(cnum));
28762877let mut bundled_libs = Default::default();
2878match linkage {
2879 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2880if link_static_crate {
2881 bundled_libs = crate_info.native_libraries[&cnum]
2882 .iter()
2883 .filter_map(|lib| lib.filename)
2884 .collect();
2885 add_static_crate(
2886 cmd,
2887 sess,
2888 archive_builder_builder,
2889 crate_info,
2890 tmpdir,
2891 cnum,
2892&bundled_libs,
2893 );
2894 }
2895 }
2896 Linkage::Dynamic => {
2897let src = &crate_info.used_crate_source[&cnum];
2898 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
2899 }
2900 }
29012902// Static libraries are linked for a subset of linked upstream crates.
2903 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2904 // because the rlib is just an archive.
2905 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
2906 // the native library because it is already linked into the dylib, and even if
2907 // inline/const/generic functions from the dylib can refer to symbols from the native
2908 // library, those symbols should be exported and available from the dylib anyway.
2909 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
2910let link_static = link_static_crate;
2911// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
2912let link_dynamic = false;
2913 add_native_libs_from_crate(
2914 cmd,
2915 sess,
2916 archive_builder_builder,
2917 crate_info,
2918 tmpdir,
2919&bundled_libs,
2920 cnum,
2921 link_static,
2922 link_dynamic,
2923 link_output_kind,
2924 );
2925 }
2926}
29272928fn add_upstream_native_libraries(
2929 cmd: &mut dyn Linker,
2930 sess: &Session,
2931 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2932 crate_info: &CrateInfo,
2933 tmpdir: &Path,
2934 link_output_kind: LinkOutputKind,
2935) {
2936for &cnum in &crate_info.used_crates {
2937// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
2938 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
2939 // are linked together with their respective upstream crates, and in their originally
2940 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
2941 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
2942let link_static = false;
2943// Dynamic libraries are linked for all linked upstream crates.
2944 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2945 // because the rlib is just an archive.
2946 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
2947 // the native library too because inline/const/generic functions from the dylib can refer
2948 // to symbols from the native library, so the native library providing those symbols should
2949 // be available when linking our final binary.
2950let link_dynamic = true;
2951 add_native_libs_from_crate(
2952 cmd,
2953 sess,
2954 archive_builder_builder,
2955 crate_info,
2956 tmpdir,
2957&Default::default(),
2958 cnum,
2959 link_static,
2960 link_dynamic,
2961 link_output_kind,
2962 );
2963 }
2964}
29652966// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
2967// to be relative to the sysroot directory, which may be a relative path specified by the user.
2968//
2969// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
2970// linker command line can be non-deterministic due to the paths including the current working
2971// directory. The linker command line needs to be deterministic since it appears inside the PDB
2972// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
2973//
2974// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
2975fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2976let sysroot_lib_path = &sess.target_tlib_path.dir;
2977let canonical_sysroot_lib_path =
2978 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
29792980let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2981if canonical_lib_dir == canonical_sysroot_lib_path {
2982// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
2983sysroot_lib_path.clone()
2984 } else {
2985fix_windows_verbatim_for_gcc(lib_dir)
2986 }
2987}
29882989fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2990if let Some(dir) = path.parent() {
2991let file_name = path.file_name().expect("library path has no file name component");
2992rehome_sysroot_lib_dir(sess, dir).join(file_name)
2993 } else {
2994fix_windows_verbatim_for_gcc(path)
2995 }
2996}
29972998// Adds the static "rlib" versions of all crates to the command line.
2999// There's a bit of magic which happens here specifically related to LTO,
3000// namely that we remove upstream object files.
3001//
3002// When performing LTO, almost(*) all of the bytecode from the upstream
3003// libraries has already been included in our object file output. As a
3004// result we need to remove the object files in the upstream libraries so
3005// the linker doesn't try to include them twice (or whine about duplicate
3006// symbols). We must continue to include the rest of the rlib, however, as
3007// it may contain static native libraries which must be linked in.
3008//
3009// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3010// their bytecode wasn't included. The object files in those libraries must
3011// still be passed to the linker.
3012//
3013// Note, however, that if we're not doing LTO we can just pass the rlib
3014// blindly to the linker (fast) because it's fine if it's not actually
3015// included as we're at the end of the dependency chain.
3016fn add_static_crate(
3017 cmd: &mut dyn Linker,
3018 sess: &Session,
3019 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3020 crate_info: &CrateInfo,
3021 tmpdir: &Path,
3022 cnum: CrateNum,
3023 bundled_lib_file_names: &FxIndexSet<Symbol>,
3024) {
3025let src = &crate_info.used_crate_source[&cnum];
3026let cratepath = src.rlib.as_ref().unwrap();
30273028let mut link_upstream =
3029 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
30303031if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3032 {
3033link_upstream(cratepath);
3034return;
3035 }
30363037let dst = tmpdir.join(cratepath.file_name().unwrap());
3038let name = cratepath.file_name().unwrap().to_str().unwrap();
3039let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3040let bundled_lib_file_names = bundled_lib_file_names.clone();
30413042sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3043let canonical_name = name.replace('-', "_");
3044let upstream_rust_objects_already_included =
3045are_upstream_rust_objects_already_included(sess);
3046let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
30473048let mut archive = archive_builder_builder.new_archive_builder(sess);
3049if let Err(error) = archive.add_archive(
3050cratepath,
3051Box::new(move |f| {
3052if f == METADATA_FILENAME {
3053return true;
3054 }
30553056let canonical = f.replace('-', "_");
30573058let is_rust_object =
3059canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
30603061// If we're performing LTO and this is a rust-generated object
3062 // file, then we don't need the object file as it's part of the
3063 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3064 // though, so we let that object file slide.
3065if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3066return true;
3067 }
30683069// We skip native libraries because:
3070 // 1. This native libraries won't be used from the generated rlib,
3071 // so we can throw them away to avoid the copying work.
3072 // 2. We can't allow it to be a single remaining entry in archive
3073 // as some linkers may complain on that.
3074if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3075return true;
3076 }
30773078false
3079}),
3080 ) {
3081sess.dcx()
3082 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3083 }
3084if archive.build(&dst) {
3085link_upstream(&dst);
3086 }
3087 });
3088}
30893090// Same thing as above, but for dynamic crates instead of static crates.
3091fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3092cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3093}
30943095fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3096match lib.cfg {
3097Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3098None => true,
3099 }
3100}
31013102pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3103match sess.lto() {
3104 config::Lto::Fat => true,
3105 config::Lto::Thin => {
3106// If we defer LTO to the linker, we haven't run LTO ourselves, so
3107 // any upstream object files have not been copied yet.
3108!sess.opts.cg.linker_plugin_lto.enabled()
3109 }
3110 config::Lto::No | config::Lto::ThinLocal => false,
3111 }
3112}
31133114/// We need to communicate five things to the linker on Apple/Darwin targets:
3115/// - The architecture.
3116/// - The operating system (and that it's an Apple platform).
3117/// - The environment.
3118/// - The deployment target.
3119/// - The SDK version.
3120fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3121if !sess.target.is_like_darwin {
3122return;
3123 }
3124let LinkerFlavor::Darwin(cc, _) = flavorelse {
3125return;
3126 };
31273128// `sess.target.arch` (`target_arch`) is not detailed enough.
3129let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3130let target_os = &sess.target.os;
3131let target_env = &sess.target.env;
31323133// The architecture name to forward to the linker.
3134 //
3135 // Supported architecture names can be found in the source:
3136 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3137 //
3138 // Intentionally verbose to ensure that the list always matches correctly
3139 // with the list in the source above.
3140let ld64_arch = match llvm_arch {
3141"armv7k" => "armv7k",
3142"armv7s" => "armv7s",
3143"arm64" => "arm64",
3144"arm64e" => "arm64e",
3145"arm64_32" => "arm64_32",
3146// ld64 doesn't understand i686, so fall back to i386 instead.
3147 //
3148 // Same story when linking with cc, since that ends up invoking ld64.
3149"i386" | "i686" => "i386",
3150"x86_64" => "x86_64",
3151"x86_64h" => "x86_64h",
3152_ => ::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),
3153 };
31543155if cc == Cc::No {
3156// From the man page for ld64 (`man ld`):
3157 // > The linker accepts universal (multiple-architecture) input files,
3158 // > but always creates a "thin" (single-architecture), standard
3159 // > Mach-O output file. The architecture for the output file is
3160 // > specified using the -arch option.
3161 //
3162 // The linker has heuristics to determine the desired architecture,
3163 // but to be safe, and to avoid a warning, we set the architecture
3164 // explicitly.
3165cmd.link_args(&["-arch", ld64_arch]);
31663167// Man page says that ld64 supports the following platform names:
3168 // > - macos
3169 // > - ios
3170 // > - tvos
3171 // > - watchos
3172 // > - bridgeos
3173 // > - visionos
3174 // > - xros
3175 // > - mac-catalyst
3176 // > - ios-simulator
3177 // > - tvos-simulator
3178 // > - watchos-simulator
3179 // > - visionos-simulator
3180 // > - xros-simulator
3181 // > - driverkit
3182let platform_name = match (target_os, target_env) {
3183 (os, Env::Unspecified) => os.desc(),
3184 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3185 (Os::IOs, Env::Sim) => "ios-simulator",
3186 (Os::TvOs, Env::Sim) => "tvos-simulator",
3187 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3188 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3189_ => ::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}"),
3190 };
31913192let min_version = sess.apple_deployment_target().fmt_full().to_string();
31933194// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3195 // - By dyld to give extra warnings and errors, see e.g.:
3196 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3197 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3198 // - By system frameworks to change certain behaviour. For example, the default value of
3199 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3200 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3201 //
3202 // We do not currently know the actual SDK version though, so we have a few options:
3203 // 1. Use the minimum version supported by rustc.
3204 // 2. Use the same as the deployment target.
3205 // 3. Use an arbitrary recent version.
3206 // 4. Omit the version.
3207 //
3208 // The first option is too low / too conservative, and means that users will not get the
3209 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3210 //
3211 // The second option is similarly conservative, and also wrong since if the user specified a
3212 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3213 // make invalid assumptions about the capabilities of the binary.
3214 //
3215 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3216 // version, and is also wrong for similar reasons as above.
3217 //
3218 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3219 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3220 // it as 0.0, which is again too low/conservative.
3221 //
3222 // Currently, we lie about the SDK version, and choose the second option.
3223 //
3224 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3225 // <https://github.com/rust-lang/rust/issues/129432>
3226let sdk_version = &*min_version;
32273228// From the man page for ld64 (`man ld`):
3229 // > This is set to indicate the platform, oldest supported version of
3230 // > that platform that output is to be used on, and the SDK that the
3231 // > output was built against.
3232 //
3233 // Like with `-arch`, the linker can figure out the platform versions
3234 // itself from the binaries being linked, but to be safe, we specify
3235 // the desired versions here explicitly.
3236cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3237 } else {
3238// cc == Cc::Yes
3239 //
3240 // We'd _like_ to use `-target` everywhere, since that can uniquely
3241 // communicate all the required details except for the SDK version
3242 // (which is read by Clang itself from the SDKROOT), but that doesn't
3243 // work on GCC, and since we don't know whether the `cc` compiler is
3244 // Clang, GCC, or something else, we fall back to other options that
3245 // also work on GCC when compiling for macOS.
3246 //
3247 // Targets other than macOS are ill-supported by GCC (it doesn't even
3248 // support e.g. `-miphoneos-version-min`), so in those cases we can
3249 // fairly safely use `-target`. See also the following, where it is
3250 // made explicit that the recommendation by LLVM developers is to use
3251 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3252if *target_os == Os::MacOs {
3253// `-arch` communicates the architecture.
3254 //
3255 // CC forwards the `-arch` to the linker, so we use the same value
3256 // here intentionally.
3257cmd.cc_args(&["-arch", ld64_arch]);
32583259// The presence of `-mmacosx-version-min` makes CC default to
3260 // macOS, and it sets the deployment target.
3261let version = sess.apple_deployment_target().fmt_full();
3262// Intentionally pass this as a single argument, Clang doesn't
3263 // seem to like it otherwise.
3264cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
32653266// macOS has no environment, so with these two, we've told CC the
3267 // four desired parameters.
3268 //
3269 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3270} else {
3271cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3272 }
3273 }
3274}
32753276fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3277if !sess.target.is_like_darwin {
3278return None;
3279 }
3280let LinkerFlavor::Darwin(cc, _) = flavorelse {
3281return None;
3282 };
32833284// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3285 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3286 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3287 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3288 // instead we invoke `xcrun` manually.
3289 //
3290 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3291 // cause the trampoline binary to skip looking up the SDK itself).
3292let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
32933294if cc == Cc::Yes {
3295// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3296 // - The `--sysroot` flag.
3297 // - The `-isysroot` flag.
3298 // - The `SDKROOT` environment variable.
3299 //
3300 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3301 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3302 // only applies to include header files, but on Apple targets it also applies to libraries
3303 // and frameworks.
3304 //
3305 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3306 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3307 // primarily because that is the same interface that is used when invoking the tool under
3308 // `xcrun -sdk macosx $tool`.
3309 //
3310 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3311 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3312 //
3313 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3314 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3315 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3316 //
3317 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3318 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3319 // ignoring the value we set here, and instead use their built-in sysroot).
3320cmd.cmd().env("SDKROOT", &sdkroot);
3321 } else {
3322// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3323 // read by the linker, so it's really the only option.
3324 //
3325 // This is also what Clang does.
3326cmd.link_arg("-syslibroot");
3327cmd.link_arg(&sdkroot);
3328 }
33293330Some(sdkroot)
3331}
33323333fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3334if let Ok(sdkroot) = env::var("SDKROOT") {
3335let p = PathBuf::from(&sdkroot);
33363337// Ignore invalid SDKs, similar to what clang does:
3338 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3339 //
3340 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3341 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3342 // clearly set for the wrong platform.
3343 //
3344 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3345match &*apple::sdk_name(&sess.target).to_lowercase() {
3346"appletvos"
3347if sdkroot.contains("TVSimulator.platform")
3348 || sdkroot.contains("MacOSX.platform") => {}
3349"appletvsimulator"
3350if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3351"iphoneos"
3352if sdkroot.contains("iPhoneSimulator.platform")
3353 || sdkroot.contains("MacOSX.platform") => {}
3354"iphonesimulator"
3355if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3356 }
3357"macosx"
3358if sdkroot.contains("iPhoneOS.platform")
3359 || sdkroot.contains("iPhoneSimulator.platform")
3360 || sdkroot.contains("AppleTVOS.platform")
3361 || sdkroot.contains("AppleTVSimulator.platform")
3362 || sdkroot.contains("WatchOS.platform")
3363 || sdkroot.contains("WatchSimulator.platform")
3364 || sdkroot.contains("XROS.platform")
3365 || sdkroot.contains("XRSimulator.platform") => {}
3366"watchos"
3367if sdkroot.contains("WatchSimulator.platform")
3368 || sdkroot.contains("MacOSX.platform") => {}
3369"watchsimulator"
3370if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3371"xros"
3372if sdkroot.contains("XRSimulator.platform")
3373 || sdkroot.contains("MacOSX.platform") => {}
3374"xrsimulator"
3375if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3376// Ignore `SDKROOT` if it's not a valid path.
3377_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3378_ => return Some(p),
3379 }
3380 }
33813382 apple::get_sdk_root(sess)
3383}
33843385/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3386/// invoke it:
3387/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3388/// - or any `lld` available to `cc`.
3389fn add_lld_args(
3390 cmd: &mut dyn Linker,
3391 sess: &Session,
3392 flavor: LinkerFlavor,
3393 self_contained_components: LinkSelfContainedComponents,
3394) {
3395{
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:3395",
"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(3395u32),
::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!(
3396"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3397 flavor, self_contained_components,
3398 );
33993400// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3401 // we don't need to do anything.
3402if !(flavor.uses_cc() && flavor.uses_lld()) {
3403return;
3404 }
34053406// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3407 // directories to the tool's search path, depending on a mix between what users can specify on
3408 // the CLI, and what the target spec enables (as it can't disable components):
3409 // - if the self-contained linker is enabled on the CLI or by the target spec,
3410 // - and if the self-contained linker is not disabled on the CLI.
3411let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3412let self_contained_target = self_contained_components.is_linker_enabled();
34133414let self_contained_linker = self_contained_cli || self_contained_target;
3415if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3416let mut linker_path_exists = false;
3417for path in sess.get_tools_search_paths(false) {
3418let linker_path = path.join("gcc-ld");
3419 linker_path_exists |= linker_path.exists();
3420 cmd.cc_arg({
3421let mut arg = OsString::from("-B");
3422 arg.push(linker_path);
3423 arg
3424 });
3425 }
3426if !linker_path_exists {
3427// As a sanity check, we emit an error if none of these paths exist: we want
3428 // self-contained linking and have no linker.
3429sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3430 }
3431 }
34323433// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3434 // `lld` as the linker.
3435 //
3436 // Note that wasm targets skip this step since the only option there anyway
3437 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3438 // this, `wasm-component-ld`, which is overridden if this option is passed.
3439if !sess.target.is_like_wasm {
3440cmd.cc_arg("-fuse-ld=lld");
3441 }
34423443if !flavor.is_gnu() {
3444// Tell clang to use a non-default LLD flavor.
3445 // Gcc doesn't understand the target option, but we currently assume
3446 // that gcc is not used for Apple and Wasm targets (#97402).
3447 //
3448 // Note that we don't want to do that by default on macOS: e.g. passing a
3449 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3450 // shown in issue #101653 and the discussion in PR #101792.
3451 //
3452 // It could be required in some cases of cross-compiling with
3453 // LLD, but this is generally unspecified, and we don't know
3454 // which specific versions of clang, macOS SDK, host and target OS
3455 // combinations impact us here.
3456 //
3457 // So we do a simple first-approximation until we know more of what the
3458 // Apple targets require (and which would be handled prior to hitting this
3459 // LLD codepath anyway), but the expectation is that until then
3460 // this should be manually passed if needed. We specify the target when
3461 // targeting a different linker flavor on macOS, and that's also always
3462 // the case when targeting WASM.
3463if sess.target.linker_flavor != sess.host.linker_flavor {
3464cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3465 }
3466 }
3467}
34683469// gold has been deprecated with binutils 2.44
3470// and is known to behave incorrectly around Rust programs.
3471// There have been reports of being unable to bootstrap with gold:
3472// https://github.com/rust-lang/rust/issues/139425
3473// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3474// emitted with `#[used(linker)]`.
3475fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3476use object::read::elf::{FileHeader, SectionHeader};
3477use object::read::{ReadCache, ReadRef, Result};
3478use object::{Endianness, elf};
34793480fn elf_has_gold_version_note<'a>(
3481 elf: &impl FileHeader,
3482 data: impl ReadRef<'a>,
3483 ) -> Result<bool> {
3484let endian = elf.endian()?;
34853486let section =
3487elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3488if let Some((_, section)) = section3489 && let Some(mut notes) = section.notes(endian, data)?
3490{
3491return Ok(notes.any(|note| {
3492note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3493 }));
3494 }
34953496Ok(false)
3497 }
34983499let data = ReadCache::new(BufReader::new(File::open(path)?));
35003501let was_linked_with_gold = if sess.target.pointer_width == 64 {
3502let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3503elf_has_gold_version_note(elf, &data)?
3504} else if sess.target.pointer_width == 32 {
3505let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3506elf_has_gold_version_note(elf, &data)?
3507} else {
3508return Ok(());
3509 };
35103511if was_linked_with_gold {
3512let mut warn =
3513sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3514warn.help("consider using LLD or ld from GNU binutils instead");
3515warn.emit();
3516 }
3517Ok(())
3518}