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 && sess.target.options.cfg_abi != CfgAbi::Llvm696}
697698fn is_windows_gnu_clang(sess: &Session) -> bool {
699let (_, flavor) = linker_and_flavor(sess);
700sess.target.is_like_windows
701 && !sess.target.is_like_msvc
702 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))703 && sess.target.options.cfg_abi == CfgAbi::Llvm704}
705706fn report_linker_output(sess: &Session, levels: CodegenLintLevels, stdout: &[u8], stderr: &[u8]) {
707let mut escaped_stderr = escape_string(&stderr);
708let mut escaped_stdout = escape_string(&stdout);
709let mut linker_info = String::new();
710711{
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:711",
"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(711u32),
::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);
712{
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:712",
"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(712u32),
::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);
713714fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
715let mut output = String::new();
716if let Ok(str) = str::from_utf8(bytes) {
717{
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:717",
"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(717u32),
::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}");
718output = String::with_capacity(str.len());
719for line in str.lines() {
720 f(line.trim(), &mut output);
721 }
722 }
723escape_string(output.trim().as_bytes())
724 }
725726if is_msvc_link_exe(sess) {
727{
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:727",
"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(727u32),
::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");
728729escaped_stdout = for_each(&stdout, |line, output| {
730// Hide some progress messages from link.exe that we don't care about.
731 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
732let trimmed = line.trim_start();
733if trimmed.starts_with("Creating library")
734 || trimmed.starts_with("Generating code")
735 || trimmed.starts_with("Finished generating code")
736 {
737linker_info += line;
738linker_info += "\r\n";
739 } else {
740*output += line;
741*output += "\r\n"
742}
743 });
744 } else if is_macos_ld(sess) {
745{
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:745",
"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(745u32),
::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");
746747// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
748let deployment_mismatch = |line: &str| {
749line.starts_with("ld: warning: object file (")
750 && line.contains("was built for newer 'macOS' version")
751 && line.contains("than being linked")
752 };
753// FIXME: This is a real warning we would like to show, but it hits too many crates
754 // to want to turn it on immediately.
755let search_path = |line: &str| {
756line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
757 };
758escaped_stderr = for_each(&stderr, |line, output| {
759// This duplicate library warning is just not helpful at all.
760if line.starts_with("ld: warning: ignoring duplicate libraries: ")
761 || deployment_mismatch(line)
762 || search_path(line)
763 {
764linker_info += line;
765linker_info += "\n";
766 } else {
767*output += line;
768*output += "\n"
769}
770 });
771 } else if is_windows_gnu_ld(sess) {
772{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:772",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(772u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows GNU LD")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows GNU LD");
773774let mut saw_exclude_symbol = false;
775// See https://github.com/rust-lang/rust/issues/112368.
776 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
777let exclude_symbols = |line: &str| {
778line.starts_with("Warning: .drectve `-exclude-symbols:")
779 && line.ends_with("' unrecognized")
780 };
781escaped_stderr = for_each(&stderr, |line, output| {
782if exclude_symbols(line) {
783saw_exclude_symbol = true;
784linker_info += line;
785linker_info += "\n";
786 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
787linker_info += line;
788linker_info += "\n";
789 } else {
790*output += line;
791*output += "\n"
792}
793 });
794 } else if is_windows_gnu_clang(sess) {
795{
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:795",
"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(795u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("inferred Windows Clang (GNU ABI)")
as &dyn Value))])
});
} else { ; }
};info!("inferred Windows Clang (GNU ABI)");
796escaped_stderr = for_each(&stderr, |line, output| {
797if line.contains("argument unused during compilation: '-nolibc'") {
798linker_info += line;
799linker_info += "\n";
800 } else {
801*output += line;
802*output += "\n"
803}
804 });
805 };
806807let lint_msg = |msg| {
808emit_lint_base(
809sess,
810LINKER_MESSAGES,
811levels.linker_messages,
812None,
813LinkerOutput { inner: msg },
814 );
815 };
816let lint_info = |msg| {
817emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
818 };
819820if !escaped_stderr.is_empty() {
821// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
822escaped_stderr =
823escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
824// Windows GNU LD prints uppercase Warning
825escaped_stderr = escaped_stderr826 .strip_prefix("Warning: ")
827 .unwrap_or(&escaped_stderr)
828 .replace(": warning: ", ": ");
829lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
830 }
831if !escaped_stdout.is_empty() {
832lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
833 }
834if !linker_info.is_empty() {
835lint_info(linker_info);
836 }
837}
838839/// Create a dynamic library or executable.
840///
841/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
842/// files as well.
843fn link_natively(
844 sess: &Session,
845 archive_builder_builder: &dyn ArchiveBuilderBuilder,
846 crate_type: CrateType,
847 out_filename: &Path,
848 compiled_modules: &CompiledModules,
849 crate_info: &CrateInfo,
850 metadata: &EncodedMetadata,
851 tmpdir: &Path,
852 codegen_backend: &'static str,
853) {
854{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:854",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(854u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing {0:?} to {1:?}",
crate_type, out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
855let (linker_path, flavor) = linker_and_flavor(sess);
856let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
857858// On AIX, we ship all libraries as .a big_af archive
859 // the expected format is lib<name>.a(libname.so) for the actual
860 // dynamic library. So we link to a temporary .so file to be archived
861 // at the final out_filename location
862let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
863let archive_member =
864should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
865let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
866867let mut cmd = linker_with_args(
868&linker_path,
869flavor,
870sess,
871archive_builder_builder,
872crate_type,
873tmpdir,
874temp_filename,
875compiled_modules,
876crate_info,
877metadata,
878self_contained_components,
879codegen_backend,
880 );
881882 linker::disable_localization(&mut cmd);
883884for (k, v) in sess.target.link_env.as_ref() {
885 cmd.env(k.as_ref(), v.as_ref());
886 }
887for k in sess.target.link_env_remove.as_ref() {
888 cmd.env_remove(k.as_ref());
889 }
890891for print in &sess.opts.prints {
892if print.kind == PrintKind::LinkArgs {
893let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
894 print.out.overwrite(&content, sess);
895 }
896 }
897898// May have not found libraries in the right formats.
899sess.dcx().abort_if_errors();
900901// Invoke the system linker
902{
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:902",
"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(902u32),
::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:?}");
903let unknown_arg_regex =
904Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
905let mut prog;
906loop {
907prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
908let Ok(ref output) = progelse {
909break;
910 };
911if output.status.success() {
912break;
913 }
914let mut out = output.stderr.clone();
915out.extend(&output.stdout);
916let out = String::from_utf8_lossy(&out);
917918// Check to see if the link failed with an error message that indicates it
919 // doesn't recognize the -no-pie option. If so, re-perform the link step
920 // without it. This is safe because if the linker doesn't support -no-pie
921 // then it should not default to linking executables as pie. Different
922 // versions of gcc seem to use different quotes in the error message so
923 // don't check for them.
924if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))925 && unknown_arg_regex.is_match(&out)
926 && out.contains("-no-pie")
927 && cmd.get_args().iter().any(|e| e == "-no-pie")
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::WARN,
::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::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.");
931for arg in cmd.take_args() {
932if arg != "-no-pie" {
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// Check if linking failed with an error message that indicates the driver didn't recognize
941 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
942 // to spawn multiple instances on the happy path to do version checking, and ensures things
943 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
944 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
945if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))946 && unknown_arg_regex.is_match(&out)
947 && out.contains("-fuse-ld=lld")
948 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
949 {
950{
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:950",
"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(950u32),
::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);
951{
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:951",
"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(951u32),
::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.");
952for arg in cmd.take_args() {
953if arg.to_string_lossy() != "-fuse-ld=lld" {
954 cmd.arg(arg);
955 }
956 }
957{
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:957",
"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(957u32),
::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:?}");
958continue;
959 }
960961// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
962 // Fallback from '-static-pie' to '-static' in that case.
963if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))964 && unknown_arg_regex.is_match(&out)
965 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
966 && cmd.get_args().iter().any(|e| e == "-static-pie")
967 {
968{
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:968",
"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(968u32),
::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);
969{
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:969",
"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(969u32),
::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!(
970"Linker does not support -static-pie command line option. Retrying with -static instead."
971);
972// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
973let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
974let opts = &sess.target;
975let pre_objects = if self_contained_crt_objects {
976&opts.pre_link_objects_self_contained
977 } else {
978&opts.pre_link_objects
979 };
980let post_objects = if self_contained_crt_objects {
981&opts.post_link_objects_self_contained
982 } else {
983&opts.post_link_objects
984 };
985let get_objects = |objects: &CrtObjects, kind| {
986objects987 .get(&kind)
988 .iter()
989 .copied()
990 .flatten()
991 .map(|obj| {
992get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
993 })
994 .collect::<Vec<_>>()
995 };
996let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
997let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
998let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
999let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1000// Assume that we know insertion positions for the replacement arguments from replaced
1001 // arguments, which is true for all supported targets.
1002if !(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());
1003if !(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());
1004for arg in cmd.take_args() {
1005if arg == "-static-pie" {
1006// Replace the output kind.
1007cmd.arg("-static");
1008 } else if pre_objects_static_pie.contains(&arg) {
1009// Replace the pre-link objects (replace the first and remove the rest).
1010cmd.args(mem::take(&mut pre_objects_static));
1011 } else if post_objects_static_pie.contains(&arg) {
1012// Replace the post-link objects (replace the first and remove the rest).
1013cmd.args(mem::take(&mut post_objects_static));
1014 } else {
1015 cmd.arg(arg);
1016 }
1017 }
1018{
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:1018",
"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(1018u32),
::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:?}");
1019continue;
1020 }
10211022break;
1023 }
10241025match prog {
1026Ok(prog) => {
1027if !prog.status.success() {
1028let mut output = prog.stderr.clone();
1029output.extend_from_slice(&prog.stdout);
1030let escaped_output = escape_linker_output(&output, flavor);
1031let err = errors::LinkingFailed {
1032 linker_path: &linker_path,
1033 exit_status: prog.status,
1034 command: cmd,
1035escaped_output,
1036 verbose: sess.opts.verbose,
1037 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1038 };
1039sess.dcx().emit_err(err);
1040// If MSVC's `link.exe` was expected but the return code
1041 // is not a Microsoft LNK error then suggest a way to fix or
1042 // install the Visual Studio build tools.
1043if let Some(code) = prog.status.code() {
1044// All Microsoft `link.exe` linking ror codes are
1045 // four digit numbers in the range 1000 to 9999 inclusive
1046if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1047let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1048let has_linker =
1049 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1050 .is_some();
10511052sess.dcx().emit_note(errors::LinkExeUnexpectedError);
10531054// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1055 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1056const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1057if code == STATUS_STACK_BUFFER_OVERRUN {
1058sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1059 }
10601061if is_vs_installed && has_linker {
1062// the linker is broken
1063sess.dcx().emit_note(errors::RepairVSBuildTools);
1064sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1065 } else if is_vs_installed {
1066// the linker is not installed
1067sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1068 } else {
1069// visual studio is not installed
1070sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1071 }
1072 }
1073 }
10741075sess.dcx().abort_if_errors();
1076 }
10771078{
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:1078",
"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(1078u32),
::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:?}");
1079report_linker_output(sess, crate_info.lint_levels, &prog.stdout, &prog.stderr);
1080 }
1081Err(e) => {
1082let linker_not_found = e.kind() == io::ErrorKind::NotFound;
10831084let err = if linker_not_found {
1085sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1086 } else {
1087sess.dcx().emit_err(errors::UnableToExeLinker {
1088linker_path,
1089 error: e,
1090 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1091 })
1092 };
10931094if sess.target.is_like_msvc && linker_not_found {
1095sess.dcx().emit_note(errors::MsvcMissingLinker);
1096sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1097sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1098 }
1099err.raise_fatal();
1100 }
1101 }
11021103match sess.split_debuginfo() {
1104// If split debug information is disabled or located in individual files
1105 // there's nothing to do here.
1106SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
11071108// If packed split-debuginfo is requested, but the final compilation
1109 // doesn't actually have any debug information, then we skip this step.
1110SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
11111112// On macOS the external `dsymutil` tool is used to create the packed
1113 // debug information. Note that this will read debug information from
1114 // the objects on the filesystem which we'll clean up later.
1115SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1116let prog = Command::new("dsymutil").arg(out_filename).output();
1117match prog {
1118Ok(prog) => {
1119if !prog.status.success() {
1120let mut output = prog.stderr.clone();
1121output.extend_from_slice(&prog.stdout);
1122sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1123 status: prog.status,
1124 output: escape_string(&output),
1125 });
1126 }
1127 }
1128Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1129 }
1130 }
11311132// On MSVC packed debug information is produced by the linker itself so
1133 // there's no need to do anything else here.
1134SplitDebuginfo::Packedif sess.target.is_like_windows => {}
11351136// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1137 //
1138 // We cannot rely on the .o paths in the executable because they may have been
1139 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1140 // the .o/.dwo paths explicitly.
1141SplitDebuginfo::Packed => {
1142link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1143 }
1144 }
11451146let strip = sess.opts.cg.strip;
11471148if sess.target.is_like_darwin {
1149let stripcmd = "rust-objcopy";
1150match (strip, crate_type) {
1151 (Strip::Debuginfo, _) => {
1152strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1153 }
11541155// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1156(
1157 Strip::Symbols,
1158 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1159 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1160 (Strip::Symbols, _) => {
1161strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1162 }
1163 (Strip::None, _) => {}
1164 }
1165 }
11661167if sess.target.is_like_solaris {
1168// Many illumos systems will have both the native 'strip' utility and
1169 // the GNU one. Use the native version explicitly and do not rely on
1170 // what's in the path.
1171 //
1172 // If cross-compiling and there is not a native version, then use
1173 // `llvm-strip` and hope.
1174let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1175match strip {
1176// Always preserve the symbol table (-x).
1177Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1178// Strip::Symbols is handled via the --strip-all linker option.
1179Strip::Symbols => {}
1180 Strip::None => {}
1181 }
1182 }
11831184if sess.target.is_like_aix {
1185// `llvm-strip` doesn't work for AIX - their strip must be used.
1186if !sess.host.is_like_aix {
1187sess.dcx().emit_warn(errors::AixStripNotUsed);
1188 }
1189let stripcmd = "/usr/bin/strip";
1190match strip {
1191 Strip::Debuginfo => {
1192// FIXME: AIX's strip utility only offers option to strip line number information.
1193strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1194 }
1195 Strip::Symbols => {
1196// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1197strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1198 }
1199 Strip::None => {}
1200 }
1201 }
12021203if should_archive {
1204let mut ab = archive_builder_builder.new_archive_builder(sess);
1205ab.add_file(temp_filename);
1206ab.build(out_filename);
1207 }
1208}
12091210fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1211let mut cmd = Command::new(util);
1212cmd.args(options);
12131214let mut new_path = sess.get_tools_search_paths(false);
1215if let Some(path) = env::var_os("PATH") {
1216new_path.extend(env::split_paths(&path));
1217 }
1218cmd.env("PATH", env::join_paths(new_path).unwrap());
12191220let prog = cmd.arg(out_filename).output();
1221match prog {
1222Ok(prog) => {
1223if !prog.status.success() {
1224let mut output = prog.stderr.clone();
1225output.extend_from_slice(&prog.stdout);
1226sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1227util,
1228 status: prog.status,
1229 output: escape_string(&output),
1230 });
1231 }
1232 }
1233Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1234 }
1235}
12361237fn escape_string(s: &[u8]) -> String {
1238match str::from_utf8(s) {
1239Ok(s) => s.to_owned(),
1240Err(_) => ::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()),
1241 }
1242}
12431244#[cfg(not(windows))]
1245fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1246escape_string(s)
1247}
12481249/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1250/// then try to convert the string from the OEM encoding.
1251#[cfg(windows)]
1252fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1253// This only applies to the actual MSVC linker.
1254if flavour != LinkerFlavor::Msvc(Lld::No) {
1255return escape_string(s);
1256 }
1257match str::from_utf8(s) {
1258Ok(s) => return s.to_owned(),
1259Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1260Some(s) => s,
1261// The string is not UTF-8 and isn't valid for the OEM code page
1262None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1263 },
1264 }
1265}
12661267/// Wrappers around the Windows API.
1268#[cfg(windows)]
1269mod win {
1270use windows::Win32::Globalization::{
1271 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1272 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1273 };
12741275/// Get the Windows system OEM code page. This is most notably the code page
1276 /// used for link.exe's output.
1277pub(super) fn oem_code_page() -> u32 {
1278unsafe {
1279let mut cp: u32 = 0;
1280// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1281 // But the API requires us to pass the data as though it's a [u16] string.
1282let len = size_of::<u32>() / size_of::<u16>();
1283let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1284let len_written = GetLocaleInfoEx(
1285 LOCALE_NAME_SYSTEM_DEFAULT,
1286 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1287Some(data),
1288 );
1289if len_written as usize == len { cp } else { CP_OEMCP }
1290 }
1291 }
1292/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1293 /// The string does not need to be null terminated.
1294 ///
1295 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1296 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1297 ///
1298 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1299 /// any invalid bytes for the expected encoding.
1300pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1301// `MultiByteToWideChar` requires a length to be a "positive integer".
1302if s.len() > isize::MAX as usize {
1303return None;
1304 }
1305// Error if the string is not valid for the expected code page.
1306let flags = MB_ERR_INVALID_CHARS;
1307// Call MultiByteToWideChar twice.
1308 // First to calculate the length then to convert the string.
1309let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1310if len > 0 {
1311let mut utf16 = vec![0; len as usize];
1312 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1313if len > 0 {
1314return utf16.get(..len as usize).map(String::from_utf16_lossy);
1315 }
1316 }
1317None
1318}
1319}
13201321fn add_sanitizer_libraries(
1322 sess: &Session,
1323 flavor: LinkerFlavor,
1324 crate_type: CrateType,
1325 linker: &mut dyn Linker,
1326) {
1327if sess.target.is_like_android {
1328// Sanitizer runtime libraries are provided dynamically on Android
1329 // targets.
1330return;
1331 }
13321333if sess.opts.unstable_opts.external_clangrt {
1334// Linking against in-tree sanitizer runtimes is disabled via
1335 // `-Z external-clangrt`
1336return;
1337 }
13381339if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1340return;
1341 }
13421343// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1344 // which should be linked to both executables and dynamic libraries.
1345 // Everywhere else the runtimes are currently distributed as static
1346 // libraries which should be linked to executables only.
1347if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1348 crate_type,
1349 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1350 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1351 {
1352return;
1353 }
13541355let sanitizer = sess.sanitizers();
1356if sanitizer.contains(SanitizerSet::ADDRESS) {
1357link_sanitizer_runtime(sess, flavor, linker, "asan");
1358 }
1359if sanitizer.contains(SanitizerSet::DATAFLOW) {
1360link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1361 }
1362if sanitizer.contains(SanitizerSet::LEAK)
1363 && !sanitizer.contains(SanitizerSet::ADDRESS)
1364 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1365 {
1366link_sanitizer_runtime(sess, flavor, linker, "lsan");
1367 }
1368if sanitizer.contains(SanitizerSet::MEMORY) {
1369link_sanitizer_runtime(sess, flavor, linker, "msan");
1370 }
1371if sanitizer.contains(SanitizerSet::THREAD) {
1372link_sanitizer_runtime(sess, flavor, linker, "tsan");
1373 }
1374if sanitizer.contains(SanitizerSet::HWADDRESS) {
1375link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1376 }
1377if sanitizer.contains(SanitizerSet::SAFESTACK) {
1378link_sanitizer_runtime(sess, flavor, linker, "safestack");
1379 }
1380if sanitizer.contains(SanitizerSet::REALTIME) {
1381link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1382 }
1383}
13841385fn link_sanitizer_runtime(
1386 sess: &Session,
1387 flavor: LinkerFlavor,
1388 linker: &mut dyn Linker,
1389 name: &str,
1390) {
1391fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1392let path = sess.target_tlib_path.dir.join(filename);
1393if path.exists() {
1394sess.target_tlib_path.dir.clone()
1395 } else {
1396 filesearch::make_target_lib_path(
1397&sess.opts.sysroot.default,
1398sess.opts.target_triple.tuple(),
1399 )
1400 }
1401 }
14021403let channel =
1404::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();
14051406if sess.target.is_like_darwin {
1407// On Apple platforms, the sanitizer is always built as a dylib, and
1408 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1409 // rpath to the library as well (the rpath should be absolute, see
1410 // PR #41352 for details).
1411let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1412let path = find_sanitizer_runtime(sess, &filename);
1413let rpath = path.to_str().expect("non-utf8 component in path");
1414linker.link_args(&["-rpath", rpath]);
1415linker.link_dylib_by_name(&filename, false, true);
1416 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1417// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1418 // compatible ASAN library.
1419linker.link_arg("/INFERASANLIBS");
1420 } else {
1421let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1422let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1423linker.link_staticlib_by_path(&path, true);
1424 }
1425}
14261427/// Returns a boolean indicating whether the specified crate should be ignored
1428/// during LTO.
1429///
1430/// Crates ignored during LTO are not lumped together in the "massive object
1431/// file" that we create and are linked in their normal rlib states. See
1432/// comments below for what crates do not participate in LTO.
1433///
1434/// It's unusual for a crate to not participate in LTO. Typically only
1435/// compiler-specific and unstable crates have a reason to not participate in
1436/// LTO.
1437pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1438// If our target enables builtin function lowering in LLVM then the
1439 // crates providing these functions don't participate in LTO (e.g.
1440 // no_builtins or compiler builtins crates).
1441!sess.target.no_builtins
1442 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1443}
14441445/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1446pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1447fn infer_from(
1448 sess: &Session,
1449 linker: Option<PathBuf>,
1450 flavor: Option<LinkerFlavor>,
1451 features: LinkerFeaturesCli,
1452 ) -> Option<(PathBuf, LinkerFlavor)> {
1453let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1454match (linker, flavor) {
1455 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1456// only the linker flavor is known; use the default linker for the selected flavor
1457(None, Some(flavor)) => Some((
1458PathBuf::from(match flavor {
1459 LinkerFlavor::Gnu(Cc::Yes, _)
1460 | LinkerFlavor::Darwin(Cc::Yes, _)
1461 | LinkerFlavor::WasmLld(Cc::Yes)
1462 | LinkerFlavor::Unix(Cc::Yes) => {
1463if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1464// On historical Solaris systems, "cc" may have
1465 // been Sun Studio, which is not flag-compatible
1466 // with "gcc". This history casts a long shadow,
1467 // and many modern illumos distributions today
1468 // ship GCC as "gcc" without also making it
1469 // available as "cc".
1470"gcc"
1471} else {
1472"cc"
1473}
1474 }
1475 LinkerFlavor::Gnu(_, Lld::Yes)
1476 | LinkerFlavor::Darwin(_, Lld::Yes)
1477 | LinkerFlavor::WasmLld(..)
1478 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1479 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1480"ld"
1481}
1482 LinkerFlavor::Msvc(..) => "link.exe",
1483 LinkerFlavor::EmCc => {
1484if falsecfg!(windows) {
1485"emcc.bat"
1486} else {
1487"emcc"
1488}
1489 }
1490 LinkerFlavor::Bpf => "bpf-linker",
1491 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1492 LinkerFlavor::Ptx => "rust-ptx-linker",
1493 }),
1494flavor,
1495 )),
1496 (Some(linker), None) => {
1497let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1498sess.dcx().emit_fatal(errors::LinkerFileStem);
1499 });
1500let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1501let flavor = adjust_flavor_to_features(flavor, features);
1502Some((linker, flavor))
1503 }
1504 (None, None) => None,
1505 }
1506 }
15071508// While linker flavors and linker features are isomorphic (and thus targets don't need to
1509 // define features separately), we use the flavor as the root piece of data and have the
1510 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1511 // both yet.
1512fn adjust_flavor_to_features(
1513 flavor: LinkerFlavor,
1514 features: LinkerFeaturesCli,
1515 ) -> LinkerFlavor {
1516// Note: a linker feature cannot be both enabled and disabled on the CLI.
1517if features.enabled.contains(LinkerFeatures::LLD) {
1518flavor.with_lld_enabled()
1519 } else if features.disabled.contains(LinkerFeatures::LLD) {
1520flavor.with_lld_disabled()
1521 } else {
1522flavor1523 }
1524 }
15251526let features = sess.opts.cg.linker_features;
15271528// linker and linker flavor specified via command line have precedence over what the target
1529 // specification specifies
1530let linker_flavor = match sess.opts.cg.linker_flavor {
1531// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1532Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1533Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1534// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1535linker_flavor => {
1536linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1537 }
1538 };
1539if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1540return ret;
1541 }
15421543if let Some(ret) = infer_from(
1544sess,
1545sess.target.linker.as_deref().map(PathBuf::from),
1546Some(sess.target.linker_flavor),
1547features,
1548 ) {
1549return ret;
1550 }
15511552::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");
1553}
15541555/// Returns a pair of boolean indicating whether we should preserve the object and
1556/// dwarf object files on the filesystem for their debug information. This is often
1557/// useful with split-dwarf like schemes.
1558fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1559// If the objects don't have debuginfo there's nothing to preserve.
1560if sess.opts.debuginfo == config::DebugInfo::None {
1561return (false, false);
1562 }
15631564match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1565// If there is no split debuginfo then do not preserve objects.
1566(SplitDebuginfo::Off, _) => (false, false),
1567// If there is packed split debuginfo, then the debuginfo in the objects
1568 // has been packaged and the objects can be deleted.
1569(SplitDebuginfo::Packed, _) => (false, false),
1570// If there is unpacked split debuginfo and the current target can not use
1571 // split dwarf, then keep objects.
1572(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1573// If there is unpacked split debuginfo and the target can use split dwarf, then
1574 // keep the object containing that debuginfo (whether that is an object file or
1575 // dwarf object file depends on the split dwarf kind).
1576(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1577 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1578 }
1579}
15801581#[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)]
1582enum RlibFlavor {
1583 Normal,
1584 StaticlibBase,
1585}
15861587fn print_native_static_libs(
1588 sess: &Session,
1589 out: &OutFileName,
1590 all_native_libs: &[NativeLib],
1591 all_rust_dylibs: &[&Path],
1592) {
1593let mut lib_args: Vec<_> = all_native_libs1594 .iter()
1595 .filter(|l| relevant_lib(sess, l))
1596 .filter_map(|lib| {
1597let name = lib.name;
1598match lib.kind {
1599 NativeLibKind::Static { bundle: Some(false), .. }
1600 | NativeLibKind::Dylib { .. }
1601 | NativeLibKind::Unspecified => {
1602let verbatim = lib.verbatim;
1603if sess.target.is_like_msvc {
1604let (prefix, suffix) = sess.staticlib_components(verbatim);
1605Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1606 } else if sess.target.linker_flavor.is_gnu() {
1607Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1608 } else {
1609Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1610 }
1611 }
1612 NativeLibKind::Framework { .. } => {
1613// ld-only syntax, since there are no frameworks in MSVC
1614Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1615 }
1616// These are included, no need to print them
1617NativeLibKind::Static { bundle: None | Some(true), .. }
1618 | NativeLibKind::LinkArg1619 | NativeLibKind::WasmImportModule1620 | NativeLibKind::RawDylib { .. } => None,
1621 }
1622 })
1623// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1624.dedup()
1625 .collect();
1626for path in all_rust_dylibs {
1627// FIXME deduplicate with add_dynamic_crate
16281629 // Just need to tell the linker about where the library lives and
1630 // what its name is
1631let parent = path.parent();
1632if let Some(dir) = parent {
1633let dir = fix_windows_verbatim_for_gcc(dir);
1634if sess.target.is_like_msvc {
1635let mut arg = String::from("/LIBPATH:");
1636 arg.push_str(&dir.display().to_string());
1637 lib_args.push(arg);
1638 } else {
1639 lib_args.push("-L".to_owned());
1640 lib_args.push(dir.display().to_string());
1641 }
1642 }
1643let stem = path.file_stem().unwrap().to_str().unwrap();
1644// Convert library file-stem into a cc -l argument.
1645let lib = if let Some(lib) = stem.strip_prefix("lib")
1646 && !sess.target.is_like_windows
1647 {
1648 lib
1649 } else {
1650 stem
1651 };
1652let path = parent.unwrap_or_else(|| Path::new(""));
1653if sess.target.is_like_msvc {
1654// When producing a dll, the MSVC linker may not actually emit a
1655 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1656 // check to see if the file is there and just omit linking to it if it's
1657 // not present.
1658let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1659if path.join(&name).exists() {
1660 lib_args.push(name);
1661 }
1662 } else {
1663 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1664 }
1665 }
16661667match out {
1668 OutFileName::Real(path) => {
1669out.overwrite(&lib_args.join(" "), sess);
1670sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1671 }
1672 OutFileName::Stdout => {
1673sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1674// Prefix for greppability
1675 // Note: This must not be translated as tools are allowed to depend on this exact string.
1676sess.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(" ")));
1677 }
1678 }
1679}
16801681fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1682let file_path = sess.target_tlib_path.dir.join(name);
1683if file_path.exists() {
1684return file_path;
1685 }
1686// Special directory with objects used only in self-contained linkage mode
1687if self_contained {
1688let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1689if file_path.exists() {
1690return file_path;
1691 }
1692 }
1693for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1694let file_path = search_path.dir.join(name);
1695if file_path.exists() {
1696return file_path;
1697 }
1698 }
1699PathBuf::from(name)
1700}
17011702fn exec_linker(
1703 sess: &Session,
1704 cmd: &Command,
1705 out_filename: &Path,
1706 flavor: LinkerFlavor,
1707 tmpdir: &Path,
1708) -> io::Result<Output> {
1709// When attempting to spawn the linker we run a risk of blowing out the
1710 // size limits for spawning a new process with respect to the arguments
1711 // we pass on the command line.
1712 //
1713 // Here we attempt to handle errors from the OS saying "your list of
1714 // arguments is too big" by reinvoking the linker again with an `@`-file
1715 // that contains all the arguments (aka 'response' files).
1716 // The theory is that this is then accepted on all linkers and the linker
1717 // will read all its options out of there instead of looking at the command line.
1718if !cmd.very_likely_to_exceed_some_spawn_limit() {
1719match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1720Ok(child) => {
1721let output = child.wait_with_output();
1722flush_linked_file(&output, out_filename)?;
1723return output;
1724 }
1725Err(ref e) if command_line_too_big(e) => {
1726{
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:1726",
"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(1726u32),
::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);
1727 }
1728Err(e) => return Err(e),
1729 }
1730 }
17311732{
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:1732",
"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(1732u32),
::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");
1733let mut cmd2 = cmd.clone();
1734let mut args = String::new();
1735for arg in cmd2.take_args() {
1736 args.push_str(
1737&Escape {
1738 arg: arg.to_str().unwrap(),
1739// Windows-style escaping for @-files is used by
1740 // - all linkers targeting MSVC-like targets, including LLD
1741 // - all LLD flavors running on Windows hosts
1742 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1743is_like_msvc: sess.target.is_like_msvc
1744 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1745 }
1746 .to_string(),
1747 );
1748 args.push('\n');
1749 }
1750let file = tmpdir.join("linker-arguments");
1751let bytes = if sess.target.is_like_msvc {
1752let mut out = Vec::with_capacity((1 + args.len()) * 2);
1753// start the stream with a UTF-16 BOM
1754for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1755// encode in little endian
1756out.push(c as u8);
1757 out.push((c >> 8) as u8);
1758 }
1759out1760 } else {
1761args.into_bytes()
1762 };
1763 fs::write(&file, &bytes)?;
1764cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1765{
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:1765",
"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(1765u32),
::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);
1766let output = cmd2.output();
1767flush_linked_file(&output, out_filename)?;
1768return output;
17691770#[cfg(not(windows))]
1771fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1772Ok(())
1773 }
17741775#[cfg(windows)]
1776fn flush_linked_file(
1777 command_output: &io::Result<Output>,
1778 out_filename: &Path,
1779 ) -> io::Result<()> {
1780// On Windows, under high I/O load, output buffers are sometimes not flushed,
1781 // even long after process exit, causing nasty, non-reproducible output bugs.
1782 //
1783 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1784 //
1785 // А full writeup of the original Chrome bug can be found at
1786 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
17871788if let &Ok(ref out) = command_output {
1789if out.status.success() {
1790if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1791 of.sync_all()?;
1792 }
1793 }
1794 }
17951796Ok(())
1797 }
17981799#[cfg(unix)]
1800fn command_line_too_big(err: &io::Error) -> bool {
1801err.raw_os_error() == Some(::libc::E2BIG)
1802 }
18031804#[cfg(windows)]
1805fn command_line_too_big(err: &io::Error) -> bool {
1806const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1807 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1808 }
18091810#[cfg(not(any(unix, windows)))]
1811fn command_line_too_big(_: &io::Error) -> bool {
1812false
1813}
18141815struct Escape<'a> {
1816 arg: &'a str,
1817 is_like_msvc: bool,
1818 }
18191820impl<'a> fmt::Displayfor Escape<'a> {
1821fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1822if self.is_like_msvc {
1823// This is "documented" at
1824 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1825 //
1826 // Unfortunately there's not a great specification of the
1827 // syntax I could find online (at least) but some local
1828 // testing showed that this seemed sufficient-ish to catch
1829 // at least a few edge cases.
1830f.write_fmt(format_args!("\""))write!(f, "\"")?;
1831for c in self.arg.chars() {
1832match c {
1833'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1834 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1835 }
1836 }
1837f.write_fmt(format_args!("\""))write!(f, "\"")?;
1838 } else {
1839// This is documented at https://linux.die.net/man/1/ld, namely:
1840 //
1841 // > Options in file are separated by whitespace. A whitespace
1842 // > character may be included in an option by surrounding the
1843 // > entire option in either single or double quotes. Any
1844 // > character (including a backslash) may be included by
1845 // > prefixing the character to be included with a backslash.
1846 //
1847 // We put an argument on each line, so all we need to do is
1848 // ensure the line is interpreted as one whole argument.
1849for c in self.arg.chars() {
1850match c {
1851'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1852 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1853 }
1854 }
1855 }
1856Ok(())
1857 }
1858 }
1859}
18601861fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1862let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1863 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1864 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1865 LinkOutputKind::DynamicPicExe1866 }
1867 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1868 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1869 LinkOutputKind::StaticPicExe1870 }
1871 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1872 (_, true, _) => LinkOutputKind::StaticDylib,
1873 (_, false, _) => LinkOutputKind::DynamicDylib,
1874 };
18751876// Adjust the output kind to target capabilities.
1877let opts = &sess.target;
1878let pic_exe_supported = opts.position_independent_executables;
1879let static_pic_exe_supported = opts.static_position_independent_executables;
1880let static_dylib_supported = opts.crt_static_allows_dylibs;
1881match kind {
1882 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1883 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1884 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1885_ => kind,
1886 }
1887}
18881889// Returns true if linker is located within sysroot
1890fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1891let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1892linker.with_extension("exe")
1893 } else {
1894linker.to_path_buf()
1895 };
1896for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1897let full_path = dir.join(&linker_with_extension);
1898// If linker comes from sysroot assume self-contained mode
1899if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1900return false;
1901 }
1902 }
1903true
1904}
19051906/// Various toolchain components used during linking are used from rustc distribution
1907/// instead of being found somewhere on the host system.
1908/// We only provide such support for a very limited number of targets.
1909fn self_contained_components(
1910 sess: &Session,
1911 crate_type: CrateType,
1912 linker: &Path,
1913) -> LinkSelfContainedComponents {
1914// Turn the backwards compatible bool values for `self_contained` into fully inferred
1915 // `LinkSelfContainedComponents`.
1916let self_contained =
1917if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1918// Emit an error if the user requested self-contained mode on the CLI but the target
1919 // explicitly refuses it.
1920if sess.target.link_self_contained.is_disabled() {
1921sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1922 }
1923self_contained1924 } else {
1925match sess.target.link_self_contained {
1926 LinkSelfContainedDefault::False => false,
1927 LinkSelfContainedDefault::True => true,
19281929 LinkSelfContainedDefault::WithComponents(components) => {
1930// For target specs with explicitly enabled components, we can return them
1931 // directly.
1932return components;
1933 }
19341935// FIXME: Find a better heuristic for "native musl toolchain is available",
1936 // based on host and linker path, for example.
1937 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1938LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1939 LinkSelfContainedDefault::InferredForMingw => {
1940sess.host == sess.target
1941 && sess.target.cfg_abi != CfgAbi::Uwp1942 && detect_self_contained_mingw(sess, linker)
1943 }
1944 }
1945 };
1946if self_contained {
1947LinkSelfContainedComponents::all()
1948 } else {
1949LinkSelfContainedComponents::empty()
1950 }
1951}
19521953/// Add pre-link object files defined by the target spec.
1954fn add_pre_link_objects(
1955 cmd: &mut dyn Linker,
1956 sess: &Session,
1957 flavor: LinkerFlavor,
1958 link_output_kind: LinkOutputKind,
1959 self_contained: bool,
1960) {
1961// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1962 // so Fuchsia has to be special-cased.
1963let opts = &sess.target;
1964let empty = Default::default();
1965let objects = if self_contained {
1966&opts.pre_link_objects_self_contained
1967 } 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, _))) {
1968&opts.pre_link_objects
1969 } else {
1970&empty1971 };
1972for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1973 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1974 }
1975}
19761977/// Add post-link object files defined by the target spec.
1978fn add_post_link_objects(
1979 cmd: &mut dyn Linker,
1980 sess: &Session,
1981 link_output_kind: LinkOutputKind,
1982 self_contained: bool,
1983) {
1984let objects = if self_contained {
1985&sess.target.post_link_objects_self_contained
1986 } else {
1987&sess.target.post_link_objects
1988 };
1989for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1990 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1991 }
1992}
19931994/// Add arbitrary "pre-link" args defined by the target spec or from command line.
1995/// FIXME: Determine where exactly these args need to be inserted.
1996fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1997if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1998cmd.verbatim_args(args.iter().map(Deref::deref));
1999 }
20002001cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2002}
20032004/// Add a link script embedded in the target, if applicable.
2005fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2006match (crate_type, &sess.target.link_script) {
2007 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2008if !sess.target.linker_flavor.is_gnu() {
2009sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2010 }
20112012let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
20132014let path = tmpdir.join(file_name);
2015if let Err(error) = fs::write(&path, script.as_ref()) {
2016sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2017 }
20182019cmd.link_arg("--script").link_arg(path);
2020 }
2021_ => {}
2022 }
2023}
20242025/// Add arbitrary "user defined" args defined from command line.
2026/// FIXME: Determine where exactly these args need to be inserted.
2027fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2028cmd.verbatim_args(&sess.opts.cg.link_args);
2029}
20302031/// Add arbitrary "late link" args defined by the target spec.
2032/// FIXME: Determine where exactly these args need to be inserted.
2033fn add_late_link_args(
2034 cmd: &mut dyn Linker,
2035 sess: &Session,
2036 flavor: LinkerFlavor,
2037 crate_type: CrateType,
2038 crate_info: &CrateInfo,
2039) {
2040let any_dynamic_crate = crate_type == CrateType::Dylib2041 || crate_type == CrateType::Sdylib2042 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2043*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2044 });
2045if any_dynamic_crate {
2046if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2047cmd.verbatim_args(args.iter().map(Deref::deref));
2048 }
2049 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2050cmd.verbatim_args(args.iter().map(Deref::deref));
2051 }
2052if let Some(args) = sess.target.late_link_args.get(&flavor) {
2053cmd.verbatim_args(args.iter().map(Deref::deref));
2054 }
2055}
20562057/// Add arbitrary "post-link" args defined by the target spec.
2058/// FIXME: Determine where exactly these args need to be inserted.
2059fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2060if let Some(args) = sess.target.post_link_args.get(&flavor) {
2061cmd.verbatim_args(args.iter().map(Deref::deref));
2062 }
2063}
20642065/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2066/// the linker.
2067///
2068/// Background: we implement rlibs as static library (archives). Linkers treat archives
2069/// differently from object files: all object files participate in linking, while archives will
2070/// only participate in linking if they can satisfy at least one undefined reference (version
2071/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2072/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2073/// can't keep them either. This causes #47384.
2074///
2075/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2076/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2077/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2078/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2079/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2080/// from removing them, and this is especially problematic for embedded programming where every
2081/// byte counts.
2082///
2083/// This method creates a synthetic object file, which contains undefined references to all symbols
2084/// that are necessary for the linking. They are only present in symbol table but not actually
2085/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2086/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2087///
2088/// There's a few internal crates in the standard library (aka libcore and
2089/// libstd) which actually have a circular dependence upon one another. This
2090/// currently arises through "weak lang items" where libcore requires things
2091/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2092/// circular dependence to work correctly we declare some of these things
2093/// in this synthetic object.
2094fn add_linked_symbol_object(
2095 cmd: &mut dyn Linker,
2096 sess: &Session,
2097 tmpdir: &Path,
2098 symbols: &[(String, SymbolExportKind)],
2099) {
2100if symbols.is_empty() {
2101return;
2102 }
21032104let Some(mut file) = super::metadata::create_object_file(sess) else {
2105return;
2106 };
21072108if file.format() == object::BinaryFormat::Coff {
2109// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2110 // so add an empty section.
2111file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
21122113// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2114 // default mangler in `object` crate.
2115file.set_mangling(object::write::Mangling::None);
2116 }
21172118if file.format() == object::BinaryFormat::MachO {
2119// Divide up the sections into sub-sections via symbols for dead code stripping.
2120 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2121 // discard on MachO targets.
2122file.set_subsections_via_symbols();
2123 }
21242125// ld64 requires a relocation to load undefined symbols, see below.
2126 // Not strictly needed if linking with lld, but might as well do it there too.
2127let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2128Some(file.add_section(
2129file.segment_name(object::write::StandardSegment::Data).to_vec(),
2130"__data".into(),
2131 object::SectionKind::Data,
2132 ))
2133 } else {
2134None2135 };
21362137for (sym, kind) in symbols.iter() {
2138let symbol = file.add_symbol(object::write::Symbol {
2139 name: sym.clone().into(),
2140 value: 0,
2141 size: 0,
2142 kind: match kind {
2143 SymbolExportKind::Text => object::SymbolKind::Text,
2144 SymbolExportKind::Data => object::SymbolKind::Data,
2145 SymbolExportKind::Tls => object::SymbolKind::Tls,
2146 },
2147 scope: object::SymbolScope::Unknown,
2148 weak: false,
2149 section: object::write::SymbolSection::Undefined,
2150 flags: object::SymbolFlags::None,
2151 });
21522153// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2154 //
2155 // Code-wise, the relevant parts of ld64 are roughly:
2156 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2157 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2158 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2159 //
2160 // 2. Read the archive table of contents (__.SYMDEF file).
2161 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2162 //
2163 // 3. Begin linking by loading "atoms" from input files.
2164 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2165 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2166 //
2167 // a. Directly specified object files (`.o`) are parsed immediately.
2168 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2169 //
2170 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2171 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2172 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2173 //
2174 // - Relocations/fixups are atoms.
2175 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2176 //
2177 // b. Archives are not parsed yet.
2178 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2179 //
2180 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2181 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2182 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2183 //
2184 // All of the steps above are fairly similar to other linkers, except that **it completely
2185 // ignores undefined symbols**.
2186 //
2187 // So to make this trick work on ld64, we need to do something else to load the relevant
2188 // object files. We do this by inserting a relocation (fixup) for each symbol.
2189if let Some(section) = ld64_section_helper {
2190 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2191 .expect("failed adding relocation");
2192 }
2193 }
21942195let path = tmpdir.join("symbols.o");
2196let result = std::fs::write(&path, file.write().unwrap());
2197if let Err(error) = result {
2198sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2199 }
2200cmd.add_object(&path);
2201}
22022203/// Add object files containing code from the current crate.
2204fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2205for obj in compiled_modules.modules.iter().filter_map(|m| m.object.as_ref()) {
2206 cmd.add_object(obj);
2207 }
2208}
22092210/// Add object files for allocator code linked once for the whole crate tree.
2211fn add_local_crate_allocator_objects(
2212 cmd: &mut dyn Linker,
2213 compiled_modules: &CompiledModules,
2214 crate_info: &CrateInfo,
2215 crate_type: CrateType,
2216) {
2217if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type) {
2218if let Some(obj) =
2219compiled_modules.allocator_module.as_ref().and_then(|m| m.object.as_ref())
2220 {
2221cmd.add_object(obj);
2222 }
2223 }
2224}
22252226/// Add object files containing metadata for the current crate.
2227fn add_local_crate_metadata_objects(
2228 cmd: &mut dyn Linker,
2229 sess: &Session,
2230 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2231 crate_type: CrateType,
2232 tmpdir: &Path,
2233 crate_info: &CrateInfo,
2234 metadata: &EncodedMetadata,
2235) {
2236// When linking a dynamic library, we put the metadata into a section of the
2237 // executable. This metadata is in a separate object file from the main
2238 // object file, so we create and link it in here.
2239if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2240let data = archive_builder_builder.create_dylib_metadata_wrapper(
2241sess,
2242&metadata,
2243&crate_info.metadata_symbol,
2244 );
2245let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
22462247cmd.add_object(&obj);
2248 }
2249}
22502251/// Add sysroot and other globally set directories to the directory search list.
2252fn add_library_search_dirs(
2253 cmd: &mut dyn Linker,
2254 sess: &Session,
2255 self_contained_components: LinkSelfContainedComponents,
2256 apple_sdk_root: Option<&Path>,
2257) {
2258if !sess.opts.unstable_opts.link_native_libraries {
2259return;
2260 }
22612262let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2263let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2264if is_framework {
2265cmd.framework_path(dir);
2266 } else {
2267cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2268 }
2269 ControlFlow::<()>::Continue(())
2270 });
2271}
22722273/// Add options making relocation sections in the produced ELF files read-only
2274/// and suppressing lazy binding.
2275fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2276match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2277 RelroLevel::Full => cmd.full_relro(),
2278 RelroLevel::Partial => cmd.partial_relro(),
2279 RelroLevel::Off => cmd.no_relro(),
2280 RelroLevel::None => {}
2281 }
2282}
22832284/// Add library search paths used at runtime by dynamic linkers.
2285fn add_rpath_args(
2286 cmd: &mut dyn Linker,
2287 sess: &Session,
2288 crate_info: &CrateInfo,
2289 out_filename: &Path,
2290) {
2291if !sess.target.has_rpath {
2292return;
2293 }
22942295// FIXME (#2397): At some point we want to rpath our guesses as to
2296 // where extern libraries might live, based on the
2297 // add_lib_search_paths
2298if sess.opts.cg.rpath {
2299let libs = crate_info2300 .used_crates
2301 .iter()
2302 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2303 .collect::<Vec<_>>();
2304let rpath_config = RPathConfig {
2305 libs: &*libs,
2306 out_filename: out_filename.to_path_buf(),
2307 is_like_darwin: sess.target.is_like_darwin,
2308 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2309 };
2310cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2311 }
2312}
23132314fn add_c_staticlib_symbols(
2315 sess: &Session,
2316 lib: &NativeLib,
2317 out: &mut Vec<(String, SymbolExportKind)>,
2318) -> io::Result<()> {
2319let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
23202321let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
23222323let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2324 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23252326for member in archive.members() {
2327let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23282329let data = member
2330 .data(&*archive_map)
2331 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23322333// clang LTO: raw LLVM bitcode
2334if data.starts_with(b"BC\xc0\xde") {
2335return Err(io::Error::new(
2336 io::ErrorKind::InvalidData,
2337"LLVM bitcode object in C static library (LTO not supported)",
2338 ));
2339 }
23402341let object = object::File::parse(&*data)
2342 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23432344// gcc / clang ELF / Mach-O LTO
2345if object.sections().any(|s| {
2346 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2347 }) {
2348return Err(io::Error::new(
2349 io::ErrorKind::InvalidData,
2350"LTO object in C static library is not supported",
2351 ));
2352 }
23532354for symbol in object.symbols() {
2355if symbol.scope() != object::SymbolScope::Dynamic {
2356continue;
2357 }
23582359let name = match symbol.name() {
2360Ok(n) => n,
2361Err(_) => continue,
2362 };
23632364let export_kind = match symbol.kind() {
2365 object::SymbolKind::Text => SymbolExportKind::Text,
2366 object::SymbolKind::Data => SymbolExportKind::Data,
2367_ => continue,
2368 };
23692370// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2371 // Need to be resolved.
2372out.push((name.to_string(), export_kind));
2373 }
2374 }
23752376Ok(())
2377}
23782379/// Produce the linker command line containing linker path and arguments.
2380///
2381/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2382/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2383/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2384/// to the linking process as a whole.
2385/// Order-independent options may still override each other in order-dependent fashion,
2386/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2387fn linker_with_args(
2388 path: &Path,
2389 flavor: LinkerFlavor,
2390 sess: &Session,
2391 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2392 crate_type: CrateType,
2393 tmpdir: &Path,
2394 out_filename: &Path,
2395 compiled_modules: &CompiledModules,
2396 crate_info: &CrateInfo,
2397 metadata: &EncodedMetadata,
2398 self_contained_components: LinkSelfContainedComponents,
2399 codegen_backend: &'static str,
2400) -> Command {
2401let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2402let cmd = &mut *super::linker::get_linker(
2403sess,
2404path,
2405flavor,
2406self_contained_components.are_any_components_enabled(),
2407&crate_info.target_cpu,
2408codegen_backend,
2409 );
2410let link_output_kind = link_output_kind(sess, crate_type);
24112412let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
24132414if crate_type == CrateType::Cdylib {
2415let mut seen = FxHashSet::default();
24162417for lib in &crate_info.used_libraries {
2418if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2419 && seen.insert((lib.name, lib.verbatim))
2420 {
2421if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2422 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2423"failed to process C static library `{}`: {}",
2424 lib.name, err
2425 ));
2426 }
2427 }
2428 }
2429 }
24302431// ------------ Early order-dependent options ------------
24322433 // If we're building something like a dynamic library then some platforms
2434 // need to make sure that all symbols are exported correctly from the
2435 // dynamic library.
2436 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2437 // at least on some platforms (e.g. windows-gnu).
2438cmd.export_symbols(tmpdir, crate_type, &export_symbols);
24392440// Can be used for adding custom CRT objects or overriding order-dependent options above.
2441 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2442 // introduce a target spec option for order-independent linker options and migrate built-in
2443 // specs to it.
2444add_pre_link_args(cmd, sess, flavor);
24452446// ------------ Object code and libraries, order-dependent ------------
24472448 // Pre-link CRT objects.
2449add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
24502451add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
24522453// Sanitizer libraries.
2454add_sanitizer_libraries(sess, flavor, crate_type, cmd);
24552456// Object code from the current crate.
2457 // Take careful note of the ordering of the arguments we pass to the linker
2458 // here. Linkers will assume that things on the left depend on things to the
2459 // right. Things on the right cannot depend on things on the left. This is
2460 // all formally implemented in terms of resolving symbols (libs on the right
2461 // resolve unknown symbols of libs on the left, but not vice versa).
2462 //
2463 // For this reason, we have organized the arguments we pass to the linker as
2464 // such:
2465 //
2466 // 1. The local object that LLVM just generated
2467 // 2. Local native libraries
2468 // 3. Upstream rust libraries
2469 // 4. Upstream native libraries
2470 //
2471 // The rationale behind this ordering is that those items lower down in the
2472 // list can't depend on items higher up in the list. For example nothing can
2473 // depend on what we just generated (e.g., that'd be a circular dependency).
2474 // Upstream rust libraries are not supposed to depend on our local native
2475 // libraries as that would violate the structure of the DAG, in that
2476 // scenario they are required to link to them as well in a shared fashion.
2477 //
2478 // Note that upstream rust libraries may contain native dependencies as
2479 // well, but they also can't depend on what we just started to add to the
2480 // link line. And finally upstream native libraries can't depend on anything
2481 // in this DAG so far because they can only depend on other native libraries
2482 // and such dependencies are also required to be specified.
2483add_local_crate_regular_objects(cmd, compiled_modules);
2484add_local_crate_metadata_objects(
2485cmd,
2486sess,
2487archive_builder_builder,
2488crate_type,
2489tmpdir,
2490crate_info,
2491metadata,
2492 );
2493add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
24942495// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2496 // at the point at which they are specified on the command line.
2497 // Must be passed before any (dynamic) libraries to have effect on them.
2498 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2499 // so it will ignore unreferenced ELF sections from relocatable objects.
2500 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2501 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2502 // and move this option back to the top.
2503cmd.add_as_needed();
25042505// Local native libraries of all kinds.
2506add_local_native_libraries(
2507cmd,
2508sess,
2509archive_builder_builder,
2510crate_info,
2511tmpdir,
2512link_output_kind,
2513 );
25142515// Upstream rust crates and their non-dynamic native libraries.
2516add_upstream_rust_crates(
2517cmd,
2518sess,
2519archive_builder_builder,
2520crate_info,
2521crate_type,
2522tmpdir,
2523link_output_kind,
2524 );
25252526// Dynamic native libraries from upstream crates.
2527add_upstream_native_libraries(
2528cmd,
2529sess,
2530archive_builder_builder,
2531crate_info,
2532tmpdir,
2533link_output_kind,
2534 );
25352536// Raw-dylibs from all crates.
2537let raw_dylib_dir = tmpdir.join("raw-dylibs");
2538if sess.target.binary_format == BinaryFormat::Elf {
2539// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2540 // instead we need to pass them via -l. To find the stub, we need to add
2541 // the directory of the stub to the linker search path.
2542 // We make an extra directory for this to avoid polluting the search path.
2543if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2544sess.dcx().emit_fatal(errors::CreateTempDir { error })
2545 }
2546cmd.include_path(&raw_dylib_dir);
2547 }
25482549// Link with the import library generated for any raw-dylib functions.
2550if sess.target.is_like_windows {
2551for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2552 sess,
2553 archive_builder_builder,
2554 crate_info.used_libraries.iter(),
2555 tmpdir,
2556true,
2557 ) {
2558 cmd.add_object(&output_path);
2559 }
2560 } else {
2561for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2562 sess,
2563 crate_info.used_libraries.iter(),
2564&raw_dylib_dir,
2565 ) {
2566// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2567cmd.link_dylib_by_name(&link_path, true, as_needed);
2568 }
2569 }
2570// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2571 // they are used within inlined functions or instantiated generic functions. We do this *after*
2572 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2573 // by the linker.
2574let dependency_linkage = crate_info2575 .dependency_formats
2576 .get(&crate_type)
2577 .expect("failed to find crate type in dependency format list");
25782579// We sort the libraries below
2580#[allow(rustc::potential_query_instability)]
2581let mut native_libraries_from_nonstatics = crate_info2582 .native_libraries
2583 .iter()
2584 .filter_map(|(&cnum, libraries)| {
2585if sess.target.is_like_windows {
2586 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2587 } else {
2588Some(libraries)
2589 }
2590 })
2591 .flatten()
2592 .collect::<Vec<_>>();
2593native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
25942595if sess.target.is_like_windows {
2596for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2597 sess,
2598 archive_builder_builder,
2599 native_libraries_from_nonstatics,
2600 tmpdir,
2601false,
2602 ) {
2603 cmd.add_object(&output_path);
2604 }
2605 } else {
2606for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2607 sess,
2608 native_libraries_from_nonstatics,
2609&raw_dylib_dir,
2610 ) {
2611// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2612cmd.link_dylib_by_name(&link_path, true, as_needed);
2613 }
2614 }
26152616// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2617 // command line shorter, reset it to default here before adding more libraries.
2618cmd.reset_per_library_state();
26192620// FIXME: Built-in target specs occasionally use this for linking system libraries,
2621 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2622 // and remove the option.
2623add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
26242625// ------------ Arbitrary order-independent options ------------
26262627 // Add order-independent options determined by rustc from its compiler options,
2628 // target properties and source code.
2629add_order_independent_options(
2630cmd,
2631sess,
2632link_output_kind,
2633self_contained_components,
2634flavor,
2635crate_type,
2636crate_info,
2637out_filename,
2638tmpdir,
2639 );
26402641// Can be used for arbitrary order-independent options.
2642 // In practice may also be occasionally used for linking native libraries.
2643 // Passed after compiler-generated options to support manual overriding when necessary.
2644add_user_defined_link_args(cmd, sess);
26452646// ------------ Builtin configurable linker scripts ------------
2647 // The user's link args should be able to overwrite symbols in the compiler's
2648 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2649 // to work correctly, the user needs to be able to specify linker arguments like
2650 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2651add_link_script(cmd, sess, tmpdir, crate_type);
26522653// ------------ Object code and libraries, order-dependent ------------
26542655 // Post-link CRT objects.
2656add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
26572658// ------------ Late order-dependent options ------------
26592660 // Doesn't really make sense.
2661 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2662 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2663 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2664add_post_link_args(cmd, sess, flavor);
26652666cmd.take_cmd()
2667}
26682669fn add_order_independent_options(
2670 cmd: &mut dyn Linker,
2671 sess: &Session,
2672 link_output_kind: LinkOutputKind,
2673 self_contained_components: LinkSelfContainedComponents,
2674 flavor: LinkerFlavor,
2675 crate_type: CrateType,
2676 crate_info: &CrateInfo,
2677 out_filename: &Path,
2678 tmpdir: &Path,
2679) {
2680// Take care of the flavors and CLI options requesting the `lld` linker.
2681add_lld_args(cmd, sess, flavor, self_contained_components);
26822683add_apple_link_args(cmd, sess, flavor);
26842685let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
26862687if sess.target.os == Os::Fuchsia2688 && crate_type == CrateType::Executable2689 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2690 {
2691let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2692cmd.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"));
2693 }
26942695if sess.target.eh_frame_header {
2696cmd.add_eh_frame_header();
2697 }
26982699// Make the binary compatible with data execution prevention schemes.
2700cmd.add_no_exec();
27012702if self_contained_components.is_crt_objects_enabled() {
2703cmd.no_crt_objects();
2704 }
27052706if sess.target.os == Os::Emscripten {
2707cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2708"-fwasm-exceptions"
2709} else if sess.panic_strategy().unwinds() {
2710"-sDISABLE_EXCEPTION_CATCHING=0"
2711} else {
2712"-sDISABLE_EXCEPTION_CATCHING=1"
2713});
2714 }
27152716if flavor == LinkerFlavor::Llbc {
2717cmd.link_args(&[
2718"--target",
2719&versioned_llvm_target(sess),
2720"--target-cpu",
2721&crate_info.target_cpu,
2722 ]);
2723if crate_info.target_features.len() > 0 {
2724cmd.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(",")));
2725 }
2726 } else if flavor == LinkerFlavor::Ptx {
2727cmd.link_args(&["--fallback-arch", &crate_info.target_cpu]);
2728 } else if flavor == LinkerFlavor::Bpf {
2729cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2730if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2731 .into_iter()
2732 .find(|feat| !feat.is_empty())
2733 {
2734cmd.link_args(&["--cpu-features", feat]);
2735 }
2736 }
27372738cmd.linker_plugin_lto();
27392740add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
27412742cmd.output_filename(out_filename);
27432744if crate_type == CrateType::Executable2745 && sess.target.is_like_windows
2746 && let Some(s) = &crate_info.windows_subsystem
2747 {
2748cmd.windows_subsystem(*s);
2749 }
27502751// Try to strip as much out of the generated object by removing unused
2752 // sections if possible. See more comments in linker.rs
2753if !sess.link_dead_code() {
2754// If PGO is enabled sometimes gc_sections will remove the profile data section
2755 // as it appears to be unused. This can then cause the PGO profile file to lose
2756 // some functions. If we are generating a profile we shouldn't strip those metadata
2757 // sections to ensure we have all the data for PGO.
2758let keep_metadata =
2759crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2760cmd.gc_sections(keep_metadata);
2761 }
27622763cmd.set_output_kind(link_output_kind, crate_type, out_filename);
27642765add_relro_args(cmd, sess);
27662767// Pass optimization flags down to the linker.
2768cmd.optimize();
27692770// Gather the set of NatVis files, if any, and write them out to a temp directory.
2771let natvis_visualizers = collect_natvis_visualizers(
2772tmpdir,
2773sess,
2774&crate_info.local_crate_name,
2775&crate_info.natvis_debugger_visualizers,
2776 );
27772778// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2779cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
27802781// We want to prevent the compiler from accidentally leaking in any system libraries,
2782 // so by default we tell linkers not to link to any default libraries.
2783if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2784cmd.no_default_libraries();
2785 }
27862787if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2788cmd.pgo_gen();
2789 }
27902791if sess.opts.unstable_opts.instrument_mcount {
2792cmd.enable_profiling();
2793 }
27942795if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2796cmd.control_flow_guard();
2797 }
27982799// OBJECT-FILES-NO, AUDIT-ORDER
2800if sess.opts.unstable_opts.ehcont_guard {
2801cmd.ehcont_guard();
2802 }
28032804add_rpath_args(cmd, sess, crate_info, out_filename);
2805}
28062807// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2808fn collect_natvis_visualizers(
2809 tmpdir: &Path,
2810 sess: &Session,
2811 crate_name: &Symbol,
2812 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2813) -> Vec<PathBuf> {
2814let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
28152816for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2817let 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));
28182819match fs::write(&visualizer_out_file, &visualizer.src) {
2820Ok(()) => {
2821 visualizer_paths.push(visualizer_out_file);
2822 }
2823Err(error) => {
2824 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2825 path: visualizer_out_file,
2826 error,
2827 });
2828 }
2829 };
2830 }
2831visualizer_paths2832}
28332834fn add_native_libs_from_crate(
2835 cmd: &mut dyn Linker,
2836 sess: &Session,
2837 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2838 crate_info: &CrateInfo,
2839 tmpdir: &Path,
2840 bundled_libs: &FxIndexSet<Symbol>,
2841 cnum: CrateNum,
2842 link_static: bool,
2843 link_dynamic: bool,
2844 link_output_kind: LinkOutputKind,
2845) {
2846if !sess.opts.unstable_opts.link_native_libraries {
2847// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2848 // external build system already has the native dependencies defined, and it
2849 // will provide them to the linker itself.
2850return;
2851 }
28522853if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2854// If rlib contains native libs as archives, unpack them to tmpdir.
2855let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2856archive_builder_builder2857 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2858 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2859 }
28602861let native_libs = match cnum {
2862LOCAL_CRATE => &crate_info.used_libraries,
2863_ => &crate_info.native_libraries[&cnum],
2864 };
28652866let mut last = (None, NativeLibKind::Unspecified, false);
2867for lib in native_libs {
2868if !relevant_lib(sess, lib) {
2869continue;
2870 }
28712872// Skip if this library is the same as the last.
2873last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2874continue;
2875 } else {
2876 (Some(lib.name), lib.kind, lib.verbatim)
2877 };
28782879let name = lib.name.as_str();
2880let verbatim = lib.verbatim;
2881match lib.kind {
2882 NativeLibKind::Static { bundle, whole_archive, .. } => {
2883if link_static {
2884let bundle = bundle.unwrap_or(true);
2885let whole_archive = whole_archive == Some(true);
2886if bundle && cnum != LOCAL_CRATE {
2887if let Some(filename) = lib.filename {
2888// If rlib contains native libs as archives, they are unpacked to tmpdir.
2889let path = tmpdir.join(filename.as_str());
2890 cmd.link_staticlib_by_path(&path, whole_archive);
2891 }
2892 } else {
2893 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2894 }
2895 }
2896 }
2897 NativeLibKind::Dylib { as_needed } => {
2898if link_dynamic {
2899 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2900 }
2901 }
2902 NativeLibKind::Unspecified => {
2903// If we are generating a static binary, prefer static library when the
2904 // link kind is unspecified.
2905if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2906if link_static {
2907 cmd.link_staticlib_by_name(name, verbatim, false);
2908 }
2909 } else if link_dynamic {
2910 cmd.link_dylib_by_name(name, verbatim, true);
2911 }
2912 }
2913 NativeLibKind::Framework { as_needed } => {
2914if link_dynamic {
2915 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2916 }
2917 }
2918 NativeLibKind::RawDylib { as_needed: _ } => {
2919// Handled separately in `linker_with_args`.
2920}
2921 NativeLibKind::WasmImportModule => {}
2922 NativeLibKind::LinkArg => {
2923if link_static {
2924if verbatim {
2925 cmd.verbatim_arg(name);
2926 } else {
2927 cmd.link_arg(name);
2928 }
2929 }
2930 }
2931 }
2932 }
2933}
29342935fn add_local_native_libraries(
2936 cmd: &mut dyn Linker,
2937 sess: &Session,
2938 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2939 crate_info: &CrateInfo,
2940 tmpdir: &Path,
2941 link_output_kind: LinkOutputKind,
2942) {
2943// All static and dynamic native library dependencies are linked to the local crate.
2944let link_static = true;
2945let link_dynamic = true;
2946add_native_libs_from_crate(
2947cmd,
2948sess,
2949archive_builder_builder,
2950crate_info,
2951tmpdir,
2952&Default::default(),
2953LOCAL_CRATE,
2954link_static,
2955link_dynamic,
2956link_output_kind,
2957 );
2958}
29592960fn add_upstream_rust_crates(
2961 cmd: &mut dyn Linker,
2962 sess: &Session,
2963 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2964 crate_info: &CrateInfo,
2965 crate_type: CrateType,
2966 tmpdir: &Path,
2967 link_output_kind: LinkOutputKind,
2968) {
2969// All of the heavy lifting has previously been accomplished by the
2970 // dependency_format module of the compiler. This is just crawling the
2971 // output of that module, adding crates as necessary.
2972 //
2973 // Linking to a rlib involves just passing it to the linker (the linker
2974 // will slurp up the object files inside), and linking to a dynamic library
2975 // involves just passing the right -l flag.
2976let data = crate_info2977 .dependency_formats
2978 .get(&crate_type)
2979 .expect("failed to find crate type in dependency format list");
29802981if sess.target.is_like_aix {
2982// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
2983 // the dependency name when outputting a shared library. Thus, `ld` will
2984 // use the full path to shared libraries as the dependency if passed it
2985 // by default unless `noipath` is passed.
2986 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
2987cmd.link_or_cc_arg("-bnoipath");
2988 }
29892990for &cnum in &crate_info.used_crates {
2991// We may not pass all crates through to the linker. Some crates may appear statically in
2992 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2993 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2994 // Even if they were already included into a dylib
2995 // (e.g. `libstd` when `-C prefer-dynamic` is used).
2996 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
2997 // See the comment in inject_profiler_runtime for why this is the case.
2998let linkage = data[cnum];
2999let link_static_crate = linkage == Linkage::Static
3000 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3001 && (crate_info.compiler_builtins == Some(cnum)
3002 || crate_info.profiler_runtime == Some(cnum));
30033004let mut bundled_libs = Default::default();
3005match linkage {
3006 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3007if link_static_crate {
3008 bundled_libs = crate_info.native_libraries[&cnum]
3009 .iter()
3010 .filter_map(|lib| lib.filename)
3011 .collect();
3012 add_static_crate(
3013 cmd,
3014 sess,
3015 archive_builder_builder,
3016 crate_info,
3017 tmpdir,
3018 cnum,
3019&bundled_libs,
3020 );
3021 }
3022 }
3023 Linkage::Dynamic => {
3024let src = &crate_info.used_crate_source[&cnum];
3025 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3026 }
3027 }
30283029// Static libraries are linked for a subset of linked upstream crates.
3030 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3031 // because the rlib is just an archive.
3032 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3033 // the native library because it is already linked into the dylib, and even if
3034 // inline/const/generic functions from the dylib can refer to symbols from the native
3035 // library, those symbols should be exported and available from the dylib anyway.
3036 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3037let link_static = link_static_crate;
3038// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3039let link_dynamic = false;
3040 add_native_libs_from_crate(
3041 cmd,
3042 sess,
3043 archive_builder_builder,
3044 crate_info,
3045 tmpdir,
3046&bundled_libs,
3047 cnum,
3048 link_static,
3049 link_dynamic,
3050 link_output_kind,
3051 );
3052 }
3053}
30543055fn add_upstream_native_libraries(
3056 cmd: &mut dyn Linker,
3057 sess: &Session,
3058 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3059 crate_info: &CrateInfo,
3060 tmpdir: &Path,
3061 link_output_kind: LinkOutputKind,
3062) {
3063for &cnum in &crate_info.used_crates {
3064// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3065 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3066 // are linked together with their respective upstream crates, and in their originally
3067 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3068 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3069let link_static = false;
3070// Dynamic libraries are linked for all linked upstream crates.
3071 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3072 // because the rlib is just an archive.
3073 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3074 // the native library too because inline/const/generic functions from the dylib can refer
3075 // to symbols from the native library, so the native library providing those symbols should
3076 // be available when linking our final binary.
3077let link_dynamic = true;
3078 add_native_libs_from_crate(
3079 cmd,
3080 sess,
3081 archive_builder_builder,
3082 crate_info,
3083 tmpdir,
3084&Default::default(),
3085 cnum,
3086 link_static,
3087 link_dynamic,
3088 link_output_kind,
3089 );
3090 }
3091}
30923093// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3094// to be relative to the sysroot directory, which may be a relative path specified by the user.
3095//
3096// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3097// linker command line can be non-deterministic due to the paths including the current working
3098// directory. The linker command line needs to be deterministic since it appears inside the PDB
3099// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3100//
3101// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3102fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3103let sysroot_lib_path = &sess.target_tlib_path.dir;
3104let canonical_sysroot_lib_path =
3105 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
31063107let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3108if canonical_lib_dir == canonical_sysroot_lib_path {
3109// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3110sysroot_lib_path.clone()
3111 } else {
3112fix_windows_verbatim_for_gcc(lib_dir)
3113 }
3114}
31153116fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3117if let Some(dir) = path.parent() {
3118let file_name = path.file_name().expect("library path has no file name component");
3119rehome_sysroot_lib_dir(sess, dir).join(file_name)
3120 } else {
3121fix_windows_verbatim_for_gcc(path)
3122 }
3123}
31243125// Adds the static "rlib" versions of all crates to the command line.
3126// There's a bit of magic which happens here specifically related to LTO,
3127// namely that we remove upstream object files.
3128//
3129// When performing LTO, almost(*) all of the bytecode from the upstream
3130// libraries has already been included in our object file output. As a
3131// result we need to remove the object files in the upstream libraries so
3132// the linker doesn't try to include them twice (or whine about duplicate
3133// symbols). We must continue to include the rest of the rlib, however, as
3134// it may contain static native libraries which must be linked in.
3135//
3136// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3137// their bytecode wasn't included. The object files in those libraries must
3138// still be passed to the linker.
3139//
3140// Note, however, that if we're not doing LTO we can just pass the rlib
3141// blindly to the linker (fast) because it's fine if it's not actually
3142// included as we're at the end of the dependency chain.
3143fn add_static_crate(
3144 cmd: &mut dyn Linker,
3145 sess: &Session,
3146 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3147 crate_info: &CrateInfo,
3148 tmpdir: &Path,
3149 cnum: CrateNum,
3150 bundled_lib_file_names: &FxIndexSet<Symbol>,
3151) {
3152let src = &crate_info.used_crate_source[&cnum];
3153let cratepath = src.rlib.as_ref().unwrap();
31543155let mut link_upstream =
3156 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
31573158if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3159 {
3160link_upstream(cratepath);
3161return;
3162 }
31633164let dst = tmpdir.join(cratepath.file_name().unwrap());
3165let name = cratepath.file_name().unwrap().to_str().unwrap();
3166let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3167let bundled_lib_file_names = bundled_lib_file_names.clone();
31683169sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3170let canonical_name = name.replace('-', "_");
3171let upstream_rust_objects_already_included =
3172are_upstream_rust_objects_already_included(sess);
3173let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
31743175let mut archive = archive_builder_builder.new_archive_builder(sess);
3176if let Err(error) = archive.add_archive(
3177cratepath,
3178Box::new(move |f| {
3179if f == METADATA_FILENAME {
3180return true;
3181 }
31823183let canonical = f.replace('-', "_");
31843185let is_rust_object =
3186canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
31873188// If we're performing LTO and this is a rust-generated object
3189 // file, then we don't need the object file as it's part of the
3190 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3191 // though, so we let that object file slide.
3192if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3193return true;
3194 }
31953196// We skip native libraries because:
3197 // 1. This native libraries won't be used from the generated rlib,
3198 // so we can throw them away to avoid the copying work.
3199 // 2. We can't allow it to be a single remaining entry in archive
3200 // as some linkers may complain on that.
3201if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3202return true;
3203 }
32043205false
3206}),
3207 ) {
3208sess.dcx()
3209 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3210 }
3211if archive.build(&dst) {
3212link_upstream(&dst);
3213 }
3214 });
3215}
32163217// Same thing as above, but for dynamic crates instead of static crates.
3218fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3219cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3220}
32213222fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3223match lib.cfg {
3224Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3225None => true,
3226 }
3227}
32283229pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3230match sess.lto() {
3231 config::Lto::Fat => true,
3232 config::Lto::Thin => {
3233// If we defer LTO to the linker, we haven't run LTO ourselves, so
3234 // any upstream object files have not been copied yet.
3235!sess.opts.cg.linker_plugin_lto.enabled()
3236 }
3237 config::Lto::No | config::Lto::ThinLocal => false,
3238 }
3239}
32403241/// We need to communicate five things to the linker on Apple/Darwin targets:
3242/// - The architecture.
3243/// - The operating system (and that it's an Apple platform).
3244/// - The environment.
3245/// - The deployment target.
3246/// - The SDK version.
3247fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3248if !sess.target.is_like_darwin {
3249return;
3250 }
3251let LinkerFlavor::Darwin(cc, _) = flavorelse {
3252return;
3253 };
32543255// `sess.target.arch` (`target_arch`) is not detailed enough.
3256let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3257let target_os = &sess.target.os;
3258let target_env = &sess.target.env;
32593260// The architecture name to forward to the linker.
3261 //
3262 // Supported architecture names can be found in the source:
3263 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3264 //
3265 // Intentionally verbose to ensure that the list always matches correctly
3266 // with the list in the source above.
3267let ld64_arch = match llvm_arch {
3268"armv7k" => "armv7k",
3269"armv7s" => "armv7s",
3270"arm64" => "arm64",
3271"arm64e" => "arm64e",
3272"arm64_32" => "arm64_32",
3273// ld64 doesn't understand i686, so fall back to i386 instead.
3274 //
3275 // Same story when linking with cc, since that ends up invoking ld64.
3276"i386" | "i686" => "i386",
3277"x86_64" => "x86_64",
3278"x86_64h" => "x86_64h",
3279_ => ::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),
3280 };
32813282if cc == Cc::No {
3283// From the man page for ld64 (`man ld`):
3284 // > The linker accepts universal (multiple-architecture) input files,
3285 // > but always creates a "thin" (single-architecture), standard
3286 // > Mach-O output file. The architecture for the output file is
3287 // > specified using the -arch option.
3288 //
3289 // The linker has heuristics to determine the desired architecture,
3290 // but to be safe, and to avoid a warning, we set the architecture
3291 // explicitly.
3292cmd.link_args(&["-arch", ld64_arch]);
32933294// Man page says that ld64 supports the following platform names:
3295 // > - macos
3296 // > - ios
3297 // > - tvos
3298 // > - watchos
3299 // > - bridgeos
3300 // > - visionos
3301 // > - xros
3302 // > - mac-catalyst
3303 // > - ios-simulator
3304 // > - tvos-simulator
3305 // > - watchos-simulator
3306 // > - visionos-simulator
3307 // > - xros-simulator
3308 // > - driverkit
3309let platform_name = match (target_os, target_env) {
3310 (os, Env::Unspecified) => os.desc(),
3311 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3312 (Os::IOs, Env::Sim) => "ios-simulator",
3313 (Os::TvOs, Env::Sim) => "tvos-simulator",
3314 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3315 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3316_ => ::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}"),
3317 };
33183319let min_version = sess.apple_deployment_target().fmt_full().to_string();
33203321// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3322 // - By dyld to give extra warnings and errors, see e.g.:
3323 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3324 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3325 // - By system frameworks to change certain behaviour. For example, the default value of
3326 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3327 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3328 //
3329 // We do not currently know the actual SDK version though, so we have a few options:
3330 // 1. Use the minimum version supported by rustc.
3331 // 2. Use the same as the deployment target.
3332 // 3. Use an arbitrary recent version.
3333 // 4. Omit the version.
3334 //
3335 // The first option is too low / too conservative, and means that users will not get the
3336 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3337 //
3338 // The second option is similarly conservative, and also wrong since if the user specified a
3339 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3340 // make invalid assumptions about the capabilities of the binary.
3341 //
3342 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3343 // version, and is also wrong for similar reasons as above.
3344 //
3345 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3346 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3347 // it as 0.0, which is again too low/conservative.
3348 //
3349 // Currently, we lie about the SDK version, and choose the second option.
3350 //
3351 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3352 // <https://github.com/rust-lang/rust/issues/129432>
3353let sdk_version = &*min_version;
33543355// From the man page for ld64 (`man ld`):
3356 // > This is set to indicate the platform, oldest supported version of
3357 // > that platform that output is to be used on, and the SDK that the
3358 // > output was built against.
3359 //
3360 // Like with `-arch`, the linker can figure out the platform versions
3361 // itself from the binaries being linked, but to be safe, we specify
3362 // the desired versions here explicitly.
3363cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3364 } else {
3365// cc == Cc::Yes
3366 //
3367 // We'd _like_ to use `-target` everywhere, since that can uniquely
3368 // communicate all the required details except for the SDK version
3369 // (which is read by Clang itself from the SDKROOT), but that doesn't
3370 // work on GCC, and since we don't know whether the `cc` compiler is
3371 // Clang, GCC, or something else, we fall back to other options that
3372 // also work on GCC when compiling for macOS.
3373 //
3374 // Targets other than macOS are ill-supported by GCC (it doesn't even
3375 // support e.g. `-miphoneos-version-min`), so in those cases we can
3376 // fairly safely use `-target`. See also the following, where it is
3377 // made explicit that the recommendation by LLVM developers is to use
3378 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3379if *target_os == Os::MacOs {
3380// `-arch` communicates the architecture.
3381 //
3382 // CC forwards the `-arch` to the linker, so we use the same value
3383 // here intentionally.
3384cmd.cc_args(&["-arch", ld64_arch]);
33853386// The presence of `-mmacosx-version-min` makes CC default to
3387 // macOS, and it sets the deployment target.
3388let version = sess.apple_deployment_target().fmt_full();
3389// Intentionally pass this as a single argument, Clang doesn't
3390 // seem to like it otherwise.
3391cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
33923393// macOS has no environment, so with these two, we've told CC the
3394 // four desired parameters.
3395 //
3396 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3397} else {
3398cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3399 }
3400 }
3401}
34023403fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3404if !sess.target.is_like_darwin {
3405return None;
3406 }
3407let LinkerFlavor::Darwin(cc, _) = flavorelse {
3408return None;
3409 };
34103411// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3412 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3413 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3414 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3415 // instead we invoke `xcrun` manually.
3416 //
3417 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3418 // cause the trampoline binary to skip looking up the SDK itself).
3419let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
34203421if cc == Cc::Yes {
3422// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3423 // - The `--sysroot` flag.
3424 // - The `-isysroot` flag.
3425 // - The `SDKROOT` environment variable.
3426 //
3427 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3428 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3429 // only applies to include header files, but on Apple targets it also applies to libraries
3430 // and frameworks.
3431 //
3432 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3433 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3434 // primarily because that is the same interface that is used when invoking the tool under
3435 // `xcrun -sdk macosx $tool`.
3436 //
3437 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3438 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3439 //
3440 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3441 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3442 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3443 //
3444 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3445 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3446 // ignoring the value we set here, and instead use their built-in sysroot).
3447cmd.cmd().env("SDKROOT", &sdkroot);
3448 } else {
3449// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3450 // read by the linker, so it's really the only option.
3451 //
3452 // This is also what Clang does.
3453cmd.link_arg("-syslibroot");
3454cmd.link_arg(&sdkroot);
3455 }
34563457Some(sdkroot)
3458}
34593460fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3461if let Ok(sdkroot) = env::var("SDKROOT") {
3462let p = PathBuf::from(&sdkroot);
34633464// Ignore invalid SDKs, similar to what clang does:
3465 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3466 //
3467 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3468 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3469 // clearly set for the wrong platform.
3470 //
3471 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3472match &*apple::sdk_name(&sess.target).to_lowercase() {
3473"appletvos"
3474if sdkroot.contains("TVSimulator.platform")
3475 || sdkroot.contains("MacOSX.platform") => {}
3476"appletvsimulator"
3477if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3478"iphoneos"
3479if sdkroot.contains("iPhoneSimulator.platform")
3480 || sdkroot.contains("MacOSX.platform") => {}
3481"iphonesimulator"
3482if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3483 }
3484"macosx"
3485if sdkroot.contains("iPhoneOS.platform")
3486 || sdkroot.contains("iPhoneSimulator.platform")
3487 || sdkroot.contains("AppleTVOS.platform")
3488 || sdkroot.contains("AppleTVSimulator.platform")
3489 || sdkroot.contains("WatchOS.platform")
3490 || sdkroot.contains("WatchSimulator.platform")
3491 || sdkroot.contains("XROS.platform")
3492 || sdkroot.contains("XRSimulator.platform") => {}
3493"watchos"
3494if sdkroot.contains("WatchSimulator.platform")
3495 || sdkroot.contains("MacOSX.platform") => {}
3496"watchsimulator"
3497if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3498"xros"
3499if sdkroot.contains("XRSimulator.platform")
3500 || sdkroot.contains("MacOSX.platform") => {}
3501"xrsimulator"
3502if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3503// Ignore `SDKROOT` if it's not a valid path.
3504_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3505_ => return Some(p),
3506 }
3507 }
35083509 apple::get_sdk_root(sess)
3510}
35113512/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3513/// invoke it:
3514/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3515/// - or any `lld` available to `cc`.
3516fn add_lld_args(
3517 cmd: &mut dyn Linker,
3518 sess: &Session,
3519 flavor: LinkerFlavor,
3520 self_contained_components: LinkSelfContainedComponents,
3521) {
3522{
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:3522",
"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(3522u32),
::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!(
3523"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3524 flavor, self_contained_components,
3525 );
35263527// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3528 // we don't need to do anything.
3529if !(flavor.uses_cc() && flavor.uses_lld()) {
3530return;
3531 }
35323533// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3534 // directories to the tool's search path, depending on a mix between what users can specify on
3535 // the CLI, and what the target spec enables (as it can't disable components):
3536 // - if the self-contained linker is enabled on the CLI or by the target spec,
3537 // - and if the self-contained linker is not disabled on the CLI.
3538let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3539let self_contained_target = self_contained_components.is_linker_enabled();
35403541let self_contained_linker = self_contained_cli || self_contained_target;
3542if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3543let mut linker_path_exists = false;
3544for path in sess.get_tools_search_paths(false) {
3545let linker_path = path.join("gcc-ld");
3546 linker_path_exists |= linker_path.exists();
3547 cmd.cc_arg({
3548let mut arg = OsString::from("-B");
3549 arg.push(linker_path);
3550 arg
3551 });
3552 }
3553if !linker_path_exists {
3554// As a sanity check, we emit an error if none of these paths exist: we want
3555 // self-contained linking and have no linker.
3556sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3557 }
3558 }
35593560// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3561 // `lld` as the linker.
3562 //
3563 // Note that wasm targets skip this step since the only option there anyway
3564 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3565 // this, `wasm-component-ld`, which is overridden if this option is passed.
3566if !sess.target.is_like_wasm {
3567cmd.cc_arg("-fuse-ld=lld");
3568 }
35693570if !flavor.is_gnu() {
3571// Tell clang to use a non-default LLD flavor.
3572 // Gcc doesn't understand the target option, but we currently assume
3573 // that gcc is not used for Apple and Wasm targets (#97402).
3574 //
3575 // Note that we don't want to do that by default on macOS: e.g. passing a
3576 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3577 // shown in issue #101653 and the discussion in PR #101792.
3578 //
3579 // It could be required in some cases of cross-compiling with
3580 // LLD, but this is generally unspecified, and we don't know
3581 // which specific versions of clang, macOS SDK, host and target OS
3582 // combinations impact us here.
3583 //
3584 // So we do a simple first-approximation until we know more of what the
3585 // Apple targets require (and which would be handled prior to hitting this
3586 // LLD codepath anyway), but the expectation is that until then
3587 // this should be manually passed if needed. We specify the target when
3588 // targeting a different linker flavor on macOS, and that's also always
3589 // the case when targeting WASM.
3590if sess.target.linker_flavor != sess.host.linker_flavor {
3591cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3592 }
3593 }
3594}
35953596// gold has been deprecated with binutils 2.44
3597// and is known to behave incorrectly around Rust programs.
3598// There have been reports of being unable to bootstrap with gold:
3599// https://github.com/rust-lang/rust/issues/139425
3600// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3601// emitted with `#[used(linker)]`.
3602fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3603use object::read::elf::{FileHeader, SectionHeader};
3604use object::read::{ReadCache, ReadRef, Result};
3605use object::{Endianness, elf};
36063607fn elf_has_gold_version_note<'a>(
3608 elf: &impl FileHeader,
3609 data: impl ReadRef<'a>,
3610 ) -> Result<bool> {
3611let endian = elf.endian()?;
36123613let section =
3614elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3615if let Some((_, section)) = section3616 && let Some(mut notes) = section.notes(endian, data)?
3617{
3618return Ok(notes.any(|note| {
3619note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3620 }));
3621 }
36223623Ok(false)
3624 }
36253626let data = ReadCache::new(BufReader::new(File::open(path)?));
36273628let was_linked_with_gold = if sess.target.pointer_width == 64 {
3629let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3630elf_has_gold_version_note(elf, &data)?
3631} else if sess.target.pointer_width == 32 {
3632let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3633elf_has_gold_version_note(elf, &data)?
3634} else {
3635return Ok(());
3636 };
36373638if was_linked_with_gold {
3639let mut warn =
3640sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3641warn.help("consider using LLD or ld from GNU binutils instead");
3642warn.emit();
3643 }
3644Ok(())
3645}