1mod raw_dylib;
23use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
1112use find_msvc_tools;
13use itertools::Itertools;
14use object::{Object, ObjectSection, ObjectSymbol};
15use regex::Regex;
16use rustc_arena::TypedArena;
17use rustc_attr_parsing::eval_config_entry;
18use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::DiagCtxtHandle;
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_lint_defs::builtin::LINKER_INFO;
26use rustc_macros::Diagnostic;
27use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
28use rustc_metadata::{
29 EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
30 walk_native_lib_search_dirs,
31};
32use rustc_middle::bug;
33use rustc_middle::lint::emit_lint_base;
34use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
35use rustc_middle::middle::dependency_format::Linkage;
36use rustc_middle::middle::exported_symbols::SymbolExportKind;
37use rustc_session::config::{
38self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
39OutputType, PrintKind, SplitDwarfKind, Strip,
40};
41use rustc_session::lint::builtin::LINKER_MESSAGES;
42use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
43use rustc_session::search_paths::PathKind;
44/// For all the linkers we support, and information they might
45/// need out of the shared crate context before we get rid of it.
46use rustc_session::{Session, filesearch};
47use rustc_span::Symbol;
48use rustc_target::spec::crt_objects::CrtObjects;
49use rustc_target::spec::{
50BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
51LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
52RelroLevel, SanitizerSet, SplitDebuginfo,
53};
54use tracing::{debug, info, warn};
5556use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
57use super::command::Command;
58use super::linker::{self, Linker};
59use super::metadata::{MetadataPosition, create_wrapper_file};
60use super::rpath::{self, RPathConfig};
61use super::{apple, versioned_llvm_target};
62use crate::base::needs_allocator_shim_for_linking;
63use crate::{
64CodegenLintLevels, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors,
65looks_like_rust_object_file,
66};
6768pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
69if let Err(e) = fs::remove_file(path) {
70if e.kind() != io::ErrorKind::NotFound {
71dcx.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));
72 }
73 }
74}
7576/// Performs the linkage portion of the compilation phase. This will generate all
77/// of the requested outputs for this compilation session.
78pub fn link_binary(
79 sess: &Session,
80 archive_builder_builder: &dyn ArchiveBuilderBuilder,
81 compiled_modules: CompiledModules,
82 crate_info: CrateInfo,
83 metadata: EncodedMetadata,
84 outputs: &OutputFilenames,
85 codegen_backend: &'static str,
86) {
87let _timer = sess.timer("link_binary");
88let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
89let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
90for &crate_type in &crate_info.crate_types {
91// Ignore executable crates if we have -Z no-codegen, as they will error.
92if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
93 && !output_metadata
94 && crate_type == CrateType::Executable
95 {
96continue;
97 }
9899if invalid_output_for_target(sess, crate_type) {
100::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);
101 }
102103 sess.time("link_binary_check_files_are_writeable", || {
104for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
105 check_file_is_writeable(obj, sess);
106 }
107 });
108109if outputs.outputs.should_link() {
110let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
111let tmpdir = TempDirBuilder::new()
112 .prefix("rustc")
113 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
114 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
115let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
116117let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
118let out_filename = output.file_for_writing(
119 outputs,
120 OutputType::Exe,
121&crate_name,
122 sess.invocation_temp.as_deref(),
123 );
124match crate_type {
125 CrateType::Rlib => {
126let _timer = sess.timer("link_rlib");
127{
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:127",
"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(127u32),
::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);
128 link_rlib(
129 sess,
130 archive_builder_builder,
131&compiled_modules,
132&crate_info,
133&metadata,
134 RlibFlavor::Normal,
135&path,
136 )
137 .build(&out_filename);
138 }
139 CrateType::StaticLib => {
140 link_staticlib(
141 sess,
142 archive_builder_builder,
143&compiled_modules,
144&crate_info,
145&metadata,
146&out_filename,
147&path,
148 );
149 }
150_ => {
151 link_natively(
152 sess,
153 archive_builder_builder,
154 crate_type,
155&out_filename,
156&compiled_modules,
157&crate_info,
158&metadata,
159 path.as_ref(),
160 codegen_backend,
161 );
162 }
163 }
164if sess.opts.json_artifact_notifications {
165 sess.dcx().emit_artifact_notification(&out_filename, "link");
166 }
167168if sess.prof.enabled()
169 && let Some(artifact_name) = out_filename.file_name()
170 {
171// Record size for self-profiling
172let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
173174 sess.prof.artifact_size(
175"linked_artifact",
176 artifact_name.to_string_lossy(),
177 file_size,
178 );
179 }
180181if sess.target.binary_format == BinaryFormat::Elf {
182if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
183{
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:183",
"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(183u32),
::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");
184 }
185 }
186187if output.is_stdout() {
188if output.is_tty() {
189 sess.dcx().emit_err(errors::BinaryOutputToTty {
190 shorthand: OutputType::Exe.shorthand(),
191 });
192 } else if let Err(e) = copy_to_stdout(&out_filename) {
193 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
194 }
195 tempfiles_for_stdout_output.push(out_filename);
196 }
197 }
198 }
199200// Remove the temporary object file and metadata if we aren't saving temps.
201sess.time("link_binary_remove_temps", || {
202// If the user requests that temporaries are saved, don't delete any.
203if sess.opts.cg.save_temps {
204return;
205 }
206207let maybe_remove_temps_from_module =
208 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
209if !preserve_objects && let Some(ref obj) = module.object {
210ensure_removed(sess.dcx(), obj);
211 }
212213if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
214ensure_removed(sess.dcx(), dwo_obj);
215 }
216 };
217218let remove_temps_from_module =
219 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
220221// Otherwise, always remove the allocator module temporaries.
222if let Some(ref allocator_module) = compiled_modules.allocator_module {
223remove_temps_from_module(allocator_module);
224 }
225226// Remove the temporary files if output goes to stdout
227for temp in tempfiles_for_stdout_output {
228 ensure_removed(sess.dcx(), &temp);
229 }
230231// If no requested outputs require linking, then the object temporaries should
232 // be kept.
233if !sess.opts.output_types.should_link() {
234return;
235 }
236237// Potentially keep objects for their debuginfo.
238let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
239{
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:239",
"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(239u32),
::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);
240241for module in &compiled_modules.modules {
242 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
243 }
244 });
245}
246247// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
248// crate types must use the same dependency formats.
249pub fn each_linked_rlib(
250 info: &CrateInfo,
251 crate_type: Option<CrateType>,
252 f: &mut dyn FnMut(CrateNum, &Path),
253) -> Result<(), errors::LinkRlibError> {
254let fmts = if let Some(crate_type) = crate_type {
255let Some(fmts) = info.dependency_formats.get(&crate_type) else {
256return Err(errors::LinkRlibError::MissingFormat);
257 };
258259fmts260 } else {
261let mut dep_formats = info.dependency_formats.iter();
262let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
263if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
264return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
265 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
266 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
267 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
268 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
269 });
270 }
271list1272 };
273274let used_dep_crates = info.used_crates.iter();
275for &cnum in used_dep_crates {
276match fmts.get(cnum) {
277Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
278Some(_) => {}
279None => return Err(errors::LinkRlibError::MissingFormat),
280 }
281let crate_name = info.crate_name[&cnum];
282let used_crate_source = &info.used_crate_source[&cnum];
283if let Some(path) = &used_crate_source.rlib {
284 f(cnum, path);
285 } else if used_crate_source.rmeta.is_some() {
286return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
287 } else {
288return Err(errors::LinkRlibError::NotFound { crate_name });
289 }
290 }
291Ok(())
292}
293294/// Create an 'rlib'.
295///
296/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
297/// The rlib primarily contains the object file of the crate, but it also some of the object files
298/// from native libraries.
299fn link_rlib<'a>(
300 sess: &'a Session,
301 archive_builder_builder: &dyn ArchiveBuilderBuilder,
302 compiled_modules: &CompiledModules,
303 crate_info: &CrateInfo,
304 metadata: &EncodedMetadata,
305 flavor: RlibFlavor,
306 tmpdir: &MaybeTempDir,
307) -> Box<dyn ArchiveBuilder + 'a> {
308let mut ab = archive_builder_builder.new_archive_builder(sess);
309310let trailing_metadata = match flavor {
311 RlibFlavor::Normal => {
312let (metadata, metadata_position) =
313create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
314let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
315match metadata_position {
316 MetadataPosition::First => {
317// Most of the time metadata in rlib files is wrapped in a "dummy" object
318 // file for the target platform so the rlib can be processed entirely by
319 // normal linkers for the platform. Sometimes this is not possible however.
320 // If it is possible however, placing the metadata object first improves
321 // performance of getting metadata from rlibs.
322ab.add_file(&metadata);
323None324 }
325 MetadataPosition::Last => Some(metadata),
326 }
327 }
328329 RlibFlavor::StaticlibBase => None,
330 };
331332for m in &compiled_modules.modules {
333if let Some(obj) = m.object.as_ref() {
334 ab.add_file(obj);
335 }
336337if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
338 ab.add_file(dwarf_obj);
339 }
340 }
341342match flavor {
343 RlibFlavor::Normal => {}
344 RlibFlavor::StaticlibBase => {
345let obj = compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref());
346if let Some(obj) = obj {
347ab.add_file(obj);
348 }
349 }
350 }
351352// Used if packed_bundled_libs flag enabled.
353let mut packed_bundled_libs = Vec::new();
354355// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
356 // we may not be configured to actually include a static library if we're
357 // adding it here. That's because later when we consume this rlib we'll
358 // decide whether we actually needed the static library or not.
359 //
360 // To do this "correctly" we'd need to keep track of which libraries added
361 // which object files to the archive. We don't do that here, however. The
362 // #[link(cfg(..))] feature is unstable, though, and only intended to get
363 // liblibc working. In that sense the check below just indicates that if
364 // there are any libraries we want to omit object files for at link time we
365 // just exclude all custom object files.
366 //
367 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
368 // feature then we'll need to figure out how to record what objects were
369 // loaded from the libraries found here and then encode that into the
370 // metadata of the rlib we're generating somehow.
371for lib in crate_info.used_libraries.iter() {
372let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
373continue;
374 };
375if flavor == RlibFlavor::Normal
376 && let Some(filename) = lib.filename
377 {
378let path = find_native_static_library(filename.as_str(), true, sess);
379let src = read(path)
380 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
381let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
382let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
383 packed_bundled_libs.push(wrapper_file);
384 } else {
385let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
386 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
387 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
388 });
389 }
390 }
391392// On Windows, we add the raw-dylib import libraries to the rlibs already.
393 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
394 // Instead, we add all raw-dylibs to the final link on ELF.
395if sess.target.is_like_windows {
396for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
397 sess,
398 archive_builder_builder,
399 crate_info.used_libraries.iter(),
400 tmpdir.as_ref(),
401true,
402 ) {
403 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
404 sess.dcx()
405 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
406 });
407 }
408 }
409410if let Some(trailing_metadata) = trailing_metadata {
411// Note that it is important that we add all of our non-object "magical
412 // files" *after* all of the object files in the archive. The reason for
413 // this is as follows:
414 //
415 // * When performing LTO, this archive will be modified to remove
416 // objects from above. The reason for this is described below.
417 //
418 // * When the system linker looks at an archive, it will attempt to
419 // determine the architecture of the archive in order to see whether its
420 // linkable.
421 //
422 // The algorithm for this detection is: iterate over the files in the
423 // archive. Skip magical SYMDEF names. Interpret the first file as an
424 // object file. Read architecture from the object file.
425 //
426 // * As one can probably see, if "metadata" and "foo.bc" were placed
427 // before all of the objects, then the architecture of this archive would
428 // not be correctly inferred once 'foo.o' is removed.
429 //
430 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
431 // file for the target platform so the rlib can be processed entirely by
432 // normal linkers for the platform. Sometimes this is not possible however.
433 //
434 // Basically, all this means is that this code should not move above the
435 // code above.
436ab.add_file(&trailing_metadata);
437 }
438439// Add all bundled static native library dependencies.
440 // Archives added to the end of .rlib archive, see comment above for the reason.
441for lib in packed_bundled_libs {
442 ab.add_file(&lib)
443 }
444445ab446}
447448/// Create a static archive.
449///
450/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
451/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
452/// dependencies as well.
453///
454/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
455/// library dependencies that they're not linked in.
456///
457/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
458/// object file (and also don't prepare the archive with a metadata file).
459fn link_staticlib(
460 sess: &Session,
461 archive_builder_builder: &dyn ArchiveBuilderBuilder,
462 compiled_modules: &CompiledModules,
463 crate_info: &CrateInfo,
464 metadata: &EncodedMetadata,
465 out_filename: &Path,
466 tempdir: &MaybeTempDir,
467) {
468{
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:468",
"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(468u32),
::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);
469let mut ab = link_rlib(
470sess,
471archive_builder_builder,
472compiled_modules,
473crate_info,
474metadata,
475 RlibFlavor::StaticlibBase,
476tempdir,
477 );
478let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
479480let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
481let lto = are_upstream_rust_objects_already_included(sess)
482 && !ignored_for_lto(sess, crate_info, cnum);
483484let native_libs = crate_info.native_libraries[&cnum].iter();
485let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
486let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
487488let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
489ab.add_archive(
490path,
491Box::new(move |fname: &str| {
492// Ignore metadata files, no matter the name.
493if fname == METADATA_FILENAME {
494return true;
495 }
496497// Don't include Rust objects if LTO is enabled
498if lto && looks_like_rust_object_file(fname) {
499return true;
500 }
501502// Skip objects for bundled libs.
503if bundled_libs.contains(&Symbol::intern(fname)) {
504return true;
505 }
506507false
508}),
509 )
510 .unwrap();
511512archive_builder_builder513 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
514 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
515516for filename in relevant_libs.iter() {
517let joined = tempdir.as_ref().join(filename.as_str());
518let path = joined.as_path();
519 ab.add_archive(path, Box::new(|_| false)).unwrap();
520 }
521522all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
523 });
524if let Err(e) = res {
525sess.dcx().emit_fatal(e);
526 }
527528ab.build(out_filename);
529530let crates = crate_info.used_crates.iter();
531532let fmts = crate_info533 .dependency_formats
534 .get(&CrateType::StaticLib)
535 .expect("no dependency formats for staticlib");
536537let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
538for &cnum in crates {
539let Some(Linkage::Dynamic) = fmts.get(cnum) else {
540continue;
541 };
542let crate_name = crate_info.crate_name[&cnum];
543let used_crate_source = &crate_info.used_crate_source[&cnum];
544if let Some(path) = &used_crate_source.dylib {
545 all_rust_dylibs.push(&**path);
546 } else if used_crate_source.rmeta.is_some() {
547 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
548 } else {
549 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
550 }
551 }
552553all_native_libs.extend_from_slice(&crate_info.used_libraries);
554555for print in &sess.opts.prints {
556if print.kind == PrintKind::NativeStaticLibs {
557 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
558 }
559 }
560}
561562/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
563/// DWARF package.
564fn link_dwarf_object(
565 sess: &Session,
566 compiled_modules: &CompiledModules,
567 crate_info: &CrateInfo,
568 executable_out_filename: &Path,
569) {
570let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
571dwp_out_filename.push(".dwp");
572{
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:572",
"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(572u32),
::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);
573574#[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)]
575struct ThorinSession<Relocations> {
576 arena_data: TypedArena<Vec<u8>>,
577 arena_mmap: TypedArena<Mmap>,
578 arena_relocations: TypedArena<Relocations>,
579 }
580581impl<Relocations> ThorinSession<Relocations> {
582fn alloc_mmap(&self, data: Mmap) -> &Mmap {
583&*self.arena_mmap.alloc(data)
584 }
585 }
586587impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
588fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
589&*self.arena_data.alloc(data)
590 }
591592fn alloc_relocation(&self, data: Relocations) -> &Relocations {
593&*self.arena_relocations.alloc(data)
594 }
595596fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
597let file = File::open(&path)?;
598let mmap = (unsafe { Mmap::map(file) })?;
599Ok(self.alloc_mmap(mmap))
600 }
601 }
602603match sess.time("run_thorin", || -> Result<(), thorin::Error> {
604let thorin_sess = ThorinSession::default();
605let mut package = thorin::DwarfPackage::new(&thorin_sess);
606607// Input objs contain .o/.dwo files from the current crate.
608match sess.opts.unstable_opts.split_dwarf_kind {
609 SplitDwarfKind::Single => {
610for input_obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
611 package.add_input_object(input_obj)?;
612 }
613 }
614 SplitDwarfKind::Split => {
615for input_obj in
616compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
617 {
618 package.add_input_object(input_obj)?;
619 }
620 }
621 }
622623// Input rlibs contain .o/.dwo files from dependencies.
624let input_rlibs = crate_info625 .used_crate_source
626 .items()
627 .filter_map(|(_, csource)| csource.rlib.as_ref())
628 .into_sorted_stable_ord();
629630for input_rlib in input_rlibs {
631{
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:631",
"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(631u32),
::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);
632 package.add_input_object(input_rlib)?;
633 }
634635// Failing to read the referenced objects is expected for dependencies where the path in the
636 // executable will have been cleaned by Cargo, but the referenced objects will be contained
637 // within rlibs provided as inputs.
638 //
639 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
640 // found, but are provided explicitly above.
641 //
642 // Adding an executable is primarily done to make `thorin` check that all the referenced
643 // dwarf objects are found in the end.
644package.add_executable(
645executable_out_filename,
646 thorin::MissingReferencedObjectBehaviour::Skip,
647 )?;
648649let output_stream = BufWriter::new(
650OpenOptions::new()
651 .read(true)
652 .write(true)
653 .create(true)
654 .truncate(true)
655 .open(dwp_out_filename)?,
656 );
657let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
658package.finish()?.emit(&mut output_stream)?;
659output_stream.result()?;
660output_stream.into_inner().flush()?;
661662Ok(())
663 }) {
664Ok(()) => {}
665Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
666 }
667}
668669#[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)]
670#[diag("{$inner}")]
671/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
672/// end up with inconsistent languages within the same diagnostic.
673struct LinkerOutput {
674 inner: String,
675}
676677fn is_msvc_link_exe(sess: &Session) -> bool {
678let (linker_path, flavor) = linker_and_flavor(sess);
679sess.target.is_like_msvc
680 && flavor == LinkerFlavor::Msvc(Lld::No)
681// Match exactly "link.exe"
682&& linker_path.to_str() == Some("link.exe")
683}
684685fn is_macos_ld(sess: &Session) -> bool {
686let (_, flavor) = linker_and_flavor(sess);
687sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))688}
689690fn is_windows_gnu_ld(sess: &Session) -> bool {
691let (_, flavor) = linker_and_flavor(sess);
692sess.target.is_like_windows
693 && !sess.target.is_like_msvc
694 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))695}
696697fn report_linker_output(sess: &Session, levels: CodegenLintLevels, stdout: &[u8], stderr: &[u8]) {
698let mut escaped_stderr = escape_string(&stderr);
699let mut escaped_stdout = escape_string(&stdout);
700let mut linker_info = String::new();
701702{
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:702",
"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(702u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stderr:\n{0}",
&escaped_stderr) as &dyn Value))])
});
} else { ; }
};info!("linker stderr:\n{}", &escaped_stderr);
703{
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:703",
"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(703u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stdout:\n{0}",
&escaped_stdout) as &dyn Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &escaped_stdout);
704705fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
706let mut output = String::new();
707if let Ok(str) = str::from_utf8(bytes) {
708{
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:708",
"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(708u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("line: {0}",
str) as &dyn Value))])
});
} else { ; }
};info!("line: {str}");
709output = String::with_capacity(str.len());
710for line in str.lines() {
711 f(line.trim(), &mut output);
712 }
713 }
714escape_string(output.trim().as_bytes())
715 }
716717if is_msvc_link_exe(sess) {
718{
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:718",
"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(718u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred MSVC link.exe")
as &dyn Value))])
});
} else { ; }
};info!("inferred MSVC link.exe");
719720escaped_stdout = for_each(&stdout, |line, output| {
721// Hide some progress messages from link.exe that we don't care about.
722 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
723if line.starts_with(" Creating library")
724 || line.starts_with("Generating code")
725 || line.starts_with("Finished generating code")
726 {
727linker_info += line;
728linker_info += "\r\n";
729 } else {
730*output += line;
731*output += "\r\n"
732}
733 });
734 } else if is_macos_ld(sess) {
735{
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:735",
"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(735u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred macOS LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred macOS LD");
736737// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
738let deployment_mismatch = |line: &str| {
739line.starts_with("ld: warning: object file (")
740 && line.contains("was built for newer 'macOS' version")
741 && line.contains("than being linked")
742 };
743// FIXME: This is a real warning we would like to show, but it hits too many crates
744 // to want to turn it on immediately.
745let search_path = |line: &str| {
746line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
747 };
748escaped_stderr = for_each(&stderr, |line, output| {
749// This duplicate library warning is just not helpful at all.
750if line.starts_with("ld: warning: ignoring duplicate libraries: ")
751 || deployment_mismatch(line)
752 || search_path(line)
753 {
754linker_info += line;
755linker_info += "\n";
756 } else {
757*output += line;
758*output += "\n"
759}
760 });
761 } else if is_windows_gnu_ld(sess) {
762{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:762",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(762u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows GNU LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows GNU LD");
763764let mut saw_exclude_symbol = false;
765// See https://github.com/rust-lang/rust/issues/112368.
766 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
767let exclude_symbols = |line: &str| {
768line.starts_with("Warning: .drectve `-exclude-symbols:")
769 && line.ends_with("' unrecognized")
770 };
771escaped_stderr = for_each(&stderr, |line, output| {
772if exclude_symbols(line) {
773saw_exclude_symbol = true;
774linker_info += line;
775linker_info += "\n";
776 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
777linker_info += line;
778linker_info += "\n";
779 } else {
780*output += line;
781*output += "\n"
782}
783 });
784 }
785786let lint_msg = |msg| {
787emit_lint_base(
788sess,
789LINKER_MESSAGES,
790levels.linker_messages,
791None,
792LinkerOutput { inner: msg },
793 );
794 };
795let lint_info = |msg| {
796emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
797 };
798799if !escaped_stderr.is_empty() {
800// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
801escaped_stderr =
802escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
803// Windows GNU LD prints uppercase Warning
804escaped_stderr = escaped_stderr805 .strip_prefix("Warning: ")
806 .unwrap_or(&escaped_stderr)
807 .replace(": warning: ", ": ");
808lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr))
})format!("linker stderr: {escaped_stderr}"));
809 }
810if !escaped_stdout.is_empty() {
811lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout))
})format!("linker stdout: {}", escaped_stdout))
812 }
813if !linker_info.is_empty() {
814lint_info(linker_info);
815 }
816}
817818/// Create a dynamic library or executable.
819///
820/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
821/// files as well.
822fn link_natively(
823 sess: &Session,
824 archive_builder_builder: &dyn ArchiveBuilderBuilder,
825 crate_type: CrateType,
826 out_filename: &Path,
827 compiled_modules: &CompiledModules,
828 crate_info: &CrateInfo,
829 metadata: &EncodedMetadata,
830 tmpdir: &Path,
831 codegen_backend: &'static str,
832) {
833{
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:833",
"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(833u32),
::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);
834let (linker_path, flavor) = linker_and_flavor(sess);
835let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
836837// On AIX, we ship all libraries as .a big_af archive
838 // the expected format is lib<name>.a(libname.so) for the actual
839 // dynamic library. So we link to a temporary .so file to be archived
840 // at the final out_filename location
841let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
842let archive_member =
843should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
844let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
845846let mut cmd = linker_with_args(
847&linker_path,
848flavor,
849sess,
850archive_builder_builder,
851crate_type,
852tmpdir,
853temp_filename,
854compiled_modules,
855crate_info,
856metadata,
857self_contained_components,
858codegen_backend,
859 );
860861 linker::disable_localization(&mut cmd);
862863for (k, v) in sess.target.link_env.as_ref() {
864 cmd.env(k.as_ref(), v.as_ref());
865 }
866for k in sess.target.link_env_remove.as_ref() {
867 cmd.env_remove(k.as_ref());
868 }
869870for print in &sess.opts.prints {
871if print.kind == PrintKind::LinkArgs {
872let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
873 print.out.overwrite(&content, sess);
874 }
875 }
876877// May have not found libraries in the right formats.
878sess.dcx().abort_if_errors();
879880// Invoke the system linker
881{
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:881",
"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(881u32),
::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:?}");
882let unknown_arg_regex =
883Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
884let mut prog;
885loop {
886prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
887let Ok(ref output) = progelse {
888break;
889 };
890if output.status.success() {
891break;
892 }
893let mut out = output.stderr.clone();
894out.extend(&output.stdout);
895let out = String::from_utf8_lossy(&out);
896897// Check to see if the link failed with an error message that indicates it
898 // doesn't recognize the -no-pie option. If so, re-perform the link step
899 // without it. This is safe because if the linker doesn't support -no-pie
900 // then it should not default to linking executables as pie. Different
901 // versions of gcc seem to use different quotes in the error message so
902 // don't check for them.
903if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))904 && unknown_arg_regex.is_match(&out)
905 && out.contains("-no-pie")
906 && cmd.get_args().iter().any(|e| e == "-no-pie")
907 {
908{
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:908",
"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(908u32),
::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);
909{
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:909",
"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(909u32),
::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.");
910for arg in cmd.take_args() {
911if arg != "-no-pie" {
912 cmd.arg(arg);
913 }
914 }
915{
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:915",
"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(915u32),
::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:?}");
916continue;
917 }
918919// Check if linking failed with an error message that indicates the driver didn't recognize
920 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
921 // to spawn multiple instances on the happy path to do version checking, and ensures things
922 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
923 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
924if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))925 && unknown_arg_regex.is_match(&out)
926 && out.contains("-fuse-ld=lld")
927 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
928 {
929{
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:929",
"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(929u32),
::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);
930{
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:930",
"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(930u32),
::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.");
931for arg in cmd.take_args() {
932if arg.to_string_lossy() != "-fuse-ld=lld" {
933 cmd.arg(arg);
934 }
935 }
936{
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:936",
"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(936u32),
::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:?}");
937continue;
938 }
939940// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
941 // Fallback from '-static-pie' to '-static' in that case.
942if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))943 && unknown_arg_regex.is_match(&out)
944 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
945 && cmd.get_args().iter().any(|e| e == "-static-pie")
946 {
947{
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:947",
"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(947u32),
::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);
948{
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:948",
"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(948u32),
::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!(
949"Linker does not support -static-pie command line option. Retrying with -static instead."
950);
951// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
952let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
953let opts = &sess.target;
954let pre_objects = if self_contained_crt_objects {
955&opts.pre_link_objects_self_contained
956 } else {
957&opts.pre_link_objects
958 };
959let post_objects = if self_contained_crt_objects {
960&opts.post_link_objects_self_contained
961 } else {
962&opts.post_link_objects
963 };
964let get_objects = |objects: &CrtObjects, kind| {
965objects966 .get(&kind)
967 .iter()
968 .copied()
969 .flatten()
970 .map(|obj| {
971get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
972 })
973 .collect::<Vec<_>>()
974 };
975let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
976let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
977let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
978let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
979// Assume that we know insertion positions for the replacement arguments from replaced
980 // arguments, which is true for all supported targets.
981if !(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());
982if !(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());
983for arg in cmd.take_args() {
984if arg == "-static-pie" {
985// Replace the output kind.
986cmd.arg("-static");
987 } else if pre_objects_static_pie.contains(&arg) {
988// Replace the pre-link objects (replace the first and remove the rest).
989cmd.args(mem::take(&mut pre_objects_static));
990 } else if post_objects_static_pie.contains(&arg) {
991// Replace the post-link objects (replace the first and remove the rest).
992cmd.args(mem::take(&mut post_objects_static));
993 } else {
994 cmd.arg(arg);
995 }
996 }
997{
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:997",
"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(997u32),
::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:?}");
998continue;
999 }
10001001break;
1002 }
10031004match prog {
1005Ok(prog) => {
1006if !prog.status.success() {
1007let mut output = prog.stderr.clone();
1008output.extend_from_slice(&prog.stdout);
1009let escaped_output = escape_linker_output(&output, flavor);
1010let err = errors::LinkingFailed {
1011 linker_path: &linker_path,
1012 exit_status: prog.status,
1013 command: cmd,
1014escaped_output,
1015 verbose: sess.opts.verbose,
1016 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1017 };
1018sess.dcx().emit_err(err);
1019// If MSVC's `link.exe` was expected but the return code
1020 // is not a Microsoft LNK error then suggest a way to fix or
1021 // install the Visual Studio build tools.
1022if let Some(code) = prog.status.code() {
1023// All Microsoft `link.exe` linking ror codes are
1024 // four digit numbers in the range 1000 to 9999 inclusive
1025if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1026let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1027let has_linker =
1028 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1029 .is_some();
10301031sess.dcx().emit_note(errors::LinkExeUnexpectedError);
10321033// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1034 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1035const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1036if code == STATUS_STACK_BUFFER_OVERRUN {
1037sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1038 }
10391040if is_vs_installed && has_linker {
1041// the linker is broken
1042sess.dcx().emit_note(errors::RepairVSBuildTools);
1043sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1044 } else if is_vs_installed {
1045// the linker is not installed
1046sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1047 } else {
1048// visual studio is not installed
1049sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1050 }
1051 }
1052 }
10531054sess.dcx().abort_if_errors();
1055 }
10561057{
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:1057",
"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(1057u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("reporting linker output: flavor={0:?}",
flavor) as &dyn Value))])
});
} else { ; }
};info!("reporting linker output: flavor={flavor:?}");
1058report_linker_output(sess, crate_info.lint_levels, &prog.stdout, &prog.stderr);
1059 }
1060Err(e) => {
1061let linker_not_found = e.kind() == io::ErrorKind::NotFound;
10621063let err = if linker_not_found {
1064sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1065 } else {
1066sess.dcx().emit_err(errors::UnableToExeLinker {
1067linker_path,
1068 error: e,
1069 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1070 })
1071 };
10721073if sess.target.is_like_msvc && linker_not_found {
1074sess.dcx().emit_note(errors::MsvcMissingLinker);
1075sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1076sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1077 }
1078err.raise_fatal();
1079 }
1080 }
10811082match sess.split_debuginfo() {
1083// If split debug information is disabled or located in individual files
1084 // there's nothing to do here.
1085SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
10861087// If packed split-debuginfo is requested, but the final compilation
1088 // doesn't actually have any debug information, then we skip this step.
1089SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
10901091// On macOS the external `dsymutil` tool is used to create the packed
1092 // debug information. Note that this will read debug information from
1093 // the objects on the filesystem which we'll clean up later.
1094SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1095let prog = Command::new("dsymutil").arg(out_filename).output();
1096match prog {
1097Ok(prog) => {
1098if !prog.status.success() {
1099let mut output = prog.stderr.clone();
1100output.extend_from_slice(&prog.stdout);
1101sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1102 status: prog.status,
1103 output: escape_string(&output),
1104 });
1105 }
1106 }
1107Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1108 }
1109 }
11101111// On MSVC packed debug information is produced by the linker itself so
1112 // there's no need to do anything else here.
1113SplitDebuginfo::Packedif sess.target.is_like_windows => {}
11141115// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1116 //
1117 // We cannot rely on the .o paths in the executable because they may have been
1118 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1119 // the .o/.dwo paths explicitly.
1120SplitDebuginfo::Packed => {
1121link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1122 }
1123 }
11241125let strip = sess.opts.cg.strip;
11261127if sess.target.is_like_darwin {
1128let stripcmd = "rust-objcopy";
1129match (strip, crate_type) {
1130 (Strip::Debuginfo, _) => {
1131strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1132 }
11331134// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1135(
1136 Strip::Symbols,
1137 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1138 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1139 (Strip::Symbols, _) => {
1140strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1141 }
1142 (Strip::None, _) => {}
1143 }
1144 }
11451146if sess.target.is_like_solaris {
1147// Many illumos systems will have both the native 'strip' utility and
1148 // the GNU one. Use the native version explicitly and do not rely on
1149 // what's in the path.
1150 //
1151 // If cross-compiling and there is not a native version, then use
1152 // `llvm-strip` and hope.
1153let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1154match strip {
1155// Always preserve the symbol table (-x).
1156Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1157// Strip::Symbols is handled via the --strip-all linker option.
1158Strip::Symbols => {}
1159 Strip::None => {}
1160 }
1161 }
11621163if sess.target.is_like_aix {
1164// `llvm-strip` doesn't work for AIX - their strip must be used.
1165if !sess.host.is_like_aix {
1166sess.dcx().emit_warn(errors::AixStripNotUsed);
1167 }
1168let stripcmd = "/usr/bin/strip";
1169match strip {
1170 Strip::Debuginfo => {
1171// FIXME: AIX's strip utility only offers option to strip line number information.
1172strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1173 }
1174 Strip::Symbols => {
1175// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1176strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1177 }
1178 Strip::None => {}
1179 }
1180 }
11811182if should_archive {
1183let mut ab = archive_builder_builder.new_archive_builder(sess);
1184ab.add_file(temp_filename);
1185ab.build(out_filename);
1186 }
1187}
11881189fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1190let mut cmd = Command::new(util);
1191cmd.args(options);
11921193let mut new_path = sess.get_tools_search_paths(false);
1194if let Some(path) = env::var_os("PATH") {
1195new_path.extend(env::split_paths(&path));
1196 }
1197cmd.env("PATH", env::join_paths(new_path).unwrap());
11981199let prog = cmd.arg(out_filename).output();
1200match prog {
1201Ok(prog) => {
1202if !prog.status.success() {
1203let mut output = prog.stderr.clone();
1204output.extend_from_slice(&prog.stdout);
1205sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1206util,
1207 status: prog.status,
1208 output: escape_string(&output),
1209 });
1210 }
1211 }
1212Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1213 }
1214}
12151216fn escape_string(s: &[u8]) -> String {
1217match str::from_utf8(s) {
1218Ok(s) => s.to_owned(),
1219Err(_) => ::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()),
1220 }
1221}
12221223#[cfg(not(windows))]
1224fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1225escape_string(s)
1226}
12271228/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1229/// then try to convert the string from the OEM encoding.
1230#[cfg(windows)]
1231fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1232// This only applies to the actual MSVC linker.
1233if flavour != LinkerFlavor::Msvc(Lld::No) {
1234return escape_string(s);
1235 }
1236match str::from_utf8(s) {
1237Ok(s) => return s.to_owned(),
1238Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1239Some(s) => s,
1240// The string is not UTF-8 and isn't valid for the OEM code page
1241None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1242 },
1243 }
1244}
12451246/// Wrappers around the Windows API.
1247#[cfg(windows)]
1248mod win {
1249use windows::Win32::Globalization::{
1250 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1251 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1252 };
12531254/// Get the Windows system OEM code page. This is most notably the code page
1255 /// used for link.exe's output.
1256pub(super) fn oem_code_page() -> u32 {
1257unsafe {
1258let mut cp: u32 = 0;
1259// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1260 // But the API requires us to pass the data as though it's a [u16] string.
1261let len = size_of::<u32>() / size_of::<u16>();
1262let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1263let len_written = GetLocaleInfoEx(
1264 LOCALE_NAME_SYSTEM_DEFAULT,
1265 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1266Some(data),
1267 );
1268if len_written as usize == len { cp } else { CP_OEMCP }
1269 }
1270 }
1271/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1272 /// The string does not need to be null terminated.
1273 ///
1274 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1275 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1276 ///
1277 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1278 /// any invalid bytes for the expected encoding.
1279pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1280// `MultiByteToWideChar` requires a length to be a "positive integer".
1281if s.len() > isize::MAX as usize {
1282return None;
1283 }
1284// Error if the string is not valid for the expected code page.
1285let flags = MB_ERR_INVALID_CHARS;
1286// Call MultiByteToWideChar twice.
1287 // First to calculate the length then to convert the string.
1288let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1289if len > 0 {
1290let mut utf16 = vec![0; len as usize];
1291 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1292if len > 0 {
1293return utf16.get(..len as usize).map(String::from_utf16_lossy);
1294 }
1295 }
1296None
1297}
1298}
12991300fn add_sanitizer_libraries(
1301 sess: &Session,
1302 flavor: LinkerFlavor,
1303 crate_type: CrateType,
1304 linker: &mut dyn Linker,
1305) {
1306if sess.target.is_like_android {
1307// Sanitizer runtime libraries are provided dynamically on Android
1308 // targets.
1309return;
1310 }
13111312if sess.opts.unstable_opts.external_clangrt {
1313// Linking against in-tree sanitizer runtimes is disabled via
1314 // `-Z external-clangrt`
1315return;
1316 }
13171318if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1319return;
1320 }
13211322// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1323 // which should be linked to both executables and dynamic libraries.
1324 // Everywhere else the runtimes are currently distributed as static
1325 // libraries which should be linked to executables only.
1326if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1327 crate_type,
1328 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1329 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1330 {
1331return;
1332 }
13331334let sanitizer = sess.sanitizers();
1335if sanitizer.contains(SanitizerSet::ADDRESS) {
1336link_sanitizer_runtime(sess, flavor, linker, "asan");
1337 }
1338if sanitizer.contains(SanitizerSet::DATAFLOW) {
1339link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1340 }
1341if sanitizer.contains(SanitizerSet::LEAK)
1342 && !sanitizer.contains(SanitizerSet::ADDRESS)
1343 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1344 {
1345link_sanitizer_runtime(sess, flavor, linker, "lsan");
1346 }
1347if sanitizer.contains(SanitizerSet::MEMORY) {
1348link_sanitizer_runtime(sess, flavor, linker, "msan");
1349 }
1350if sanitizer.contains(SanitizerSet::THREAD) {
1351link_sanitizer_runtime(sess, flavor, linker, "tsan");
1352 }
1353if sanitizer.contains(SanitizerSet::HWADDRESS) {
1354link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1355 }
1356if sanitizer.contains(SanitizerSet::SAFESTACK) {
1357link_sanitizer_runtime(sess, flavor, linker, "safestack");
1358 }
1359if sanitizer.contains(SanitizerSet::REALTIME) {
1360link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1361 }
1362}
13631364fn link_sanitizer_runtime(
1365 sess: &Session,
1366 flavor: LinkerFlavor,
1367 linker: &mut dyn Linker,
1368 name: &str,
1369) {
1370fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1371let path = sess.target_tlib_path.dir.join(filename);
1372if path.exists() {
1373sess.target_tlib_path.dir.clone()
1374 } else {
1375 filesearch::make_target_lib_path(
1376&sess.opts.sysroot.default,
1377sess.opts.target_triple.tuple(),
1378 )
1379 }
1380 }
13811382let channel =
1383::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();
13841385if sess.target.is_like_darwin {
1386// On Apple platforms, the sanitizer is always built as a dylib, and
1387 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1388 // rpath to the library as well (the rpath should be absolute, see
1389 // PR #41352 for details).
1390let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1391let path = find_sanitizer_runtime(sess, &filename);
1392let rpath = path.to_str().expect("non-utf8 component in path");
1393linker.link_args(&["-rpath", rpath]);
1394linker.link_dylib_by_name(&filename, false, true);
1395 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1396// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1397 // compatible ASAN library.
1398linker.link_arg("/INFERASANLIBS");
1399 } else {
1400let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1401let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1402linker.link_staticlib_by_path(&path, true);
1403 }
1404}
14051406/// Returns a boolean indicating whether the specified crate should be ignored
1407/// during LTO.
1408///
1409/// Crates ignored during LTO are not lumped together in the "massive object
1410/// file" that we create and are linked in their normal rlib states. See
1411/// comments below for what crates do not participate in LTO.
1412///
1413/// It's unusual for a crate to not participate in LTO. Typically only
1414/// compiler-specific and unstable crates have a reason to not participate in
1415/// LTO.
1416pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1417// If our target enables builtin function lowering in LLVM then the
1418 // crates providing these functions don't participate in LTO (e.g.
1419 // no_builtins or compiler builtins crates).
1420!sess.target.no_builtins
1421 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1422}
14231424/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1425pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1426fn infer_from(
1427 sess: &Session,
1428 linker: Option<PathBuf>,
1429 flavor: Option<LinkerFlavor>,
1430 features: LinkerFeaturesCli,
1431 ) -> Option<(PathBuf, LinkerFlavor)> {
1432let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1433match (linker, flavor) {
1434 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1435// only the linker flavor is known; use the default linker for the selected flavor
1436(None, Some(flavor)) => Some((
1437PathBuf::from(match flavor {
1438 LinkerFlavor::Gnu(Cc::Yes, _)
1439 | LinkerFlavor::Darwin(Cc::Yes, _)
1440 | LinkerFlavor::WasmLld(Cc::Yes)
1441 | LinkerFlavor::Unix(Cc::Yes) => {
1442if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1443// On historical Solaris systems, "cc" may have
1444 // been Sun Studio, which is not flag-compatible
1445 // with "gcc". This history casts a long shadow,
1446 // and many modern illumos distributions today
1447 // ship GCC as "gcc" without also making it
1448 // available as "cc".
1449"gcc"
1450} else {
1451"cc"
1452}
1453 }
1454 LinkerFlavor::Gnu(_, Lld::Yes)
1455 | LinkerFlavor::Darwin(_, Lld::Yes)
1456 | LinkerFlavor::WasmLld(..)
1457 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1458 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1459"ld"
1460}
1461 LinkerFlavor::Msvc(..) => "link.exe",
1462 LinkerFlavor::EmCc => {
1463if falsecfg!(windows) {
1464"emcc.bat"
1465} else {
1466"emcc"
1467}
1468 }
1469 LinkerFlavor::Bpf => "bpf-linker",
1470 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1471 LinkerFlavor::Ptx => "rust-ptx-linker",
1472 }),
1473flavor,
1474 )),
1475 (Some(linker), None) => {
1476let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1477sess.dcx().emit_fatal(errors::LinkerFileStem);
1478 });
1479let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1480let flavor = adjust_flavor_to_features(flavor, features);
1481Some((linker, flavor))
1482 }
1483 (None, None) => None,
1484 }
1485 }
14861487// While linker flavors and linker features are isomorphic (and thus targets don't need to
1488 // define features separately), we use the flavor as the root piece of data and have the
1489 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1490 // both yet.
1491fn adjust_flavor_to_features(
1492 flavor: LinkerFlavor,
1493 features: LinkerFeaturesCli,
1494 ) -> LinkerFlavor {
1495// Note: a linker feature cannot be both enabled and disabled on the CLI.
1496if features.enabled.contains(LinkerFeatures::LLD) {
1497flavor.with_lld_enabled()
1498 } else if features.disabled.contains(LinkerFeatures::LLD) {
1499flavor.with_lld_disabled()
1500 } else {
1501flavor1502 }
1503 }
15041505let features = sess.opts.cg.linker_features;
15061507// linker and linker flavor specified via command line have precedence over what the target
1508 // specification specifies
1509let linker_flavor = match sess.opts.cg.linker_flavor {
1510// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1511Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1512Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1513// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1514linker_flavor => {
1515linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1516 }
1517 };
1518if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1519return ret;
1520 }
15211522if let Some(ret) = infer_from(
1523sess,
1524sess.target.linker.as_deref().map(PathBuf::from),
1525Some(sess.target.linker_flavor),
1526features,
1527 ) {
1528return ret;
1529 }
15301531::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");
1532}
15331534/// Returns a pair of boolean indicating whether we should preserve the object and
1535/// dwarf object files on the filesystem for their debug information. This is often
1536/// useful with split-dwarf like schemes.
1537fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1538// If the objects don't have debuginfo there's nothing to preserve.
1539if sess.opts.debuginfo == config::DebugInfo::None {
1540return (false, false);
1541 }
15421543match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1544// If there is no split debuginfo then do not preserve objects.
1545(SplitDebuginfo::Off, _) => (false, false),
1546// If there is packed split debuginfo, then the debuginfo in the objects
1547 // has been packaged and the objects can be deleted.
1548(SplitDebuginfo::Packed, _) => (false, false),
1549// If there is unpacked split debuginfo and the current target can not use
1550 // split dwarf, then keep objects.
1551(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1552// If there is unpacked split debuginfo and the target can use split dwarf, then
1553 // keep the object containing that debuginfo (whether that is an object file or
1554 // dwarf object file depends on the split dwarf kind).
1555(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1556 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1557 }
1558}
15591560#[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)]
1561enum RlibFlavor {
1562 Normal,
1563 StaticlibBase,
1564}
15651566fn print_native_static_libs(
1567 sess: &Session,
1568 out: &OutFileName,
1569 all_native_libs: &[NativeLib],
1570 all_rust_dylibs: &[&Path],
1571) {
1572let mut lib_args: Vec<_> = all_native_libs1573 .iter()
1574 .filter(|l| relevant_lib(sess, l))
1575 .filter_map(|lib| {
1576let name = lib.name;
1577match lib.kind {
1578 NativeLibKind::Static { bundle: Some(false), .. }
1579 | NativeLibKind::Dylib { .. }
1580 | NativeLibKind::Unspecified => {
1581let verbatim = lib.verbatim;
1582if sess.target.is_like_msvc {
1583let (prefix, suffix) = sess.staticlib_components(verbatim);
1584Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1585 } else if sess.target.linker_flavor.is_gnu() {
1586Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1587 } else {
1588Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1589 }
1590 }
1591 NativeLibKind::Framework { .. } => {
1592// ld-only syntax, since there are no frameworks in MSVC
1593Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1594 }
1595// These are included, no need to print them
1596NativeLibKind::Static { bundle: None | Some(true), .. }
1597 | NativeLibKind::LinkArg1598 | NativeLibKind::WasmImportModule1599 | NativeLibKind::RawDylib { .. } => None,
1600 }
1601 })
1602// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1603.dedup()
1604 .collect();
1605for path in all_rust_dylibs {
1606// FIXME deduplicate with add_dynamic_crate
16071608 // Just need to tell the linker about where the library lives and
1609 // what its name is
1610let parent = path.parent();
1611if let Some(dir) = parent {
1612let dir = fix_windows_verbatim_for_gcc(dir);
1613if sess.target.is_like_msvc {
1614let mut arg = String::from("/LIBPATH:");
1615 arg.push_str(&dir.display().to_string());
1616 lib_args.push(arg);
1617 } else {
1618 lib_args.push("-L".to_owned());
1619 lib_args.push(dir.display().to_string());
1620 }
1621 }
1622let stem = path.file_stem().unwrap().to_str().unwrap();
1623// Convert library file-stem into a cc -l argument.
1624let lib = if let Some(lib) = stem.strip_prefix("lib")
1625 && !sess.target.is_like_windows
1626 {
1627 lib
1628 } else {
1629 stem
1630 };
1631let path = parent.unwrap_or_else(|| Path::new(""));
1632if sess.target.is_like_msvc {
1633// When producing a dll, the MSVC linker may not actually emit a
1634 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1635 // check to see if the file is there and just omit linking to it if it's
1636 // not present.
1637let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1638if path.join(&name).exists() {
1639 lib_args.push(name);
1640 }
1641 } else {
1642 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1643 }
1644 }
16451646match out {
1647 OutFileName::Real(path) => {
1648out.overwrite(&lib_args.join(" "), sess);
1649sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1650 }
1651 OutFileName::Stdout => {
1652sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1653// Prefix for greppability
1654 // Note: This must not be translated as tools are allowed to depend on this exact string.
1655sess.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(" ")));
1656 }
1657 }
1658}
16591660fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1661let file_path = sess.target_tlib_path.dir.join(name);
1662if file_path.exists() {
1663return file_path;
1664 }
1665// Special directory with objects used only in self-contained linkage mode
1666if self_contained {
1667let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1668if file_path.exists() {
1669return file_path;
1670 }
1671 }
1672for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1673let file_path = search_path.dir.join(name);
1674if file_path.exists() {
1675return file_path;
1676 }
1677 }
1678PathBuf::from(name)
1679}
16801681fn exec_linker(
1682 sess: &Session,
1683 cmd: &Command,
1684 out_filename: &Path,
1685 flavor: LinkerFlavor,
1686 tmpdir: &Path,
1687) -> io::Result<Output> {
1688// When attempting to spawn the linker we run a risk of blowing out the
1689 // size limits for spawning a new process with respect to the arguments
1690 // we pass on the command line.
1691 //
1692 // Here we attempt to handle errors from the OS saying "your list of
1693 // arguments is too big" by reinvoking the linker again with an `@`-file
1694 // that contains all the arguments (aka 'response' files).
1695 // The theory is that this is then accepted on all linkers and the linker
1696 // will read all its options out of there instead of looking at the command line.
1697if !cmd.very_likely_to_exceed_some_spawn_limit() {
1698match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1699Ok(child) => {
1700let output = child.wait_with_output();
1701flush_linked_file(&output, out_filename)?;
1702return output;
1703 }
1704Err(ref e) if command_line_too_big(e) => {
1705{
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:1705",
"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(1705u32),
::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);
1706 }
1707Err(e) => return Err(e),
1708 }
1709 }
17101711{
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:1711",
"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(1711u32),
::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");
1712let mut cmd2 = cmd.clone();
1713let mut args = String::new();
1714for arg in cmd2.take_args() {
1715 args.push_str(
1716&Escape {
1717 arg: arg.to_str().unwrap(),
1718// Windows-style escaping for @-files is used by
1719 // - all linkers targeting MSVC-like targets, including LLD
1720 // - all LLD flavors running on Windows hosts
1721 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1722is_like_msvc: sess.target.is_like_msvc
1723 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1724 }
1725 .to_string(),
1726 );
1727 args.push('\n');
1728 }
1729let file = tmpdir.join("linker-arguments");
1730let bytes = if sess.target.is_like_msvc {
1731let mut out = Vec::with_capacity((1 + args.len()) * 2);
1732// start the stream with a UTF-16 BOM
1733for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1734// encode in little endian
1735out.push(c as u8);
1736 out.push((c >> 8) as u8);
1737 }
1738out1739 } else {
1740args.into_bytes()
1741 };
1742 fs::write(&file, &bytes)?;
1743cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1744{
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:1744",
"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(1744u32),
::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);
1745let output = cmd2.output();
1746flush_linked_file(&output, out_filename)?;
1747return output;
17481749#[cfg(not(windows))]
1750fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1751Ok(())
1752 }
17531754#[cfg(windows)]
1755fn flush_linked_file(
1756 command_output: &io::Result<Output>,
1757 out_filename: &Path,
1758 ) -> io::Result<()> {
1759// On Windows, under high I/O load, output buffers are sometimes not flushed,
1760 // even long after process exit, causing nasty, non-reproducible output bugs.
1761 //
1762 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1763 //
1764 // А full writeup of the original Chrome bug can be found at
1765 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
17661767if let &Ok(ref out) = command_output {
1768if out.status.success() {
1769if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1770 of.sync_all()?;
1771 }
1772 }
1773 }
17741775Ok(())
1776 }
17771778#[cfg(unix)]
1779fn command_line_too_big(err: &io::Error) -> bool {
1780err.raw_os_error() == Some(::libc::E2BIG)
1781 }
17821783#[cfg(windows)]
1784fn command_line_too_big(err: &io::Error) -> bool {
1785const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1786 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1787 }
17881789#[cfg(not(any(unix, windows)))]
1790fn command_line_too_big(_: &io::Error) -> bool {
1791false
1792}
17931794struct Escape<'a> {
1795 arg: &'a str,
1796 is_like_msvc: bool,
1797 }
17981799impl<'a> fmt::Displayfor Escape<'a> {
1800fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1801if self.is_like_msvc {
1802// This is "documented" at
1803 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1804 //
1805 // Unfortunately there's not a great specification of the
1806 // syntax I could find online (at least) but some local
1807 // testing showed that this seemed sufficient-ish to catch
1808 // at least a few edge cases.
1809f.write_fmt(format_args!("\""))write!(f, "\"")?;
1810for c in self.arg.chars() {
1811match c {
1812'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1813 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1814 }
1815 }
1816f.write_fmt(format_args!("\""))write!(f, "\"")?;
1817 } else {
1818// This is documented at https://linux.die.net/man/1/ld, namely:
1819 //
1820 // > Options in file are separated by whitespace. A whitespace
1821 // > character may be included in an option by surrounding the
1822 // > entire option in either single or double quotes. Any
1823 // > character (including a backslash) may be included by
1824 // > prefixing the character to be included with a backslash.
1825 //
1826 // We put an argument on each line, so all we need to do is
1827 // ensure the line is interpreted as one whole argument.
1828for c in self.arg.chars() {
1829match c {
1830'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1831 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1832 }
1833 }
1834 }
1835Ok(())
1836 }
1837 }
1838}
18391840fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1841let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1842 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1843 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1844 LinkOutputKind::DynamicPicExe1845 }
1846 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1847 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1848 LinkOutputKind::StaticPicExe1849 }
1850 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1851 (_, true, _) => LinkOutputKind::StaticDylib,
1852 (_, false, _) => LinkOutputKind::DynamicDylib,
1853 };
18541855// Adjust the output kind to target capabilities.
1856let opts = &sess.target;
1857let pic_exe_supported = opts.position_independent_executables;
1858let static_pic_exe_supported = opts.static_position_independent_executables;
1859let static_dylib_supported = opts.crt_static_allows_dylibs;
1860match kind {
1861 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1862 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1863 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1864_ => kind,
1865 }
1866}
18671868// Returns true if linker is located within sysroot
1869fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1870let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1871linker.with_extension("exe")
1872 } else {
1873linker.to_path_buf()
1874 };
1875for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1876let full_path = dir.join(&linker_with_extension);
1877// If linker comes from sysroot assume self-contained mode
1878if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1879return false;
1880 }
1881 }
1882true
1883}
18841885/// Various toolchain components used during linking are used from rustc distribution
1886/// instead of being found somewhere on the host system.
1887/// We only provide such support for a very limited number of targets.
1888fn self_contained_components(
1889 sess: &Session,
1890 crate_type: CrateType,
1891 linker: &Path,
1892) -> LinkSelfContainedComponents {
1893// Turn the backwards compatible bool values for `self_contained` into fully inferred
1894 // `LinkSelfContainedComponents`.
1895let self_contained =
1896if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1897// Emit an error if the user requested self-contained mode on the CLI but the target
1898 // explicitly refuses it.
1899if sess.target.link_self_contained.is_disabled() {
1900sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1901 }
1902self_contained1903 } else {
1904match sess.target.link_self_contained {
1905 LinkSelfContainedDefault::False => false,
1906 LinkSelfContainedDefault::True => true,
19071908 LinkSelfContainedDefault::WithComponents(components) => {
1909// For target specs with explicitly enabled components, we can return them
1910 // directly.
1911return components;
1912 }
19131914// FIXME: Find a better heuristic for "native musl toolchain is available",
1915 // based on host and linker path, for example.
1916 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1917LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1918 LinkSelfContainedDefault::InferredForMingw => {
1919sess.host == sess.target
1920 && sess.target.cfg_abi != CfgAbi::Uwp1921 && detect_self_contained_mingw(sess, linker)
1922 }
1923 }
1924 };
1925if self_contained {
1926LinkSelfContainedComponents::all()
1927 } else {
1928LinkSelfContainedComponents::empty()
1929 }
1930}
19311932/// Add pre-link object files defined by the target spec.
1933fn add_pre_link_objects(
1934 cmd: &mut dyn Linker,
1935 sess: &Session,
1936 flavor: LinkerFlavor,
1937 link_output_kind: LinkOutputKind,
1938 self_contained: bool,
1939) {
1940// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1941 // so Fuchsia has to be special-cased.
1942let opts = &sess.target;
1943let empty = Default::default();
1944let objects = if self_contained {
1945&opts.pre_link_objects_self_contained
1946 } 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, _))) {
1947&opts.pre_link_objects
1948 } else {
1949&empty1950 };
1951for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1952 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1953 }
1954}
19551956/// Add post-link object files defined by the target spec.
1957fn add_post_link_objects(
1958 cmd: &mut dyn Linker,
1959 sess: &Session,
1960 link_output_kind: LinkOutputKind,
1961 self_contained: bool,
1962) {
1963let objects = if self_contained {
1964&sess.target.post_link_objects_self_contained
1965 } else {
1966&sess.target.post_link_objects
1967 };
1968for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1969 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1970 }
1971}
19721973/// Add arbitrary "pre-link" args defined by the target spec or from command line.
1974/// FIXME: Determine where exactly these args need to be inserted.
1975fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1976if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1977cmd.verbatim_args(args.iter().map(Deref::deref));
1978 }
19791980cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1981}
19821983/// Add a link script embedded in the target, if applicable.
1984fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1985match (crate_type, &sess.target.link_script) {
1986 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1987if !sess.target.linker_flavor.is_gnu() {
1988sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1989 }
19901991let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
19921993let path = tmpdir.join(file_name);
1994if let Err(error) = fs::write(&path, script.as_ref()) {
1995sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1996 }
19971998cmd.link_arg("--script").link_arg(path);
1999 }
2000_ => {}
2001 }
2002}
20032004/// Add arbitrary "user defined" args defined from command line.
2005/// FIXME: Determine where exactly these args need to be inserted.
2006fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2007cmd.verbatim_args(&sess.opts.cg.link_args);
2008}
20092010/// Add arbitrary "late link" args defined by the target spec.
2011/// FIXME: Determine where exactly these args need to be inserted.
2012fn add_late_link_args(
2013 cmd: &mut dyn Linker,
2014 sess: &Session,
2015 flavor: LinkerFlavor,
2016 crate_type: CrateType,
2017 crate_info: &CrateInfo,
2018) {
2019let any_dynamic_crate = crate_type == CrateType::Dylib2020 || crate_type == CrateType::Sdylib2021 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2022*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2023 });
2024if any_dynamic_crate {
2025if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2026cmd.verbatim_args(args.iter().map(Deref::deref));
2027 }
2028 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2029cmd.verbatim_args(args.iter().map(Deref::deref));
2030 }
2031if let Some(args) = sess.target.late_link_args.get(&flavor) {
2032cmd.verbatim_args(args.iter().map(Deref::deref));
2033 }
2034}
20352036/// Add arbitrary "post-link" args defined by the target spec.
2037/// FIXME: Determine where exactly these args need to be inserted.
2038fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2039if let Some(args) = sess.target.post_link_args.get(&flavor) {
2040cmd.verbatim_args(args.iter().map(Deref::deref));
2041 }
2042}
20432044/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2045/// the linker.
2046///
2047/// Background: we implement rlibs as static library (archives). Linkers treat archives
2048/// differently from object files: all object files participate in linking, while archives will
2049/// only participate in linking if they can satisfy at least one undefined reference (version
2050/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2051/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2052/// can't keep them either. This causes #47384.
2053///
2054/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2055/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2056/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2057/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2058/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2059/// from removing them, and this is especially problematic for embedded programming where every
2060/// byte counts.
2061///
2062/// This method creates a synthetic object file, which contains undefined references to all symbols
2063/// that are necessary for the linking. They are only present in symbol table but not actually
2064/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2065/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2066///
2067/// There's a few internal crates in the standard library (aka libcore and
2068/// libstd) which actually have a circular dependence upon one another. This
2069/// currently arises through "weak lang items" where libcore requires things
2070/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2071/// circular dependence to work correctly we declare some of these things
2072/// in this synthetic object.
2073fn add_linked_symbol_object(
2074 cmd: &mut dyn Linker,
2075 sess: &Session,
2076 tmpdir: &Path,
2077 symbols: &[(String, SymbolExportKind)],
2078) {
2079if symbols.is_empty() {
2080return;
2081 }
20822083let Some(mut file) = super::metadata::create_object_file(sess) else {
2084return;
2085 };
20862087if file.format() == object::BinaryFormat::Coff {
2088// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2089 // so add an empty section.
2090file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
20912092// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2093 // default mangler in `object` crate.
2094file.set_mangling(object::write::Mangling::None);
2095 }
20962097if file.format() == object::BinaryFormat::MachO {
2098// Divide up the sections into sub-sections via symbols for dead code stripping.
2099 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2100 // discard on MachO targets.
2101file.set_subsections_via_symbols();
2102 }
21032104// ld64 requires a relocation to load undefined symbols, see below.
2105 // Not strictly needed if linking with lld, but might as well do it there too.
2106let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2107Some(file.add_section(
2108file.segment_name(object::write::StandardSegment::Data).to_vec(),
2109"__data".into(),
2110 object::SectionKind::Data,
2111 ))
2112 } else {
2113None2114 };
21152116for (sym, kind) in symbols.iter() {
2117let symbol = file.add_symbol(object::write::Symbol {
2118 name: sym.clone().into(),
2119 value: 0,
2120 size: 0,
2121 kind: match kind {
2122 SymbolExportKind::Text => object::SymbolKind::Text,
2123 SymbolExportKind::Data => object::SymbolKind::Data,
2124 SymbolExportKind::Tls => object::SymbolKind::Tls,
2125 },
2126 scope: object::SymbolScope::Unknown,
2127 weak: false,
2128 section: object::write::SymbolSection::Undefined,
2129 flags: object::SymbolFlags::None,
2130 });
21312132// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2133 //
2134 // Code-wise, the relevant parts of ld64 are roughly:
2135 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2136 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2137 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2138 //
2139 // 2. Read the archive table of contents (__.SYMDEF file).
2140 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2141 //
2142 // 3. Begin linking by loading "atoms" from input files.
2143 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2144 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2145 //
2146 // a. Directly specified object files (`.o`) are parsed immediately.
2147 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2148 //
2149 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2150 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2151 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2152 //
2153 // - Relocations/fixups are atoms.
2154 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2155 //
2156 // b. Archives are not parsed yet.
2157 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2158 //
2159 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2160 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2161 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2162 //
2163 // All of the steps above are fairly similar to other linkers, except that **it completely
2164 // ignores undefined symbols**.
2165 //
2166 // So to make this trick work on ld64, we need to do something else to load the relevant
2167 // object files. We do this by inserting a relocation (fixup) for each symbol.
2168if let Some(section) = ld64_section_helper {
2169 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2170 .expect("failed adding relocation");
2171 }
2172 }
21732174let path = tmpdir.join("symbols.o");
2175let result = std::fs::write(&path, file.write().unwrap());
2176if let Err(error) = result {
2177sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2178 }
2179cmd.add_object(&path);
2180}
21812182/// Add object files containing code from the current crate.
2183fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2184for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
2185 cmd.add_object(obj);
2186 }
2187}
21882189/// Add object files for allocator code linked once for the whole crate tree.
2190fn add_local_crate_allocator_objects(
2191 cmd: &mut dyn Linker,
2192 compiled_modules: &CompiledModules,
2193 crate_info: &CrateInfo,
2194 crate_type: CrateType,
2195) {
2196if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type) {
2197if let Some(obj) =
2198compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref())
2199 {
2200cmd.add_object(obj);
2201 }
2202 }
2203}
22042205/// Add object files containing metadata for the current crate.
2206fn add_local_crate_metadata_objects(
2207 cmd: &mut dyn Linker,
2208 sess: &Session,
2209 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2210 crate_type: CrateType,
2211 tmpdir: &Path,
2212 crate_info: &CrateInfo,
2213 metadata: &EncodedMetadata,
2214) {
2215// When linking a dynamic library, we put the metadata into a section of the
2216 // executable. This metadata is in a separate object file from the main
2217 // object file, so we create and link it in here.
2218if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2219let data = archive_builder_builder.create_dylib_metadata_wrapper(
2220sess,
2221&metadata,
2222&crate_info.metadata_symbol,
2223 );
2224let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
22252226cmd.add_object(&obj);
2227 }
2228}
22292230/// Add sysroot and other globally set directories to the directory search list.
2231fn add_library_search_dirs(
2232 cmd: &mut dyn Linker,
2233 sess: &Session,
2234 self_contained_components: LinkSelfContainedComponents,
2235 apple_sdk_root: Option<&Path>,
2236) {
2237if !sess.opts.unstable_opts.link_native_libraries {
2238return;
2239 }
22402241let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2242let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2243if is_framework {
2244cmd.framework_path(dir);
2245 } else {
2246cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2247 }
2248 ControlFlow::<()>::Continue(())
2249 });
2250}
22512252/// Add options making relocation sections in the produced ELF files read-only
2253/// and suppressing lazy binding.
2254fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2255match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2256 RelroLevel::Full => cmd.full_relro(),
2257 RelroLevel::Partial => cmd.partial_relro(),
2258 RelroLevel::Off => cmd.no_relro(),
2259 RelroLevel::None => {}
2260 }
2261}
22622263/// Add library search paths used at runtime by dynamic linkers.
2264fn add_rpath_args(
2265 cmd: &mut dyn Linker,
2266 sess: &Session,
2267 crate_info: &CrateInfo,
2268 out_filename: &Path,
2269) {
2270if !sess.target.has_rpath {
2271return;
2272 }
22732274// FIXME (#2397): At some point we want to rpath our guesses as to
2275 // where extern libraries might live, based on the
2276 // add_lib_search_paths
2277if sess.opts.cg.rpath {
2278let libs = crate_info2279 .used_crates
2280 .iter()
2281 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2282 .collect::<Vec<_>>();
2283let rpath_config = RPathConfig {
2284 libs: &*libs,
2285 out_filename: out_filename.to_path_buf(),
2286 is_like_darwin: sess.target.is_like_darwin,
2287 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2288 };
2289cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2290 }
2291}
22922293fn add_c_staticlib_symbols(
2294 sess: &Session,
2295 lib: &NativeLib,
2296 out: &mut Vec<(String, SymbolExportKind)>,
2297) -> io::Result<()> {
2298let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
22992300let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
23012302let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2303 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23042305for member in archive.members() {
2306let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23072308let data = member
2309 .data(&*archive_map)
2310 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23112312// clang LTO: raw LLVM bitcode
2313if data.starts_with(b"BC\xc0\xde") {
2314return Err(io::Error::new(
2315 io::ErrorKind::InvalidData,
2316"LLVM bitcode object in C static library (LTO not supported)",
2317 ));
2318 }
23192320let object = object::File::parse(&*data)
2321 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23222323// gcc / clang ELF / Mach-O LTO
2324if object.sections().any(|s| {
2325 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2326 }) {
2327return Err(io::Error::new(
2328 io::ErrorKind::InvalidData,
2329"LTO object in C static library is not supported",
2330 ));
2331 }
23322333for symbol in object.symbols() {
2334if symbol.scope() != object::SymbolScope::Dynamic {
2335continue;
2336 }
23372338let name = match symbol.name() {
2339Ok(n) => n,
2340Err(_) => continue,
2341 };
23422343let export_kind = match symbol.kind() {
2344 object::SymbolKind::Text => SymbolExportKind::Text,
2345 object::SymbolKind::Data => SymbolExportKind::Data,
2346_ => continue,
2347 };
23482349// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2350 // Need to be resolved.
2351out.push((name.to_string(), export_kind));
2352 }
2353 }
23542355Ok(())
2356}
23572358/// Produce the linker command line containing linker path and arguments.
2359///
2360/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2361/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2362/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2363/// to the linking process as a whole.
2364/// Order-independent options may still override each other in order-dependent fashion,
2365/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2366fn linker_with_args(
2367 path: &Path,
2368 flavor: LinkerFlavor,
2369 sess: &Session,
2370 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2371 crate_type: CrateType,
2372 tmpdir: &Path,
2373 out_filename: &Path,
2374 compiled_modules: &CompiledModules,
2375 crate_info: &CrateInfo,
2376 metadata: &EncodedMetadata,
2377 self_contained_components: LinkSelfContainedComponents,
2378 codegen_backend: &'static str,
2379) -> Command {
2380let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2381let cmd = &mut *super::linker::get_linker(
2382sess,
2383path,
2384flavor,
2385self_contained_components.are_any_components_enabled(),
2386&crate_info.target_cpu,
2387codegen_backend,
2388 );
2389let link_output_kind = link_output_kind(sess, crate_type);
23902391let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
23922393if crate_type == CrateType::Cdylib {
2394let mut seen = FxHashSet::default();
23952396for lib in &crate_info.used_libraries {
2397if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2398 && seen.insert((lib.name, lib.verbatim))
2399 {
2400if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2401 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2402"failed to process C static library `{}`: {}",
2403 lib.name, err
2404 ));
2405 }
2406 }
2407 }
2408 }
24092410// ------------ Early order-dependent options ------------
24112412 // If we're building something like a dynamic library then some platforms
2413 // need to make sure that all symbols are exported correctly from the
2414 // dynamic library.
2415 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2416 // at least on some platforms (e.g. windows-gnu).
2417cmd.export_symbols(tmpdir, crate_type, &export_symbols);
24182419// Can be used for adding custom CRT objects or overriding order-dependent options above.
2420 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2421 // introduce a target spec option for order-independent linker options and migrate built-in
2422 // specs to it.
2423add_pre_link_args(cmd, sess, flavor);
24242425// ------------ Object code and libraries, order-dependent ------------
24262427 // Pre-link CRT objects.
2428add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
24292430add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
24312432// Sanitizer libraries.
2433add_sanitizer_libraries(sess, flavor, crate_type, cmd);
24342435// Object code from the current crate.
2436 // Take careful note of the ordering of the arguments we pass to the linker
2437 // here. Linkers will assume that things on the left depend on things to the
2438 // right. Things on the right cannot depend on things on the left. This is
2439 // all formally implemented in terms of resolving symbols (libs on the right
2440 // resolve unknown symbols of libs on the left, but not vice versa).
2441 //
2442 // For this reason, we have organized the arguments we pass to the linker as
2443 // such:
2444 //
2445 // 1. The local object that LLVM just generated
2446 // 2. Local native libraries
2447 // 3. Upstream rust libraries
2448 // 4. Upstream native libraries
2449 //
2450 // The rationale behind this ordering is that those items lower down in the
2451 // list can't depend on items higher up in the list. For example nothing can
2452 // depend on what we just generated (e.g., that'd be a circular dependency).
2453 // Upstream rust libraries are not supposed to depend on our local native
2454 // libraries as that would violate the structure of the DAG, in that
2455 // scenario they are required to link to them as well in a shared fashion.
2456 //
2457 // Note that upstream rust libraries may contain native dependencies as
2458 // well, but they also can't depend on what we just started to add to the
2459 // link line. And finally upstream native libraries can't depend on anything
2460 // in this DAG so far because they can only depend on other native libraries
2461 // and such dependencies are also required to be specified.
2462add_local_crate_regular_objects(cmd, compiled_modules);
2463add_local_crate_metadata_objects(
2464cmd,
2465sess,
2466archive_builder_builder,
2467crate_type,
2468tmpdir,
2469crate_info,
2470metadata,
2471 );
2472add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
24732474// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2475 // at the point at which they are specified on the command line.
2476 // Must be passed before any (dynamic) libraries to have effect on them.
2477 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2478 // so it will ignore unreferenced ELF sections from relocatable objects.
2479 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2480 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2481 // and move this option back to the top.
2482cmd.add_as_needed();
24832484// Local native libraries of all kinds.
2485add_local_native_libraries(
2486cmd,
2487sess,
2488archive_builder_builder,
2489crate_info,
2490tmpdir,
2491link_output_kind,
2492 );
24932494// Upstream rust crates and their non-dynamic native libraries.
2495add_upstream_rust_crates(
2496cmd,
2497sess,
2498archive_builder_builder,
2499crate_info,
2500crate_type,
2501tmpdir,
2502link_output_kind,
2503 );
25042505// Dynamic native libraries from upstream crates.
2506add_upstream_native_libraries(
2507cmd,
2508sess,
2509archive_builder_builder,
2510crate_info,
2511tmpdir,
2512link_output_kind,
2513 );
25142515// Raw-dylibs from all crates.
2516let raw_dylib_dir = tmpdir.join("raw-dylibs");
2517if sess.target.binary_format == BinaryFormat::Elf {
2518// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2519 // instead we need to pass them via -l. To find the stub, we need to add
2520 // the directory of the stub to the linker search path.
2521 // We make an extra directory for this to avoid polluting the search path.
2522if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2523sess.dcx().emit_fatal(errors::CreateTempDir { error })
2524 }
2525cmd.include_path(&raw_dylib_dir);
2526 }
25272528// Link with the import library generated for any raw-dylib functions.
2529if sess.target.is_like_windows {
2530for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2531 sess,
2532 archive_builder_builder,
2533 crate_info.used_libraries.iter(),
2534 tmpdir,
2535true,
2536 ) {
2537 cmd.add_object(&output_path);
2538 }
2539 } else {
2540for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2541 sess,
2542 crate_info.used_libraries.iter(),
2543&raw_dylib_dir,
2544 ) {
2545// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2546cmd.link_dylib_by_name(&link_path, true, as_needed);
2547 }
2548 }
2549// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2550 // they are used within inlined functions or instantiated generic functions. We do this *after*
2551 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2552 // by the linker.
2553let dependency_linkage = crate_info2554 .dependency_formats
2555 .get(&crate_type)
2556 .expect("failed to find crate type in dependency format list");
25572558// We sort the libraries below
2559#[allow(rustc::potential_query_instability)]
2560let mut native_libraries_from_nonstatics = crate_info2561 .native_libraries
2562 .iter()
2563 .filter_map(|(&cnum, libraries)| {
2564if sess.target.is_like_windows {
2565 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2566 } else {
2567Some(libraries)
2568 }
2569 })
2570 .flatten()
2571 .collect::<Vec<_>>();
2572native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
25732574if sess.target.is_like_windows {
2575for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2576 sess,
2577 archive_builder_builder,
2578 native_libraries_from_nonstatics,
2579 tmpdir,
2580false,
2581 ) {
2582 cmd.add_object(&output_path);
2583 }
2584 } else {
2585for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2586 sess,
2587 native_libraries_from_nonstatics,
2588&raw_dylib_dir,
2589 ) {
2590// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2591cmd.link_dylib_by_name(&link_path, true, as_needed);
2592 }
2593 }
25942595// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2596 // command line shorter, reset it to default here before adding more libraries.
2597cmd.reset_per_library_state();
25982599// FIXME: Built-in target specs occasionally use this for linking system libraries,
2600 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2601 // and remove the option.
2602add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
26032604// ------------ Arbitrary order-independent options ------------
26052606 // Add order-independent options determined by rustc from its compiler options,
2607 // target properties and source code.
2608add_order_independent_options(
2609cmd,
2610sess,
2611link_output_kind,
2612self_contained_components,
2613flavor,
2614crate_type,
2615crate_info,
2616out_filename,
2617tmpdir,
2618 );
26192620// Can be used for arbitrary order-independent options.
2621 // In practice may also be occasionally used for linking native libraries.
2622 // Passed after compiler-generated options to support manual overriding when necessary.
2623add_user_defined_link_args(cmd, sess);
26242625// ------------ Builtin configurable linker scripts ------------
2626 // The user's link args should be able to overwrite symbols in the compiler's
2627 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2628 // to work correctly, the user needs to be able to specify linker arguments like
2629 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2630add_link_script(cmd, sess, tmpdir, crate_type);
26312632// ------------ Object code and libraries, order-dependent ------------
26332634 // Post-link CRT objects.
2635add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
26362637// ------------ Late order-dependent options ------------
26382639 // Doesn't really make sense.
2640 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2641 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2642 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2643add_post_link_args(cmd, sess, flavor);
26442645cmd.take_cmd()
2646}
26472648fn add_order_independent_options(
2649 cmd: &mut dyn Linker,
2650 sess: &Session,
2651 link_output_kind: LinkOutputKind,
2652 self_contained_components: LinkSelfContainedComponents,
2653 flavor: LinkerFlavor,
2654 crate_type: CrateType,
2655 crate_info: &CrateInfo,
2656 out_filename: &Path,
2657 tmpdir: &Path,
2658) {
2659// Take care of the flavors and CLI options requesting the `lld` linker.
2660add_lld_args(cmd, sess, flavor, self_contained_components);
26612662add_apple_link_args(cmd, sess, flavor);
26632664let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
26652666if sess.target.os == Os::Fuchsia2667 && crate_type == CrateType::Executable2668 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2669 {
2670let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2671cmd.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"));
2672 }
26732674if sess.target.eh_frame_header {
2675cmd.add_eh_frame_header();
2676 }
26772678// Make the binary compatible with data execution prevention schemes.
2679cmd.add_no_exec();
26802681if self_contained_components.is_crt_objects_enabled() {
2682cmd.no_crt_objects();
2683 }
26842685if sess.target.os == Os::Emscripten {
2686cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2687"-fwasm-exceptions"
2688} else if sess.panic_strategy().unwinds() {
2689"-sDISABLE_EXCEPTION_CATCHING=0"
2690} else {
2691"-sDISABLE_EXCEPTION_CATCHING=1"
2692});
2693 }
26942695if flavor == LinkerFlavor::Llbc {
2696cmd.link_args(&[
2697"--target",
2698&versioned_llvm_target(sess),
2699"--target-cpu",
2700&crate_info.target_cpu,
2701 ]);
2702if crate_info.target_features.len() > 0 {
2703cmd.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(",")));
2704 }
2705 } else if flavor == LinkerFlavor::Ptx {
2706cmd.link_args(&["--fallback-arch", &crate_info.target_cpu]);
2707 } else if flavor == LinkerFlavor::Bpf {
2708cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2709if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2710 .into_iter()
2711 .find(|feat| !feat.is_empty())
2712 {
2713cmd.link_args(&["--cpu-features", feat]);
2714 }
2715 }
27162717cmd.linker_plugin_lto();
27182719add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
27202721cmd.output_filename(out_filename);
27222723if crate_type == CrateType::Executable2724 && sess.target.is_like_windows
2725 && let Some(s) = &crate_info.windows_subsystem
2726 {
2727cmd.windows_subsystem(*s);
2728 }
27292730// Try to strip as much out of the generated object by removing unused
2731 // sections if possible. See more comments in linker.rs
2732if !sess.link_dead_code() {
2733// If PGO is enabled sometimes gc_sections will remove the profile data section
2734 // as it appears to be unused. This can then cause the PGO profile file to lose
2735 // some functions. If we are generating a profile we shouldn't strip those metadata
2736 // sections to ensure we have all the data for PGO.
2737let keep_metadata =
2738crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2739cmd.gc_sections(keep_metadata);
2740 }
27412742cmd.set_output_kind(link_output_kind, crate_type, out_filename);
27432744add_relro_args(cmd, sess);
27452746// Pass optimization flags down to the linker.
2747cmd.optimize();
27482749// Gather the set of NatVis files, if any, and write them out to a temp directory.
2750let natvis_visualizers = collect_natvis_visualizers(
2751tmpdir,
2752sess,
2753&crate_info.local_crate_name,
2754&crate_info.natvis_debugger_visualizers,
2755 );
27562757// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2758cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
27592760// We want to prevent the compiler from accidentally leaking in any system libraries,
2761 // so by default we tell linkers not to link to any default libraries.
2762if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2763cmd.no_default_libraries();
2764 }
27652766if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2767cmd.pgo_gen();
2768 }
27692770if sess.opts.unstable_opts.instrument_mcount {
2771cmd.enable_profiling();
2772 }
27732774if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2775cmd.control_flow_guard();
2776 }
27772778// OBJECT-FILES-NO, AUDIT-ORDER
2779if sess.opts.unstable_opts.ehcont_guard {
2780cmd.ehcont_guard();
2781 }
27822783add_rpath_args(cmd, sess, crate_info, out_filename);
2784}
27852786// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2787fn collect_natvis_visualizers(
2788 tmpdir: &Path,
2789 sess: &Session,
2790 crate_name: &Symbol,
2791 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2792) -> Vec<PathBuf> {
2793let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
27942795for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2796let 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));
27972798match fs::write(&visualizer_out_file, &visualizer.src) {
2799Ok(()) => {
2800 visualizer_paths.push(visualizer_out_file);
2801 }
2802Err(error) => {
2803 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2804 path: visualizer_out_file,
2805 error,
2806 });
2807 }
2808 };
2809 }
2810visualizer_paths2811}
28122813fn add_native_libs_from_crate(
2814 cmd: &mut dyn Linker,
2815 sess: &Session,
2816 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2817 crate_info: &CrateInfo,
2818 tmpdir: &Path,
2819 bundled_libs: &FxIndexSet<Symbol>,
2820 cnum: CrateNum,
2821 link_static: bool,
2822 link_dynamic: bool,
2823 link_output_kind: LinkOutputKind,
2824) {
2825if !sess.opts.unstable_opts.link_native_libraries {
2826// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2827 // external build system already has the native dependencies defined, and it
2828 // will provide them to the linker itself.
2829return;
2830 }
28312832if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2833// If rlib contains native libs as archives, unpack them to tmpdir.
2834let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2835archive_builder_builder2836 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2837 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2838 }
28392840let native_libs = match cnum {
2841LOCAL_CRATE => &crate_info.used_libraries,
2842_ => &crate_info.native_libraries[&cnum],
2843 };
28442845let mut last = (None, NativeLibKind::Unspecified, false);
2846for lib in native_libs {
2847if !relevant_lib(sess, lib) {
2848continue;
2849 }
28502851// Skip if this library is the same as the last.
2852last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2853continue;
2854 } else {
2855 (Some(lib.name), lib.kind, lib.verbatim)
2856 };
28572858let name = lib.name.as_str();
2859let verbatim = lib.verbatim;
2860match lib.kind {
2861 NativeLibKind::Static { bundle, whole_archive, .. } => {
2862if link_static {
2863let bundle = bundle.unwrap_or(true);
2864let whole_archive = whole_archive == Some(true);
2865if bundle && cnum != LOCAL_CRATE {
2866if let Some(filename) = lib.filename {
2867// If rlib contains native libs as archives, they are unpacked to tmpdir.
2868let path = tmpdir.join(filename.as_str());
2869 cmd.link_staticlib_by_path(&path, whole_archive);
2870 }
2871 } else {
2872 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2873 }
2874 }
2875 }
2876 NativeLibKind::Dylib { as_needed } => {
2877if link_dynamic {
2878 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2879 }
2880 }
2881 NativeLibKind::Unspecified => {
2882// If we are generating a static binary, prefer static library when the
2883 // link kind is unspecified.
2884if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2885if link_static {
2886 cmd.link_staticlib_by_name(name, verbatim, false);
2887 }
2888 } else if link_dynamic {
2889 cmd.link_dylib_by_name(name, verbatim, true);
2890 }
2891 }
2892 NativeLibKind::Framework { as_needed } => {
2893if link_dynamic {
2894 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2895 }
2896 }
2897 NativeLibKind::RawDylib { as_needed: _ } => {
2898// Handled separately in `linker_with_args`.
2899}
2900 NativeLibKind::WasmImportModule => {}
2901 NativeLibKind::LinkArg => {
2902if link_static {
2903if verbatim {
2904 cmd.verbatim_arg(name);
2905 } else {
2906 cmd.link_arg(name);
2907 }
2908 }
2909 }
2910 }
2911 }
2912}
29132914fn add_local_native_libraries(
2915 cmd: &mut dyn Linker,
2916 sess: &Session,
2917 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2918 crate_info: &CrateInfo,
2919 tmpdir: &Path,
2920 link_output_kind: LinkOutputKind,
2921) {
2922// All static and dynamic native library dependencies are linked to the local crate.
2923let link_static = true;
2924let link_dynamic = true;
2925add_native_libs_from_crate(
2926cmd,
2927sess,
2928archive_builder_builder,
2929crate_info,
2930tmpdir,
2931&Default::default(),
2932LOCAL_CRATE,
2933link_static,
2934link_dynamic,
2935link_output_kind,
2936 );
2937}
29382939fn add_upstream_rust_crates(
2940 cmd: &mut dyn Linker,
2941 sess: &Session,
2942 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2943 crate_info: &CrateInfo,
2944 crate_type: CrateType,
2945 tmpdir: &Path,
2946 link_output_kind: LinkOutputKind,
2947) {
2948// All of the heavy lifting has previously been accomplished by the
2949 // dependency_format module of the compiler. This is just crawling the
2950 // output of that module, adding crates as necessary.
2951 //
2952 // Linking to a rlib involves just passing it to the linker (the linker
2953 // will slurp up the object files inside), and linking to a dynamic library
2954 // involves just passing the right -l flag.
2955let data = crate_info2956 .dependency_formats
2957 .get(&crate_type)
2958 .expect("failed to find crate type in dependency format list");
29592960if sess.target.is_like_aix {
2961// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
2962 // the dependency name when outputting a shared library. Thus, `ld` will
2963 // use the full path to shared libraries as the dependency if passed it
2964 // by default unless `noipath` is passed.
2965 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
2966cmd.link_or_cc_arg("-bnoipath");
2967 }
29682969for &cnum in &crate_info.used_crates {
2970// We may not pass all crates through to the linker. Some crates may appear statically in
2971 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2972 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2973 // Even if they were already included into a dylib
2974 // (e.g. `libstd` when `-C prefer-dynamic` is used).
2975let linkage = data[cnum];
2976let link_static_crate = linkage == Linkage::Static
2977 || linkage == Linkage::IncludedFromDylib
2978 && (crate_info.compiler_builtins == Some(cnum)
2979 || crate_info.profiler_runtime == Some(cnum));
29802981let mut bundled_libs = Default::default();
2982match linkage {
2983 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2984if link_static_crate {
2985 bundled_libs = crate_info.native_libraries[&cnum]
2986 .iter()
2987 .filter_map(|lib| lib.filename)
2988 .collect();
2989 add_static_crate(
2990 cmd,
2991 sess,
2992 archive_builder_builder,
2993 crate_info,
2994 tmpdir,
2995 cnum,
2996&bundled_libs,
2997 );
2998 }
2999 }
3000 Linkage::Dynamic => {
3001let src = &crate_info.used_crate_source[&cnum];
3002 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3003 }
3004 }
30053006// Static libraries are linked for a subset of linked upstream crates.
3007 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3008 // because the rlib is just an archive.
3009 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3010 // the native library because it is already linked into the dylib, and even if
3011 // inline/const/generic functions from the dylib can refer to symbols from the native
3012 // library, those symbols should be exported and available from the dylib anyway.
3013 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3014let link_static = link_static_crate;
3015// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3016let link_dynamic = false;
3017 add_native_libs_from_crate(
3018 cmd,
3019 sess,
3020 archive_builder_builder,
3021 crate_info,
3022 tmpdir,
3023&bundled_libs,
3024 cnum,
3025 link_static,
3026 link_dynamic,
3027 link_output_kind,
3028 );
3029 }
3030}
30313032fn add_upstream_native_libraries(
3033 cmd: &mut dyn Linker,
3034 sess: &Session,
3035 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3036 crate_info: &CrateInfo,
3037 tmpdir: &Path,
3038 link_output_kind: LinkOutputKind,
3039) {
3040for &cnum in &crate_info.used_crates {
3041// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3042 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3043 // are linked together with their respective upstream crates, and in their originally
3044 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3045 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3046let link_static = false;
3047// Dynamic libraries are linked for all linked upstream crates.
3048 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3049 // because the rlib is just an archive.
3050 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3051 // the native library too because inline/const/generic functions from the dylib can refer
3052 // to symbols from the native library, so the native library providing those symbols should
3053 // be available when linking our final binary.
3054let link_dynamic = true;
3055 add_native_libs_from_crate(
3056 cmd,
3057 sess,
3058 archive_builder_builder,
3059 crate_info,
3060 tmpdir,
3061&Default::default(),
3062 cnum,
3063 link_static,
3064 link_dynamic,
3065 link_output_kind,
3066 );
3067 }
3068}
30693070// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3071// to be relative to the sysroot directory, which may be a relative path specified by the user.
3072//
3073// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3074// linker command line can be non-deterministic due to the paths including the current working
3075// directory. The linker command line needs to be deterministic since it appears inside the PDB
3076// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3077//
3078// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3079fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3080let sysroot_lib_path = &sess.target_tlib_path.dir;
3081let canonical_sysroot_lib_path =
3082 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
30833084let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3085if canonical_lib_dir == canonical_sysroot_lib_path {
3086// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3087sysroot_lib_path.clone()
3088 } else {
3089fix_windows_verbatim_for_gcc(lib_dir)
3090 }
3091}
30923093fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3094if let Some(dir) = path.parent() {
3095let file_name = path.file_name().expect("library path has no file name component");
3096rehome_sysroot_lib_dir(sess, dir).join(file_name)
3097 } else {
3098fix_windows_verbatim_for_gcc(path)
3099 }
3100}
31013102// Adds the static "rlib" versions of all crates to the command line.
3103// There's a bit of magic which happens here specifically related to LTO,
3104// namely that we remove upstream object files.
3105//
3106// When performing LTO, almost(*) all of the bytecode from the upstream
3107// libraries has already been included in our object file output. As a
3108// result we need to remove the object files in the upstream libraries so
3109// the linker doesn't try to include them twice (or whine about duplicate
3110// symbols). We must continue to include the rest of the rlib, however, as
3111// it may contain static native libraries which must be linked in.
3112//
3113// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3114// their bytecode wasn't included. The object files in those libraries must
3115// still be passed to the linker.
3116//
3117// Note, however, that if we're not doing LTO we can just pass the rlib
3118// blindly to the linker (fast) because it's fine if it's not actually
3119// included as we're at the end of the dependency chain.
3120fn add_static_crate(
3121 cmd: &mut dyn Linker,
3122 sess: &Session,
3123 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3124 crate_info: &CrateInfo,
3125 tmpdir: &Path,
3126 cnum: CrateNum,
3127 bundled_lib_file_names: &FxIndexSet<Symbol>,
3128) {
3129let src = &crate_info.used_crate_source[&cnum];
3130let cratepath = src.rlib.as_ref().unwrap();
31313132let mut link_upstream =
3133 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
31343135if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3136 {
3137link_upstream(cratepath);
3138return;
3139 }
31403141let dst = tmpdir.join(cratepath.file_name().unwrap());
3142let name = cratepath.file_name().unwrap().to_str().unwrap();
3143let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3144let bundled_lib_file_names = bundled_lib_file_names.clone();
31453146sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3147let canonical_name = name.replace('-', "_");
3148let upstream_rust_objects_already_included =
3149are_upstream_rust_objects_already_included(sess);
3150let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
31513152let mut archive = archive_builder_builder.new_archive_builder(sess);
3153if let Err(error) = archive.add_archive(
3154cratepath,
3155Box::new(move |f| {
3156if f == METADATA_FILENAME {
3157return true;
3158 }
31593160let canonical = f.replace('-', "_");
31613162let is_rust_object =
3163canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
31643165// If we're performing LTO and this is a rust-generated object
3166 // file, then we don't need the object file as it's part of the
3167 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3168 // though, so we let that object file slide.
3169if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3170return true;
3171 }
31723173// We skip native libraries because:
3174 // 1. This native libraries won't be used from the generated rlib,
3175 // so we can throw them away to avoid the copying work.
3176 // 2. We can't allow it to be a single remaining entry in archive
3177 // as some linkers may complain on that.
3178if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3179return true;
3180 }
31813182false
3183}),
3184 ) {
3185sess.dcx()
3186 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3187 }
3188if archive.build(&dst) {
3189link_upstream(&dst);
3190 }
3191 });
3192}
31933194// Same thing as above, but for dynamic crates instead of static crates.
3195fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3196cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3197}
31983199fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3200match lib.cfg {
3201Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3202None => true,
3203 }
3204}
32053206pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3207match sess.lto() {
3208 config::Lto::Fat => true,
3209 config::Lto::Thin => {
3210// If we defer LTO to the linker, we haven't run LTO ourselves, so
3211 // any upstream object files have not been copied yet.
3212!sess.opts.cg.linker_plugin_lto.enabled()
3213 }
3214 config::Lto::No | config::Lto::ThinLocal => false,
3215 }
3216}
32173218/// We need to communicate five things to the linker on Apple/Darwin targets:
3219/// - The architecture.
3220/// - The operating system (and that it's an Apple platform).
3221/// - The environment.
3222/// - The deployment target.
3223/// - The SDK version.
3224fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3225if !sess.target.is_like_darwin {
3226return;
3227 }
3228let LinkerFlavor::Darwin(cc, _) = flavorelse {
3229return;
3230 };
32313232// `sess.target.arch` (`target_arch`) is not detailed enough.
3233let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3234let target_os = &sess.target.os;
3235let target_env = &sess.target.env;
32363237// The architecture name to forward to the linker.
3238 //
3239 // Supported architecture names can be found in the source:
3240 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3241 //
3242 // Intentionally verbose to ensure that the list always matches correctly
3243 // with the list in the source above.
3244let ld64_arch = match llvm_arch {
3245"armv7k" => "armv7k",
3246"armv7s" => "armv7s",
3247"arm64" => "arm64",
3248"arm64e" => "arm64e",
3249"arm64_32" => "arm64_32",
3250// ld64 doesn't understand i686, so fall back to i386 instead.
3251 //
3252 // Same story when linking with cc, since that ends up invoking ld64.
3253"i386" | "i686" => "i386",
3254"x86_64" => "x86_64",
3255"x86_64h" => "x86_64h",
3256_ => ::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),
3257 };
32583259if cc == Cc::No {
3260// From the man page for ld64 (`man ld`):
3261 // > The linker accepts universal (multiple-architecture) input files,
3262 // > but always creates a "thin" (single-architecture), standard
3263 // > Mach-O output file. The architecture for the output file is
3264 // > specified using the -arch option.
3265 //
3266 // The linker has heuristics to determine the desired architecture,
3267 // but to be safe, and to avoid a warning, we set the architecture
3268 // explicitly.
3269cmd.link_args(&["-arch", ld64_arch]);
32703271// Man page says that ld64 supports the following platform names:
3272 // > - macos
3273 // > - ios
3274 // > - tvos
3275 // > - watchos
3276 // > - bridgeos
3277 // > - visionos
3278 // > - xros
3279 // > - mac-catalyst
3280 // > - ios-simulator
3281 // > - tvos-simulator
3282 // > - watchos-simulator
3283 // > - visionos-simulator
3284 // > - xros-simulator
3285 // > - driverkit
3286let platform_name = match (target_os, target_env) {
3287 (os, Env::Unspecified) => os.desc(),
3288 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3289 (Os::IOs, Env::Sim) => "ios-simulator",
3290 (Os::TvOs, Env::Sim) => "tvos-simulator",
3291 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3292 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3293_ => ::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}"),
3294 };
32953296let min_version = sess.apple_deployment_target().fmt_full().to_string();
32973298// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3299 // - By dyld to give extra warnings and errors, see e.g.:
3300 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3301 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3302 // - By system frameworks to change certain behaviour. For example, the default value of
3303 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3304 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3305 //
3306 // We do not currently know the actual SDK version though, so we have a few options:
3307 // 1. Use the minimum version supported by rustc.
3308 // 2. Use the same as the deployment target.
3309 // 3. Use an arbitrary recent version.
3310 // 4. Omit the version.
3311 //
3312 // The first option is too low / too conservative, and means that users will not get the
3313 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3314 //
3315 // The second option is similarly conservative, and also wrong since if the user specified a
3316 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3317 // make invalid assumptions about the capabilities of the binary.
3318 //
3319 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3320 // version, and is also wrong for similar reasons as above.
3321 //
3322 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3323 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3324 // it as 0.0, which is again too low/conservative.
3325 //
3326 // Currently, we lie about the SDK version, and choose the second option.
3327 //
3328 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3329 // <https://github.com/rust-lang/rust/issues/129432>
3330let sdk_version = &*min_version;
33313332// From the man page for ld64 (`man ld`):
3333 // > This is set to indicate the platform, oldest supported version of
3334 // > that platform that output is to be used on, and the SDK that the
3335 // > output was built against.
3336 //
3337 // Like with `-arch`, the linker can figure out the platform versions
3338 // itself from the binaries being linked, but to be safe, we specify
3339 // the desired versions here explicitly.
3340cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3341 } else {
3342// cc == Cc::Yes
3343 //
3344 // We'd _like_ to use `-target` everywhere, since that can uniquely
3345 // communicate all the required details except for the SDK version
3346 // (which is read by Clang itself from the SDKROOT), but that doesn't
3347 // work on GCC, and since we don't know whether the `cc` compiler is
3348 // Clang, GCC, or something else, we fall back to other options that
3349 // also work on GCC when compiling for macOS.
3350 //
3351 // Targets other than macOS are ill-supported by GCC (it doesn't even
3352 // support e.g. `-miphoneos-version-min`), so in those cases we can
3353 // fairly safely use `-target`. See also the following, where it is
3354 // made explicit that the recommendation by LLVM developers is to use
3355 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3356if *target_os == Os::MacOs {
3357// `-arch` communicates the architecture.
3358 //
3359 // CC forwards the `-arch` to the linker, so we use the same value
3360 // here intentionally.
3361cmd.cc_args(&["-arch", ld64_arch]);
33623363// The presence of `-mmacosx-version-min` makes CC default to
3364 // macOS, and it sets the deployment target.
3365let version = sess.apple_deployment_target().fmt_full();
3366// Intentionally pass this as a single argument, Clang doesn't
3367 // seem to like it otherwise.
3368cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
33693370// macOS has no environment, so with these two, we've told CC the
3371 // four desired parameters.
3372 //
3373 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3374} else {
3375cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3376 }
3377 }
3378}
33793380fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3381if !sess.target.is_like_darwin {
3382return None;
3383 }
3384let LinkerFlavor::Darwin(cc, _) = flavorelse {
3385return None;
3386 };
33873388// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3389 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3390 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3391 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3392 // instead we invoke `xcrun` manually.
3393 //
3394 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3395 // cause the trampoline binary to skip looking up the SDK itself).
3396let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
33973398if cc == Cc::Yes {
3399// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3400 // - The `--sysroot` flag.
3401 // - The `-isysroot` flag.
3402 // - The `SDKROOT` environment variable.
3403 //
3404 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3405 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3406 // only applies to include header files, but on Apple targets it also applies to libraries
3407 // and frameworks.
3408 //
3409 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3410 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3411 // primarily because that is the same interface that is used when invoking the tool under
3412 // `xcrun -sdk macosx $tool`.
3413 //
3414 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3415 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3416 //
3417 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3418 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3419 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3420 //
3421 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3422 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3423 // ignoring the value we set here, and instead use their built-in sysroot).
3424cmd.cmd().env("SDKROOT", &sdkroot);
3425 } else {
3426// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3427 // read by the linker, so it's really the only option.
3428 //
3429 // This is also what Clang does.
3430cmd.link_arg("-syslibroot");
3431cmd.link_arg(&sdkroot);
3432 }
34333434Some(sdkroot)
3435}
34363437fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3438if let Ok(sdkroot) = env::var("SDKROOT") {
3439let p = PathBuf::from(&sdkroot);
34403441// Ignore invalid SDKs, similar to what clang does:
3442 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3443 //
3444 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3445 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3446 // clearly set for the wrong platform.
3447 //
3448 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3449match &*apple::sdk_name(&sess.target).to_lowercase() {
3450"appletvos"
3451if sdkroot.contains("TVSimulator.platform")
3452 || sdkroot.contains("MacOSX.platform") => {}
3453"appletvsimulator"
3454if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3455"iphoneos"
3456if sdkroot.contains("iPhoneSimulator.platform")
3457 || sdkroot.contains("MacOSX.platform") => {}
3458"iphonesimulator"
3459if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3460 }
3461"macosx"
3462if sdkroot.contains("iPhoneOS.platform")
3463 || sdkroot.contains("iPhoneSimulator.platform")
3464 || sdkroot.contains("AppleTVOS.platform")
3465 || sdkroot.contains("AppleTVSimulator.platform")
3466 || sdkroot.contains("WatchOS.platform")
3467 || sdkroot.contains("WatchSimulator.platform")
3468 || sdkroot.contains("XROS.platform")
3469 || sdkroot.contains("XRSimulator.platform") => {}
3470"watchos"
3471if sdkroot.contains("WatchSimulator.platform")
3472 || sdkroot.contains("MacOSX.platform") => {}
3473"watchsimulator"
3474if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3475"xros"
3476if sdkroot.contains("XRSimulator.platform")
3477 || sdkroot.contains("MacOSX.platform") => {}
3478"xrsimulator"
3479if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3480// Ignore `SDKROOT` if it's not a valid path.
3481_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3482_ => return Some(p),
3483 }
3484 }
34853486 apple::get_sdk_root(sess)
3487}
34883489/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3490/// invoke it:
3491/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3492/// - or any `lld` available to `cc`.
3493fn add_lld_args(
3494 cmd: &mut dyn Linker,
3495 sess: &Session,
3496 flavor: LinkerFlavor,
3497 self_contained_components: LinkSelfContainedComponents,
3498) {
3499{
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:3499",
"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(3499u32),
::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!(
3500"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3501 flavor, self_contained_components,
3502 );
35033504// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3505 // we don't need to do anything.
3506if !(flavor.uses_cc() && flavor.uses_lld()) {
3507return;
3508 }
35093510// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3511 // directories to the tool's search path, depending on a mix between what users can specify on
3512 // the CLI, and what the target spec enables (as it can't disable components):
3513 // - if the self-contained linker is enabled on the CLI or by the target spec,
3514 // - and if the self-contained linker is not disabled on the CLI.
3515let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3516let self_contained_target = self_contained_components.is_linker_enabled();
35173518let self_contained_linker = self_contained_cli || self_contained_target;
3519if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3520let mut linker_path_exists = false;
3521for path in sess.get_tools_search_paths(false) {
3522let linker_path = path.join("gcc-ld");
3523 linker_path_exists |= linker_path.exists();
3524 cmd.cc_arg({
3525let mut arg = OsString::from("-B");
3526 arg.push(linker_path);
3527 arg
3528 });
3529 }
3530if !linker_path_exists {
3531// As a sanity check, we emit an error if none of these paths exist: we want
3532 // self-contained linking and have no linker.
3533sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3534 }
3535 }
35363537// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3538 // `lld` as the linker.
3539 //
3540 // Note that wasm targets skip this step since the only option there anyway
3541 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3542 // this, `wasm-component-ld`, which is overridden if this option is passed.
3543if !sess.target.is_like_wasm {
3544cmd.cc_arg("-fuse-ld=lld");
3545 }
35463547if !flavor.is_gnu() {
3548// Tell clang to use a non-default LLD flavor.
3549 // Gcc doesn't understand the target option, but we currently assume
3550 // that gcc is not used for Apple and Wasm targets (#97402).
3551 //
3552 // Note that we don't want to do that by default on macOS: e.g. passing a
3553 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3554 // shown in issue #101653 and the discussion in PR #101792.
3555 //
3556 // It could be required in some cases of cross-compiling with
3557 // LLD, but this is generally unspecified, and we don't know
3558 // which specific versions of clang, macOS SDK, host and target OS
3559 // combinations impact us here.
3560 //
3561 // So we do a simple first-approximation until we know more of what the
3562 // Apple targets require (and which would be handled prior to hitting this
3563 // LLD codepath anyway), but the expectation is that until then
3564 // this should be manually passed if needed. We specify the target when
3565 // targeting a different linker flavor on macOS, and that's also always
3566 // the case when targeting WASM.
3567if sess.target.linker_flavor != sess.host.linker_flavor {
3568cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3569 }
3570 }
3571}
35723573// gold has been deprecated with binutils 2.44
3574// and is known to behave incorrectly around Rust programs.
3575// There have been reports of being unable to bootstrap with gold:
3576// https://github.com/rust-lang/rust/issues/139425
3577// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3578// emitted with `#[used(linker)]`.
3579fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3580use object::read::elf::{FileHeader, SectionHeader};
3581use object::read::{ReadCache, ReadRef, Result};
3582use object::{Endianness, elf};
35833584fn elf_has_gold_version_note<'a>(
3585 elf: &impl FileHeader,
3586 data: impl ReadRef<'a>,
3587 ) -> Result<bool> {
3588let endian = elf.endian()?;
35893590let section =
3591elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3592if let Some((_, section)) = section3593 && let Some(mut notes) = section.notes(endian, data)?
3594{
3595return Ok(notes.any(|note| {
3596note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3597 }));
3598 }
35993600Ok(false)
3601 }
36023603let data = ReadCache::new(BufReader::new(File::open(path)?));
36043605let was_linked_with_gold = if sess.target.pointer_width == 64 {
3606let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3607elf_has_gold_version_note(elf, &data)?
3608} else if sess.target.pointer_width == 32 {
3609let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3610elf_has_gold_version_note(elf, &data)?
3611} else {
3612return Ok(());
3613 };
36143615if was_linked_with_gold {
3616let mut warn =
3617sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3618warn.help("consider using LLD or ld from GNU binutils instead");
3619warn.emit();
3620 }
3621Ok(())
3622}