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::{
29EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
30walk_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::{
57AddArchiveKind, ArchiveBuilder, ArchiveBuilderBuilder, ArchiveEntryKind, ArchiveSymbols,
58};
59use super::command::Command;
60use super::linker::{self, Linker};
61use super::metadata::{MetadataPosition, create_wrapper_file};
62use super::rpath::{self, RPathConfig};
63use super::{apple, rmeta_link, versioned_llvm_target};
64use crate::base::needs_allocator_shim_for_linking;
65use crate::{CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors};
6667pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
68if let Err(e) = fs::remove_file(path) {
69if e.kind() != io::ErrorKind::NotFound {
70dcx.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));
71 }
72 }
73}
7475/// Performs the linkage portion of the compilation phase. This will generate all
76/// of the requested outputs for this compilation session.
77pub fn link_binary(
78 sess: &Session,
79 archive_builder_builder: &dyn ArchiveBuilderBuilder,
80 compiled_modules: CompiledModules,
81 crate_info: CrateInfo,
82 metadata: EncodedMetadata,
83 outputs: &OutputFilenames,
84 codegen_backend: &'static str,
85) {
86let _timer = sess.timer("link_binary");
87let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
88let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
89for &crate_type in &crate_info.crate_types {
90// Ignore executable crates if we have -Z no-codegen, as they will error.
91if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
92 && !output_metadata
93 && crate_type == CrateType::Executable
94 {
95continue;
96 }
9798if invalid_output_for_target(sess, crate_type) {
99::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);
100 }
101102 sess.time("link_binary_check_files_are_writeable", || {
103for m in &compiled_modules.modules {
104if let Some(obj) = &m.object {
105 check_file_is_writeable(obj, sess);
106 }
107if let Some(obj) = &m.global_asm_object {
108 check_file_is_writeable(obj, sess);
109 }
110 }
111 });
112113if outputs.outputs.should_link() {
114let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
115let tmpdir = TempDirBuilder::new()
116 .prefix("rustc")
117 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
118 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
119let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
120121let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
122let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
123match crate_type {
124 CrateType::Rlib => {
125let _timer = sess.timer("link_rlib");
126{
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:126",
"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(126u32),
::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);
127 link_rlib(
128 sess,
129 archive_builder_builder,
130&compiled_modules,
131&crate_info,
132&metadata,
133 RlibFlavor::Normal,
134&path,
135 )
136 .build(&out_filename, None);
137 }
138 CrateType::StaticLib => {
139 link_staticlib(
140 sess,
141 archive_builder_builder,
142&compiled_modules,
143&crate_info,
144&metadata,
145&out_filename,
146&path,
147 );
148 }
149_ => {
150 link_natively(
151 sess,
152 archive_builder_builder,
153 crate_type,
154&out_filename,
155&compiled_modules,
156&crate_info,
157&metadata,
158 path.as_ref(),
159 codegen_backend,
160 );
161 }
162 }
163if sess.opts.json_artifact_notifications {
164 sess.dcx().emit_artifact_notification(&out_filename, "link");
165 }
166167if sess.prof.enabled()
168 && let Some(artifact_name) = out_filename.file_name()
169 {
170// Record size for self-profiling
171let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
172173 sess.prof.artifact_size(
174"linked_artifact",
175 artifact_name.to_string_lossy(),
176 file_size,
177 );
178 }
179180if sess.target.binary_format == BinaryFormat::Elf {
181if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
182{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:182",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(182u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message", "err"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Error while checking if gold was the linker")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&err) as
&dyn Value))])
});
} else { ; }
};info!(?err, "Error while checking if gold was the linker");
183 }
184 }
185186if output.is_stdout() {
187if output.is_tty() {
188 sess.dcx().emit_err(errors::BinaryOutputToTty {
189 shorthand: OutputType::Exe.shorthand(),
190 });
191 } else if let Err(e) = copy_to_stdout(&out_filename) {
192 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
193 }
194 tempfiles_for_stdout_output.push(out_filename);
195 }
196 }
197 }
198199// Remove the temporary object file and metadata if we aren't saving temps.
200sess.time("link_binary_remove_temps", || {
201// If the user requests that temporaries are saved, don't delete any.
202if sess.opts.cg.save_temps {
203return;
204 }
205206let maybe_remove_temps_from_module =
207 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
208if !preserve_objects && let Some(ref obj) = module.object {
209ensure_removed(sess.dcx(), obj);
210 }
211212if !preserve_objects && let Some(ref obj) = module.global_asm_object {
213ensure_removed(sess.dcx(), obj);
214 }
215216if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
217ensure_removed(sess.dcx(), dwo_obj);
218 }
219 };
220221let remove_temps_from_module =
222 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
223224// Otherwise, always remove the allocator module temporaries.
225if let Some(ref allocator_module) = compiled_modules.allocator_module {
226remove_temps_from_module(allocator_module);
227 }
228229// Remove the temporary files if output goes to stdout
230for temp in tempfiles_for_stdout_output {
231 ensure_removed(sess.dcx(), &temp);
232 }
233234// If no requested outputs require linking, then the object temporaries should
235 // be kept.
236if !sess.opts.output_types.should_link() {
237return;
238 }
239240// Potentially keep objects for their debuginfo.
241let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
242{
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:242",
"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(242u32),
::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);
243244for module in &compiled_modules.modules {
245 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
246 }
247 });
248}
249250// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
251// crate types must use the same dependency formats.
252pub fn each_linked_rlib(
253 info: &CrateInfo,
254 crate_type: Option<CrateType>,
255 f: &mut dyn FnMut(CrateNum, &Path),
256) -> Result<(), errors::LinkRlibError> {
257let fmts = if let Some(crate_type) = crate_type {
258let Some(fmts) = info.dependency_formats.get(&crate_type) else {
259return Err(errors::LinkRlibError::MissingFormat);
260 };
261262fmts263 } else {
264let mut dep_formats = info.dependency_formats.iter();
265let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
266if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
267return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
268 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
269 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
270 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
271 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
272 });
273 }
274list1275 };
276277let used_dep_crates = info.used_crates.iter();
278for &cnum in used_dep_crates {
279match fmts.get(cnum) {
280Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
281Some(_) => {}
282None => return Err(errors::LinkRlibError::MissingFormat),
283 }
284let crate_name = info.crate_name[&cnum];
285let used_crate_source = &info.used_crate_source[&cnum];
286if let Some(path) = &used_crate_source.rlib {
287 f(cnum, path);
288 } else if used_crate_source.rmeta.is_some() {
289return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
290 } else {
291return Err(errors::LinkRlibError::NotFound { crate_name });
292 }
293 }
294Ok(())
295}
296297/// Create an 'rlib'.
298///
299/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
300/// The rlib primarily contains the object file of the crate, but it also some of the object files
301/// from native libraries.
302fn link_rlib<'a>(
303 sess: &'a Session,
304 archive_builder_builder: &dyn ArchiveBuilderBuilder,
305 compiled_modules: &CompiledModules,
306 crate_info: &CrateInfo,
307 metadata: &EncodedMetadata,
308 flavor: RlibFlavor,
309 tmpdir: &MaybeTempDir,
310) -> Box<dyn ArchiveBuilder + 'a> {
311let mut ab = archive_builder_builder.new_archive_builder(sess);
312313// Pre-compute the list of Rust object filenames and materialize the rmeta-link
314 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
315 // placed immediately after metadata in the archive, so consumers can find
316 // it without iterating every archive member.
317let rust_object_files: Vec<String> = compiled_modules318 .modules
319 .iter()
320 .filter_map(|m| m.object.as_ref())
321 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
322 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
323 .collect();
324325let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
326let metadata_link = rmeta_link::RmetaLink { rust_object_files };
327let metadata_link_data = metadata_link.encode();
328let (wrapper, _) =
329create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
330Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
331 } else {
332None333 };
334335let trailing_metadata = match flavor {
336 RlibFlavor::Normal => {
337let (metadata, metadata_position) =
338create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
339let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
340match metadata_position {
341 MetadataPosition::First => {
342// Most of the time metadata in rlib files is wrapped in a "dummy" object
343 // file for the target platform so the rlib can be processed entirely by
344 // normal linkers for the platform. Sometimes this is not possible however.
345 // If it is possible however, placing the metadata object first improves
346 // performance of getting metadata from rlibs.
347ab.add_file(&metadata, ArchiveEntryKind::Other);
348// Place the rmeta-link member immediately after metadata so consumers
349 // can find it without iterating the whole archive.
350if let Some(file) = &metadata_link_file {
351ab.add_file(file, ArchiveEntryKind::Other);
352 }
353None354 }
355 MetadataPosition::Last => Some(metadata),
356 }
357 }
358359 RlibFlavor::StaticlibBase => None,
360 };
361362for m in &compiled_modules.modules {
363if let Some(obj) = m.object.as_ref() {
364 ab.add_file(obj, ArchiveEntryKind::RustObj);
365 }
366367if let Some(obj) = m.global_asm_object.as_ref() {
368 ab.add_file(obj, ArchiveEntryKind::RustObj);
369 }
370371if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
372 ab.add_file(dwarf_obj, ArchiveEntryKind::Other);
373 }
374 }
375376match flavor {
377 RlibFlavor::Normal => {}
378 RlibFlavor::StaticlibBase => {
379if let Some(m) = &compiled_modules.allocator_module {
380if let Some(obj) = &m.object {
381ab.add_file(obj, ArchiveEntryKind::RustObj);
382 }
383if let Some(obj) = &m.global_asm_object {
384ab.add_file(obj, ArchiveEntryKind::RustObj);
385 }
386 }
387 }
388 }
389390// Used if packed_bundled_libs flag enabled.
391let mut packed_bundled_libs = Vec::new();
392393// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
394 // we may not be configured to actually include a static library if we're
395 // adding it here. That's because later when we consume this rlib we'll
396 // decide whether we actually needed the static library or not.
397 //
398 // To do this "correctly" we'd need to keep track of which libraries added
399 // which object files to the archive. We don't do that here, however. The
400 // #[link(cfg(..))] feature is unstable, though, and only intended to get
401 // liblibc working. In that sense the check below just indicates that if
402 // there are any libraries we want to omit object files for at link time we
403 // just exclude all custom object files.
404 //
405 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
406 // feature then we'll need to figure out how to record what objects were
407 // loaded from the libraries found here and then encode that into the
408 // metadata of the rlib we're generating somehow.
409for lib in crate_info.used_libraries.iter() {
410let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
411continue;
412 };
413if flavor == RlibFlavor::Normal
414 && let Some(filename) = lib.filename
415 {
416let path = find_native_static_library(filename.as_str(), true, sess);
417let src = read(path)
418 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
419let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
420let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
421 packed_bundled_libs.push(wrapper_file);
422 } else {
423let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
424 ab.add_archive(&path, AddArchiveKind::Other).unwrap_or_else(|error| {
425 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
426 });
427 }
428 }
429430// On Windows, we add the raw-dylib import libraries to the rlibs already.
431 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
432 // Instead, we add all raw-dylibs to the final link on ELF.
433if sess.target.is_like_windows {
434for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
435 sess,
436 archive_builder_builder,
437 crate_info.used_libraries.iter(),
438 tmpdir.as_ref(),
439true,
440 ) {
441 ab.add_archive(&output_path, AddArchiveKind::Other).unwrap_or_else(|error| {
442 sess.dcx()
443 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
444 });
445 }
446 }
447448if let Some(trailing_metadata) = trailing_metadata {
449// Note that it is important that we add all of our non-object "magical
450 // files" *after* all of the object files in the archive. The reason for
451 // this is as follows:
452 //
453 // * When performing LTO, this archive will be modified to remove
454 // objects from above. The reason for this is described below.
455 //
456 // * When the system linker looks at an archive, it will attempt to
457 // determine the architecture of the archive in order to see whether its
458 // linkable.
459 //
460 // The algorithm for this detection is: iterate over the files in the
461 // archive. Skip magical SYMDEF names. Interpret the first file as an
462 // object file. Read architecture from the object file.
463 //
464 // * As one can probably see, if "metadata" and "foo.bc" were placed
465 // before all of the objects, then the architecture of this archive would
466 // not be correctly inferred once 'foo.o' is removed.
467 //
468 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
469 // file for the target platform so the rlib can be processed entirely by
470 // normal linkers for the platform. Sometimes this is not possible however.
471 //
472 // Basically, all this means is that this code should not move above the
473 // code above.
474ab.add_file(&trailing_metadata, ArchiveEntryKind::Other);
475// Place the rmeta-link member immediately after metadata so consumers can
476 // find it without iterating the whole archive.
477if let Some(file) = &metadata_link_file {
478ab.add_file(file, ArchiveEntryKind::Other);
479 }
480 }
481482// Add all bundled static native library dependencies.
483 // Archives added to the end of .rlib archive, see comment above for the reason.
484for lib in packed_bundled_libs {
485 ab.add_file(&lib, ArchiveEntryKind::Other)
486 }
487488ab489}
490491/// Create a static archive.
492///
493/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
494/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
495/// dependencies as well.
496///
497/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
498/// library dependencies that they're not linked in.
499///
500/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
501/// object file (and also don't prepare the archive with a metadata file).
502fn link_staticlib(
503 sess: &Session,
504 archive_builder_builder: &dyn ArchiveBuilderBuilder,
505 compiled_modules: &CompiledModules,
506 crate_info: &CrateInfo,
507 metadata: &EncodedMetadata,
508 out_filename: &Path,
509 tempdir: &MaybeTempDir,
510) {
511{
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:511",
"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(511u32),
::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);
512let mut ab = link_rlib(
513sess,
514archive_builder_builder,
515compiled_modules,
516crate_info,
517metadata,
518 RlibFlavor::StaticlibBase,
519tempdir,
520 );
521let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
522523let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
524let lto = are_upstream_rust_objects_already_included(sess)
525 && !ignored_for_lto(sess, crate_info, cnum);
526527let native_libs = crate_info.native_libraries[&cnum].iter();
528let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
529let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
530531let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
532ab.add_archive(
533path,
534 AddArchiveKind::Rlib(&|fname: &str, entry_kind| {
535// Ignore metadata and rmeta-link files.
536if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
537return true;
538 }
539540// Don't include Rust objects if LTO is enabled.
541if lto && entry_kind == ArchiveEntryKind::RustObj {
542return true;
543 }
544545// Skip objects for bundled libs.
546if bundled_libs.contains(&Symbol::intern(fname)) {
547return true;
548 }
549550false
551}),
552 )
553 .unwrap();
554555archive_builder_builder556 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
557 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
558559for filename in relevant_libs.iter() {
560let joined = tempdir.as_ref().join(filename.as_str());
561let path = joined.as_path();
562 ab.add_archive(path, AddArchiveKind::Other).unwrap();
563 }
564565all_native_libs.extend(crate_info.native_libraries[&cnum].iter().cloned());
566 });
567if let Err(e) = res {
568sess.dcx().emit_fatal(e);
569 }
570571let hide = sess.opts.unstable_opts.staticlib_hide_internal_symbols;
572let rename = sess.opts.unstable_opts.staticlib_rename_internal_symbols;
573574let exported_symbols = if hide || rename {
575if !#[allow(non_exhaustive_omitted_patterns)] match sess.target.binary_format {
BinaryFormat::Elf | BinaryFormat::MachO => true,
_ => false,
}matches!(sess.target.binary_format, BinaryFormat::Elf | BinaryFormat::MachO) {
576if hide {
577sess.dcx().emit_warn(errors::StaticlibHideInternalSymbolsUnsupported {
578 binary_format: sess.target.archive_format.to_string(),
579 });
580 }
581if rename {
582sess.dcx().emit_warn(errors::StaticlibRenameInternalSymbolsUnsupported {
583 binary_format: sess.target.archive_format.to_string(),
584 });
585 }
586None587 } else {
588crate_info589 .exported_symbols
590 .get(&CrateType::StaticLib)
591 .map(|symbols| symbols.iter().map(|(s, _)| s.clone()).collect())
592 }
593 } else {
594None595 };
596597let symbols = exported_symbols.map(|exported| ArchiveSymbols {
598exported,
599 rename_suffix: rename.then(|| crate_info.symbol_rename_suffix.clone()),
600hide,
601 });
602603ab.build(out_filename, symbols);
604605let crates = crate_info.used_crates.iter();
606607let fmts = crate_info608 .dependency_formats
609 .get(&CrateType::StaticLib)
610 .expect("no dependency formats for staticlib");
611612let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
613for &cnum in crates {
614let Some(Linkage::Dynamic) = fmts.get(cnum) else {
615continue;
616 };
617let crate_name = crate_info.crate_name[&cnum];
618let used_crate_source = &crate_info.used_crate_source[&cnum];
619if let Some(path) = &used_crate_source.dylib {
620 all_rust_dylibs.push(&**path);
621 } else if used_crate_source.rmeta.is_some() {
622 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
623 } else {
624 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
625 }
626 }
627628all_native_libs.extend_from_slice(&crate_info.used_libraries);
629630for print in &sess.opts.prints {
631if print.kind == PrintKind::NativeStaticLibs {
632 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
633 }
634 }
635}
636637/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
638/// DWARF package.
639fn link_dwarf_object(
640 sess: &Session,
641 compiled_modules: &CompiledModules,
642 crate_info: &CrateInfo,
643 executable_out_filename: &Path,
644) {
645let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
646dwp_out_filename.push(".dwp");
647{
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:647",
"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(647u32),
::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);
648649#[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)]
650struct ThorinSession<Relocations> {
651 arena_data: TypedArena<Vec<u8>>,
652 arena_mmap: TypedArena<Mmap>,
653 arena_relocations: TypedArena<Relocations>,
654 }
655656impl<Relocations> ThorinSession<Relocations> {
657fn alloc_mmap(&self, data: Mmap) -> &Mmap {
658&*self.arena_mmap.alloc(data)
659 }
660 }
661662impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
663fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
664&*self.arena_data.alloc(data)
665 }
666667fn alloc_relocation(&self, data: Relocations) -> &Relocations {
668&*self.arena_relocations.alloc(data)
669 }
670671fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
672let file = File::open(&path)?;
673let mmap = (unsafe { Mmap::map(file) })?;
674Ok(self.alloc_mmap(mmap))
675 }
676 }
677678match sess.time("run_thorin", || -> Result<(), thorin::Error> {
679let thorin_sess = ThorinSession::default();
680let mut package = thorin::DwarfPackage::new(&thorin_sess);
681682// Input objs contain .o/.dwo files from the current crate.
683match sess.opts.unstable_opts.split_dwarf_kind {
684 SplitDwarfKind::Single => {
685for m in &compiled_modules.modules {
686if let Some(input_obj) = &m.object {
687 package.add_input_object(input_obj)?;
688 }
689if let Some(input_obj) = &m.global_asm_object {
690 package.add_input_object(input_obj)?;
691 }
692 }
693 }
694 SplitDwarfKind::Split => {
695for input_obj in
696compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
697 {
698 package.add_input_object(input_obj)?;
699 }
700 }
701 }
702703// Input rlibs contain .o/.dwo files from dependencies.
704let input_rlibs = crate_info705 .used_crate_source
706 .items()
707 .filter_map(|(_, csource)| csource.rlib.as_ref())
708 .into_sorted_stable_ord();
709710for input_rlib in input_rlibs {
711{
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::DEBUG,
::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(&["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);
712 package.add_input_object(input_rlib)?;
713 }
714715// Failing to read the referenced objects is expected for dependencies where the path in the
716 // executable will have been cleaned by Cargo, but the referenced objects will be contained
717 // within rlibs provided as inputs.
718 //
719 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
720 // found, but are provided explicitly above.
721 //
722 // Adding an executable is primarily done to make `thorin` check that all the referenced
723 // dwarf objects are found in the end.
724package.add_executable(
725 executable_out_filename,
726 thorin::MissingReferencedObjectBehaviour::Skip,
727 )?;
728729let output_stream = BufWriter::new(
730 OpenOptions::new()
731 .read(true)
732 .write(true)
733 .create(true)
734 .truncate(true)
735 .open(dwp_out_filename)?,
736 );
737let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
738 package.finish()?.emit(&mut output_stream)?;
739 output_stream.result()?;
740 output_stream.into_inner().flush()?;
741742Ok(())
743 }) {
744Ok(()) => {}
745Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
746 }
747}
748749#[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)]
750#[diag("{$inner}")]
751/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
752/// end up with inconsistent languages within the same diagnostic.
753struct LinkerOutput {
754 inner: String,
755}
756757fn is_msvc_link_exe(sess: &Session) -> bool {
758let (linker_path, flavor) = linker_and_flavor(sess);
759sess.target.is_like_msvc
760 && flavor == LinkerFlavor::Msvc(Lld::No)
761// Match exactly "link.exe"
762&& linker_path.to_str() == Some("link.exe")
763}
764765fn is_macos_ld(sess: &Session) -> bool {
766let (_, flavor) = linker_and_flavor(sess);
767sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))768}
769770fn is_windows_gnu_ld(sess: &Session) -> bool {
771let (_, flavor) = linker_and_flavor(sess);
772sess.target.is_like_windows
773 && !sess.target.is_like_msvc
774 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))775 && sess.target.options.cfg_abi != CfgAbi::Llvm776}
777778fn is_windows_gnu_clang(sess: &Session) -> bool {
779let (_, flavor) = linker_and_flavor(sess);
780sess.target.is_like_windows
781 && !sess.target.is_like_msvc
782 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))783 && sess.target.options.cfg_abi == CfgAbi::Llvm784}
785786fn report_linker_output(
787 sess: &Session,
788 levels: CodegenLintLevelSpecs,
789 stdout: &[u8],
790 stderr: &[u8],
791) {
792let mut escaped_stderr = escape_string(&stderr);
793let mut escaped_stdout = escape_string(&stdout);
794let mut linker_info = String::new();
795796{
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:796",
"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(796u32),
::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);
797{
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:797",
"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(797u32),
::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);
798799fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
800let mut output = String::new();
801if let Ok(str) = str::from_utf8(bytes) {
802{
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:802",
"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(802u32),
::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}");
803output = String::with_capacity(str.len());
804for line in str.lines() {
805 f(line.trim(), &mut output);
806 }
807 }
808escape_string(output.trim().as_bytes())
809 }
810811if is_msvc_link_exe(sess) {
812{
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:812",
"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(812u32),
::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");
813814escaped_stdout = for_each(&stdout, |line, output| {
815// Hide some progress messages from link.exe that we don't care about.
816 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
817 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
818 // missing, link.exe prints the path of the missing .exe followed by:
819let ilk_but_no_exe =
820"not found or not built by the last incremental link; performing full link";
821let trimmed = line.trim_start();
822if trimmed.starts_with("Creating library")
823 || trimmed.starts_with("Generating code")
824 || trimmed.starts_with("Finished generating code")
825 || trimmed.ends_with(ilk_but_no_exe)
826 {
827linker_info += line;
828linker_info += "\r\n";
829 } else {
830*output += line;
831*output += "\r\n"
832}
833 });
834 } else if is_macos_ld(sess) {
835{
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:835",
"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(835u32),
::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");
836837// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
838let deployment_mismatch = |line: &str| {
839// ld64 (object files + dylibs) and ld_prime (object files only):
840(line.starts_with("ld: ")
841 && line.contains("was built for newer")
842 && line.contains("than being linked"))
843// ld_prime (Xcode 15+, dylibs only):
844|| (line.starts_with("ld: ")
845 && line.contains("building for")
846 && line.contains("but linking with")
847 && line.contains("which was built for newer version"))
848 };
849// FIXME: This is a real warning we would like to show, but it hits too many crates
850 // to want to turn it on immediately.
851let search_path = |line: &str| {
852line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
853 };
854escaped_stderr = for_each(&stderr, |line, output| {
855// This duplicate library warning is just not helpful at all.
856if line.starts_with("ld: warning: ignoring duplicate libraries: ")
857 || deployment_mismatch(line)
858 || search_path(line)
859 {
860linker_info += line;
861linker_info += "\n";
862 } else {
863*output += line;
864*output += "\n"
865}
866 });
867 } else if is_windows_gnu_ld(sess) {
868{
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:868",
"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(868u32),
::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");
869870let mut saw_exclude_symbol = false;
871// See https://github.com/rust-lang/rust/issues/112368.
872 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
873let exclude_symbols = |line: &str| {
874line.starts_with("Warning: .drectve `-exclude-symbols:")
875 && line.ends_with("' unrecognized")
876 };
877escaped_stderr = for_each(&stderr, |line, output| {
878if exclude_symbols(line) {
879saw_exclude_symbol = true;
880linker_info += line;
881linker_info += "\n";
882 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
883linker_info += line;
884linker_info += "\n";
885 } else {
886*output += line;
887*output += "\n"
888}
889 });
890 } else if is_windows_gnu_clang(sess) {
891{
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:891",
"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(891u32),
::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)");
892escaped_stderr = for_each(&stderr, |line, output| {
893if line.contains("argument unused during compilation: '-nolibc'") {
894linker_info += line;
895linker_info += "\n";
896 } else {
897*output += line;
898*output += "\n"
899}
900 });
901 };
902903let lint_msg = |msg| {
904emit_lint_base(
905sess,
906LINKER_MESSAGES,
907levels.linker_messages,
908None,
909LinkerOutput { inner: msg },
910 );
911 };
912let lint_info = |msg| {
913emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
914 };
915916if !escaped_stderr.is_empty() {
917// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
918escaped_stderr =
919escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
920// Windows GNU LD prints uppercase Warning
921escaped_stderr = escaped_stderr922 .strip_prefix("Warning: ")
923 .unwrap_or(&escaped_stderr)
924 .replace(": warning: ", ": ");
925lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
926 }
927if !escaped_stdout.is_empty() {
928lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
929 }
930if !linker_info.is_empty() {
931lint_info(linker_info);
932 }
933}
934935/// Create a dynamic library or executable.
936///
937/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
938/// files as well.
939fn link_natively(
940 sess: &Session,
941 archive_builder_builder: &dyn ArchiveBuilderBuilder,
942 crate_type: CrateType,
943 out_filename: &Path,
944 compiled_modules: &CompiledModules,
945 crate_info: &CrateInfo,
946 metadata: &EncodedMetadata,
947 tmpdir: &Path,
948 codegen_backend: &'static str,
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!("preparing {0:?} to {1:?}",
crate_type, out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
951let (linker_path, flavor) = linker_and_flavor(sess);
952let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
953954// On AIX, we ship all libraries as .a big_af archive
955 // the expected format is lib<name>.a(libname.so) for the actual
956 // dynamic library. So we link to a temporary .so file to be archived
957 // at the final out_filename location
958let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
959let archive_member =
960should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
961let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
962963let mut cmd = linker_with_args(
964&linker_path,
965flavor,
966sess,
967archive_builder_builder,
968crate_type,
969tmpdir,
970temp_filename,
971compiled_modules,
972crate_info,
973metadata,
974self_contained_components,
975codegen_backend,
976 );
977978 linker::disable_localization(&mut cmd);
979980for (k, v) in sess.target.link_env.as_ref() {
981 cmd.env(k.as_ref(), v.as_ref());
982 }
983for k in sess.target.link_env_remove.as_ref() {
984 cmd.env_remove(k.as_ref());
985 }
986987for print in &sess.opts.prints {
988if print.kind == PrintKind::LinkArgs {
989let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
990 print.out.overwrite(&content, sess);
991 }
992 }
993994// May have not found libraries in the right formats.
995sess.dcx().abort_if_errors();
996997// Invoke the system linker
998{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:998",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(998u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
cmd) as &dyn Value))])
});
} else { ; }
};info!("{cmd:?}");
999let unknown_arg_regex =
1000Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
1001let mut prog;
1002loop {
1003prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
1004let Ok(ref output) = progelse {
1005break;
1006 };
1007if output.status.success() {
1008break;
1009 }
1010let mut out = output.stderr.clone();
1011out.extend(&output.stdout);
1012let out = String::from_utf8_lossy(&out);
10131014// Check to see if the link failed with an error message that indicates it
1015 // doesn't recognize the -no-pie option. If so, re-perform the link step
1016 // without it. This is safe because if the linker doesn't support -no-pie
1017 // then it should not default to linking executables as pie. Different
1018 // versions of gcc seem to use different quotes in the error message so
1019 // don't check for them.
1020if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1021 && unknown_arg_regex.is_match(&out)
1022 && out.contains("-no-pie")
1023 && cmd.get_args().iter().any(|e| e == "-no-pie")
1024 {
1025{
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:1025",
"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(1025u32),
::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);
1026{
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:1026",
"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(1026u32),
::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.");
1027for arg in cmd.take_args() {
1028if arg != "-no-pie" {
1029 cmd.arg(arg);
1030 }
1031 }
1032{
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:1032",
"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(1032u32),
::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:?}");
1033continue;
1034 }
10351036// Check if linking failed with an error message that indicates the driver didn't recognize
1037 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1038 // to spawn multiple instances on the happy path to do version checking, and ensures things
1039 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1040 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1041if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1042 && unknown_arg_regex.is_match(&out)
1043 && out.contains("-fuse-ld=lld")
1044 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
1045 {
1046{
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:1046",
"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(1046u32),
::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);
1047{
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:1047",
"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(1047u32),
::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.");
1048for arg in cmd.take_args() {
1049if arg.to_string_lossy() != "-fuse-ld=lld" {
1050 cmd.arg(arg);
1051 }
1052 }
1053{
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:1053",
"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(1053u32),
::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:?}");
1054continue;
1055 }
10561057// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1058 // Fallback from '-static-pie' to '-static' in that case.
1059if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1060 && unknown_arg_regex.is_match(&out)
1061 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1062 && cmd.get_args().iter().any(|e| e == "-static-pie")
1063 {
1064{
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:1064",
"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(1064u32),
::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);
1065{
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:1065",
"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(1065u32),
::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!(
1066"Linker does not support -static-pie command line option. Retrying with -static instead."
1067);
1068// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1069let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1070let opts = &sess.target;
1071let pre_objects = if self_contained_crt_objects {
1072&opts.pre_link_objects_self_contained
1073 } else {
1074&opts.pre_link_objects
1075 };
1076let post_objects = if self_contained_crt_objects {
1077&opts.post_link_objects_self_contained
1078 } else {
1079&opts.post_link_objects
1080 };
1081let get_objects = |objects: &CrtObjects, kind| {
1082objects1083 .get(&kind)
1084 .iter()
1085 .copied()
1086 .flatten()
1087 .map(|obj| {
1088get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1089 })
1090 .collect::<Vec<_>>()
1091 };
1092let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1093let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1094let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1095let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1096// Assume that we know insertion positions for the replacement arguments from replaced
1097 // arguments, which is true for all supported targets.
1098if !(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());
1099if !(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());
1100for arg in cmd.take_args() {
1101if arg == "-static-pie" {
1102// Replace the output kind.
1103cmd.arg("-static");
1104 } else if pre_objects_static_pie.contains(&arg) {
1105// Replace the pre-link objects (replace the first and remove the rest).
1106cmd.args(mem::take(&mut pre_objects_static));
1107 } else if post_objects_static_pie.contains(&arg) {
1108// Replace the post-link objects (replace the first and remove the rest).
1109cmd.args(mem::take(&mut post_objects_static));
1110 } else {
1111 cmd.arg(arg);
1112 }
1113 }
1114{
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:1114",
"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(1114u32),
::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:?}");
1115continue;
1116 }
11171118break;
1119 }
11201121match prog {
1122Ok(prog) => {
1123if !prog.status.success() {
1124let mut output = prog.stderr.clone();
1125output.extend_from_slice(&prog.stdout);
1126let escaped_output = escape_linker_output(&output, flavor);
1127let err = errors::LinkingFailed {
1128 linker_path: &linker_path,
1129 exit_status: prog.status,
1130 command: cmd,
1131escaped_output,
1132 verbose: sess.opts.verbose,
1133 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1134 };
1135sess.dcx().emit_err(err);
1136// If MSVC's `link.exe` was expected but the return code
1137 // is not a Microsoft LNK error then suggest a way to fix or
1138 // install the Visual Studio build tools.
1139if let Some(code) = prog.status.code() {
1140// All Microsoft `link.exe` linking ror codes are
1141 // four digit numbers in the range 1000 to 9999 inclusive
1142if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1143let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1144let has_linker =
1145 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1146 .is_some();
11471148sess.dcx().emit_note(errors::LinkExeUnexpectedError);
11491150// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1151 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1152const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1153if code == STATUS_STACK_BUFFER_OVERRUN {
1154sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1155 }
11561157if is_vs_installed && has_linker {
1158// the linker is broken
1159sess.dcx().emit_note(errors::RepairVSBuildTools);
1160sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1161 } else if is_vs_installed {
1162// the linker is not installed
1163sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1164 } else {
1165// visual studio is not installed
1166sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1167 }
1168 }
1169 }
11701171sess.dcx().abort_if_errors();
1172 }
11731174{
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:1174",
"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(1174u32),
::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:?}");
1175report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1176 }
1177Err(e) => {
1178let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11791180let err = if linker_not_found {
1181sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1182 } else {
1183sess.dcx().emit_err(errors::UnableToExeLinker {
1184linker_path,
1185 error: e,
1186 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1187 })
1188 };
11891190if sess.target.is_like_msvc && linker_not_found {
1191sess.dcx().emit_note(errors::MsvcMissingLinker);
1192sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1193sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1194 }
1195err.raise_fatal();
1196 }
1197 }
11981199match sess.split_debuginfo() {
1200// If split debug information is disabled or located in individual files
1201 // there's nothing to do here.
1202SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
12031204// If packed split-debuginfo is requested, but the final compilation
1205 // doesn't actually have any debug information, then we skip this step.
1206SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
12071208// On macOS the external `dsymutil` tool is used to create the packed
1209 // debug information. Note that this will read debug information from
1210 // the objects on the filesystem which we'll clean up later.
1211SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1212let prog = Command::new("dsymutil").arg(out_filename).output();
1213match prog {
1214Ok(prog) => {
1215if !prog.status.success() {
1216let mut output = prog.stderr.clone();
1217output.extend_from_slice(&prog.stdout);
1218sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1219 status: prog.status,
1220 output: escape_string(&output),
1221 });
1222 }
1223 }
1224Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1225 }
1226 }
12271228// On MSVC packed debug information is produced by the linker itself so
1229 // there's no need to do anything else here.
1230SplitDebuginfo::Packedif sess.target.is_like_windows => {}
12311232// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1233 //
1234 // We cannot rely on the .o paths in the executable because they may have been
1235 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1236 // the .o/.dwo paths explicitly.
1237SplitDebuginfo::Packed => {
1238link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1239 }
1240 }
12411242let strip = sess.opts.cg.strip;
12431244if sess.target.is_like_darwin {
1245let stripcmd = "rust-objcopy";
1246match (strip, crate_type) {
1247 (Strip::Debuginfo, _) => {
1248strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1249 }
12501251// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1252(
1253 Strip::Symbols,
1254 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1255 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1256 (Strip::Symbols, _) => {
1257strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1258 }
1259 (Strip::None, _) => {}
1260 }
1261 }
12621263if sess.target.is_like_solaris {
1264// Many illumos systems will have both the native 'strip' utility and
1265 // the GNU one. Use the native version explicitly and do not rely on
1266 // what's in the path.
1267 //
1268 // If cross-compiling and there is not a native version, then use
1269 // `llvm-strip` and hope.
1270let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1271match strip {
1272// Always preserve the symbol table (-x).
1273Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1274// Strip::Symbols is handled via the --strip-all linker option.
1275Strip::Symbols => {}
1276 Strip::None => {}
1277 }
1278 }
12791280if sess.target.is_like_aix {
1281// `llvm-strip` doesn't work for AIX - their strip must be used.
1282if !sess.host.is_like_aix {
1283sess.dcx().emit_warn(errors::AixStripNotUsed);
1284 }
1285let stripcmd = "/usr/bin/strip";
1286match strip {
1287 Strip::Debuginfo => {
1288// FIXME: AIX's strip utility only offers option to strip line number information.
1289strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1290 }
1291 Strip::Symbols => {
1292// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1293strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1294 }
1295 Strip::None => {}
1296 }
1297 }
12981299if should_archive {
1300let mut ab = archive_builder_builder.new_archive_builder(sess);
1301ab.add_file(temp_filename, ArchiveEntryKind::Other);
1302ab.build(out_filename, None);
1303 }
1304}
13051306fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1307let mut cmd = Command::new(util);
1308cmd.args(options);
13091310let mut new_path = sess.get_tools_search_paths(false);
1311if let Some(path) = env::var_os("PATH") {
1312new_path.extend(env::split_paths(&path));
1313 }
1314cmd.env("PATH", env::join_paths(new_path).unwrap());
13151316let prog = cmd.arg(out_filename).output();
1317match prog {
1318Ok(prog) => {
1319if !prog.status.success() {
1320let mut output = prog.stderr.clone();
1321output.extend_from_slice(&prog.stdout);
1322sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1323util,
1324 status: prog.status,
1325 output: escape_string(&output),
1326 });
1327 }
1328 }
1329Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1330 }
1331}
13321333fn escape_string(s: &[u8]) -> String {
1334match str::from_utf8(s) {
1335Ok(s) => s.to_owned(),
1336Err(_) => ::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()),
1337 }
1338}
13391340#[cfg(not(windows))]
1341fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1342escape_string(s)
1343}
13441345/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1346/// then try to convert the string from the OEM encoding.
1347#[cfg(windows)]
1348fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1349// This only applies to the actual MSVC linker.
1350if flavour != LinkerFlavor::Msvc(Lld::No) {
1351return escape_string(s);
1352 }
1353match str::from_utf8(s) {
1354Ok(s) => return s.to_owned(),
1355Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1356Some(s) => s,
1357// The string is not UTF-8 and isn't valid for the OEM code page
1358None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1359 },
1360 }
1361}
13621363/// Wrappers around the Windows API.
1364#[cfg(windows)]
1365mod win {
1366use windows::Win32::Globalization::{
1367 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1368 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1369 };
13701371/// Get the Windows system OEM code page. This is most notably the code page
1372 /// used for link.exe's output.
1373pub(super) fn oem_code_page() -> u32 {
1374unsafe {
1375let mut cp: u32 = 0;
1376// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1377 // But the API requires us to pass the data as though it's a [u16] string.
1378let len = size_of::<u32>() / size_of::<u16>();
1379let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1380let len_written = GetLocaleInfoEx(
1381 LOCALE_NAME_SYSTEM_DEFAULT,
1382 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1383Some(data),
1384 );
1385if len_written as usize == len { cp } else { CP_OEMCP }
1386 }
1387 }
1388/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1389 /// The string does not need to be null terminated.
1390 ///
1391 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1392 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1393 ///
1394 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1395 /// any invalid bytes for the expected encoding.
1396pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1397// `MultiByteToWideChar` requires a length to be a "positive integer".
1398if s.len() > isize::MAX as usize {
1399return None;
1400 }
1401// Error if the string is not valid for the expected code page.
1402let flags = MB_ERR_INVALID_CHARS;
1403// Call MultiByteToWideChar twice.
1404 // First to calculate the length then to convert the string.
1405let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1406if len > 0 {
1407let mut utf16 = vec![0; len as usize];
1408 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1409if len > 0 {
1410return utf16.get(..len as usize).map(String::from_utf16_lossy);
1411 }
1412 }
1413None
1414}
1415}
14161417fn add_sanitizer_libraries(
1418 sess: &Session,
1419 flavor: LinkerFlavor,
1420 crate_type: CrateType,
1421 linker: &mut dyn Linker,
1422) {
1423if sess.target.is_like_android {
1424// Sanitizer runtime libraries are provided dynamically on Android
1425 // targets.
1426return;
1427 }
14281429if sess.opts.unstable_opts.external_clangrt {
1430// Linking against in-tree sanitizer runtimes is disabled via
1431 // `-Z external-clangrt`
1432return;
1433 }
14341435if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1436return;
1437 }
14381439// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1440 // which should be linked to both executables and dynamic libraries.
1441 // Everywhere else the runtimes are currently distributed as static
1442 // libraries which should be linked to executables only.
1443if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1444 crate_type,
1445 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1446 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1447 {
1448return;
1449 }
14501451let sanitizer = sess.sanitizers();
1452if sanitizer.contains(SanitizerSet::ADDRESS) {
1453link_sanitizer_runtime(sess, flavor, linker, "asan");
1454 }
1455if sanitizer.contains(SanitizerSet::DATAFLOW) {
1456link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1457 }
1458if sanitizer.contains(SanitizerSet::LEAK)
1459 && !sanitizer.contains(SanitizerSet::ADDRESS)
1460 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1461 {
1462link_sanitizer_runtime(sess, flavor, linker, "lsan");
1463 }
1464if sanitizer.contains(SanitizerSet::MEMORY) {
1465link_sanitizer_runtime(sess, flavor, linker, "msan");
1466 }
1467if sanitizer.contains(SanitizerSet::THREAD) {
1468link_sanitizer_runtime(sess, flavor, linker, "tsan");
1469 }
1470if sanitizer.contains(SanitizerSet::HWADDRESS) {
1471link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1472 }
1473if sanitizer.contains(SanitizerSet::SAFESTACK) {
1474link_sanitizer_runtime(sess, flavor, linker, "safestack");
1475 }
1476if sanitizer.contains(SanitizerSet::REALTIME) {
1477link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1478 }
1479}
14801481fn link_sanitizer_runtime(
1482 sess: &Session,
1483 flavor: LinkerFlavor,
1484 linker: &mut dyn Linker,
1485 name: &str,
1486) {
1487fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1488let path = sess.target_tlib_path.dir.join(filename);
1489if path.exists() {
1490sess.target_tlib_path.dir.clone()
1491 } else {
1492 filesearch::make_target_lib_path(
1493&sess.opts.sysroot.default,
1494sess.opts.target_triple.tuple(),
1495 )
1496 }
1497 }
14981499let channel =
1500::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();
15011502if sess.target.is_like_darwin {
1503// On Apple platforms, the sanitizer is always built as a dylib, and
1504 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1505 // rpath to the library as well (the rpath should be absolute, see
1506 // PR #41352 for details).
1507let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1508let path = find_sanitizer_runtime(sess, &filename);
1509let rpath = path.to_str().expect("non-utf8 component in path");
1510linker.link_args(&["-rpath", rpath]);
1511linker.link_dylib_by_name(&filename, false, true);
1512 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1513// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1514 // compatible ASAN library.
1515linker.link_arg("/INFERASANLIBS");
1516 } else {
1517let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1518let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1519linker.link_staticlib_by_path(&path, true);
1520 }
1521}
15221523/// Returns a boolean indicating whether the specified crate should be ignored
1524/// during LTO.
1525///
1526/// Crates ignored during LTO are not lumped together in the "massive object
1527/// file" that we create and are linked in their normal rlib states. See
1528/// comments below for what crates do not participate in LTO.
1529///
1530/// It's unusual for a crate to not participate in LTO. Typically only
1531/// compiler-specific and unstable crates have a reason to not participate in
1532/// LTO.
1533pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1534// If our target enables builtin function lowering in LLVM then the
1535 // crates providing these functions don't participate in LTO (e.g.
1536 // no_builtins or compiler builtins crates).
1537!sess.target.no_builtins
1538 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1539}
15401541/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1542pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1543fn infer_from(
1544 sess: &Session,
1545 linker: Option<PathBuf>,
1546 flavor: Option<LinkerFlavor>,
1547 features: LinkerFeaturesCli,
1548 ) -> Option<(PathBuf, LinkerFlavor)> {
1549let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1550match (linker, flavor) {
1551 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1552// only the linker flavor is known; use the default linker for the selected flavor
1553(None, Some(flavor)) => Some((
1554PathBuf::from(match flavor {
1555 LinkerFlavor::Gnu(Cc::Yes, _)
1556 | LinkerFlavor::Darwin(Cc::Yes, _)
1557 | LinkerFlavor::WasmLld(Cc::Yes)
1558 | LinkerFlavor::Unix(Cc::Yes) => {
1559if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1560// On historical Solaris systems, "cc" may have
1561 // been Sun Studio, which is not flag-compatible
1562 // with "gcc". This history casts a long shadow,
1563 // and many modern illumos distributions today
1564 // ship GCC as "gcc" without also making it
1565 // available as "cc".
1566"gcc"
1567} else {
1568"cc"
1569}
1570 }
1571 LinkerFlavor::Gnu(_, Lld::Yes)
1572 | LinkerFlavor::Darwin(_, Lld::Yes)
1573 | LinkerFlavor::WasmLld(..)
1574 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1575 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1576"ld"
1577}
1578 LinkerFlavor::Msvc(..) => "link.exe",
1579 LinkerFlavor::EmCc => {
1580if falsecfg!(windows) {
1581"emcc.bat"
1582} else {
1583"emcc"
1584}
1585 }
1586 LinkerFlavor::Bpf => "bpf-linker",
1587 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1588 }),
1589flavor,
1590 )),
1591 (Some(linker), None) => {
1592let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1593sess.dcx().emit_fatal(errors::LinkerFileStem);
1594 });
1595let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1596let flavor = adjust_flavor_to_features(flavor, features);
1597Some((linker, flavor))
1598 }
1599 (None, None) => None,
1600 }
1601 }
16021603// While linker flavors and linker features are isomorphic (and thus targets don't need to
1604 // define features separately), we use the flavor as the root piece of data and have the
1605 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1606 // both yet.
1607fn adjust_flavor_to_features(
1608 flavor: LinkerFlavor,
1609 features: LinkerFeaturesCli,
1610 ) -> LinkerFlavor {
1611// Note: a linker feature cannot be both enabled and disabled on the CLI.
1612if features.enabled.contains(LinkerFeatures::LLD) {
1613flavor.with_lld_enabled()
1614 } else if features.disabled.contains(LinkerFeatures::LLD) {
1615flavor.with_lld_disabled()
1616 } else {
1617flavor1618 }
1619 }
16201621let features = sess.opts.cg.linker_features;
16221623// linker and linker flavor specified via command line have precedence over what the target
1624 // specification specifies
1625let linker_flavor = match sess.opts.cg.linker_flavor {
1626// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1627Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1628// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1629linker_flavor => {
1630linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1631 }
1632 };
1633if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1634return ret;
1635 }
16361637if let Some(ret) = infer_from(
1638sess,
1639sess.target.linker.as_deref().map(PathBuf::from),
1640Some(sess.target.linker_flavor),
1641features,
1642 ) {
1643return ret;
1644 }
16451646::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");
1647}
16481649/// Returns a pair of boolean indicating whether we should preserve the object and
1650/// dwarf object files on the filesystem for their debug information. This is often
1651/// useful with split-dwarf like schemes.
1652fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1653// If the objects don't have debuginfo there's nothing to preserve.
1654if sess.opts.debuginfo == config::DebugInfo::None {
1655return (false, false);
1656 }
16571658match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1659// If there is no split debuginfo then do not preserve objects.
1660(SplitDebuginfo::Off, _) => (false, false),
1661// If there is packed split debuginfo, then the debuginfo in the objects
1662 // has been packaged and the objects can be deleted.
1663(SplitDebuginfo::Packed, _) => (false, false),
1664// If there is unpacked split debuginfo and the current target can not use
1665 // split dwarf, then keep objects.
1666(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1667// If there is unpacked split debuginfo and the target can use split dwarf, then
1668 // keep the object containing that debuginfo (whether that is an object file or
1669 // dwarf object file depends on the split dwarf kind).
1670(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1671 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1672 }
1673}
16741675#[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)]
1676enum RlibFlavor {
1677 Normal,
1678 StaticlibBase,
1679}
16801681fn print_native_static_libs(
1682 sess: &Session,
1683 out: &OutFileName,
1684 all_native_libs: &[NativeLib],
1685 all_rust_dylibs: &[&Path],
1686) {
1687let mut lib_args: Vec<_> = all_native_libs1688 .iter()
1689 .filter(|l| relevant_lib(sess, l))
1690 .filter_map(|lib| {
1691let name = lib.name;
1692match lib.kind {
1693 NativeLibKind::Static { bundle: Some(false), .. }
1694 | NativeLibKind::Dylib { .. }
1695 | NativeLibKind::Unspecified => {
1696let verbatim = lib.verbatim;
1697if sess.target.is_like_msvc {
1698let (prefix, suffix) = sess.staticlib_components(verbatim);
1699Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1700 } else if sess.target.linker_flavor.is_gnu() {
1701Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1702 } else {
1703Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1704 }
1705 }
1706 NativeLibKind::Framework { .. } => {
1707// ld-only syntax, since there are no frameworks in MSVC
1708Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1709 }
1710// These are included, no need to print them
1711NativeLibKind::Static { bundle: None | Some(true), .. }
1712 | NativeLibKind::LinkArg1713 | NativeLibKind::WasmImportModule1714 | NativeLibKind::RawDylib { .. } => None,
1715 }
1716 })
1717// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1718.dedup()
1719 .collect();
1720for path in all_rust_dylibs {
1721// FIXME deduplicate with add_dynamic_crate
17221723 // Just need to tell the linker about where the library lives and
1724 // what its name is
1725let parent = path.parent();
1726if let Some(dir) = parent {
1727let dir = fix_windows_verbatim_for_gcc(dir);
1728if sess.target.is_like_msvc {
1729let mut arg = String::from("/LIBPATH:");
1730 arg.push_str(&dir.display().to_string());
1731 lib_args.push(arg);
1732 } else {
1733 lib_args.push("-L".to_owned());
1734 lib_args.push(dir.display().to_string());
1735 }
1736 }
1737let stem = path.file_stem().unwrap().to_str().unwrap();
1738// Convert library file-stem into a cc -l argument.
1739let lib = if let Some(lib) = stem.strip_prefix("lib")
1740 && !sess.target.is_like_windows
1741 {
1742 lib
1743 } else {
1744 stem
1745 };
1746let path = parent.unwrap_or_else(|| Path::new(""));
1747if sess.target.is_like_msvc {
1748// When producing a dll, the MSVC linker may not actually emit a
1749 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1750 // check to see if the file is there and just omit linking to it if it's
1751 // not present.
1752let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1753if path.join(&name).exists() {
1754 lib_args.push(name);
1755 }
1756 } else {
1757 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1758 }
1759 }
17601761match out {
1762 OutFileName::Real(path) => {
1763out.overwrite(&lib_args.join(" "), sess);
1764sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1765 }
1766 OutFileName::Stdout => {
1767sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1768// Prefix for greppability
1769 // Note: This must not be translated as tools are allowed to depend on this exact string.
1770sess.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(" ")));
1771 }
1772 }
1773}
17741775fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1776let file_path = sess.target_tlib_path.dir.join(name);
1777if file_path.exists() {
1778return file_path;
1779 }
1780// Special directory with objects used only in self-contained linkage mode
1781if self_contained {
1782let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1783if file_path.exists() {
1784return file_path;
1785 }
1786 }
1787for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1788let file_path = search_path.dir.join(name);
1789if file_path.exists() {
1790return file_path;
1791 }
1792 }
1793PathBuf::from(name)
1794}
17951796fn exec_linker(
1797 sess: &Session,
1798 cmd: &Command,
1799 out_filename: &Path,
1800 flavor: LinkerFlavor,
1801 tmpdir: &Path,
1802) -> io::Result<Output> {
1803// When attempting to spawn the linker we run a risk of blowing out the
1804 // size limits for spawning a new process with respect to the arguments
1805 // we pass on the command line.
1806 //
1807 // Here we attempt to handle errors from the OS saying "your list of
1808 // arguments is too big" by reinvoking the linker again with an `@`-file
1809 // that contains all the arguments (aka 'response' files).
1810 // The theory is that this is then accepted on all linkers and the linker
1811 // will read all its options out of there instead of looking at the command line.
1812if !cmd.very_likely_to_exceed_some_spawn_limit() {
1813match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1814Ok(child) => {
1815let output = child.wait_with_output();
1816 flush_linked_file(&output, out_filename)?;
1817return output;
1818 }
1819Err(ref e) if command_line_too_big(e) => {
1820{
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:1820",
"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(1820u32),
::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);
1821 }
1822Err(e) => return Err(e),
1823 }
1824 }
18251826{
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:1826",
"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(1826u32),
::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");
1827let mut cmd2 = cmd.clone();
1828let mut args = String::new();
1829for arg in cmd2.take_args() {
1830 args.push_str(
1831&Escape {
1832 arg: arg.to_str().unwrap(),
1833// Windows-style escaping for @-files is used by
1834 // - all linkers targeting MSVC-like targets, including LLD
1835 // - all LLD flavors running on Windows hosts
1836 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1837is_like_msvc: sess.target.is_like_msvc
1838 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1839 }
1840 .to_string(),
1841 );
1842 args.push('\n');
1843 }
1844let file = tmpdir.join("linker-arguments");
1845let bytes = if sess.target.is_like_msvc {
1846let mut out = Vec::with_capacity((1 + args.len()) * 2);
1847// start the stream with a UTF-16 BOM
1848for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1849// encode in little endian
1850out.push(c as u8);
1851 out.push((c >> 8) as u8);
1852 }
1853out1854 } else {
1855args.into_bytes()
1856 };
1857 fs::write(&file, &bytes)?;
1858cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1859{
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:1859",
"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(1859u32),
::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);
1860let output = cmd2.output();
1861 flush_linked_file(&output, out_filename)?;
1862return output;
18631864#[cfg(not(windows))]
1865fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1866Ok(())
1867 }
18681869#[cfg(windows)]
1870fn flush_linked_file(
1871 command_output: &io::Result<Output>,
1872 out_filename: &Path,
1873 ) -> io::Result<()> {
1874// On Windows, under high I/O load, output buffers are sometimes not flushed,
1875 // even long after process exit, causing nasty, non-reproducible output bugs.
1876 //
1877 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1878 //
1879 // А full writeup of the original Chrome bug can be found at
1880 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18811882if let &Ok(ref out) = command_output {
1883if out.status.success() {
1884if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1885 of.sync_all()?;
1886 }
1887 }
1888 }
18891890Ok(())
1891 }
18921893#[cfg(unix)]
1894fn command_line_too_big(err: &io::Error) -> bool {
1895err.raw_os_error() == Some(::libc::E2BIG)
1896 }
18971898#[cfg(windows)]
1899fn command_line_too_big(err: &io::Error) -> bool {
1900const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1901 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1902 }
19031904#[cfg(not(any(unix, windows)))]
1905fn command_line_too_big(_: &io::Error) -> bool {
1906false
1907}
19081909struct Escape<'a> {
1910 arg: &'a str,
1911 is_like_msvc: bool,
1912 }
19131914impl<'a> fmt::Displayfor Escape<'a> {
1915fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1916if self.is_like_msvc {
1917// This is "documented" at
1918 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1919 //
1920 // Unfortunately there's not a great specification of the
1921 // syntax I could find online (at least) but some local
1922 // testing showed that this seemed sufficient-ish to catch
1923 // at least a few edge cases.
1924f.write_fmt(format_args!("\""))write!(f, "\"")?;
1925for c in self.arg.chars() {
1926match c {
1927'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1928 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1929 }
1930 }
1931f.write_fmt(format_args!("\""))write!(f, "\"")?;
1932 } else {
1933// This is documented at https://linux.die.net/man/1/ld, namely:
1934 //
1935 // > Options in file are separated by whitespace. A whitespace
1936 // > character may be included in an option by surrounding the
1937 // > entire option in either single or double quotes. Any
1938 // > character (including a backslash) may be included by
1939 // > prefixing the character to be included with a backslash.
1940 //
1941 // We put an argument on each line, so all we need to do is
1942 // ensure the line is interpreted as one whole argument.
1943for c in self.arg.chars() {
1944match c {
1945'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1946 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1947 }
1948 }
1949 }
1950Ok(())
1951 }
1952 }
1953}
19541955fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1956let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1957 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1958 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1959 LinkOutputKind::DynamicPicExe1960 }
1961 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1962 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1963 LinkOutputKind::StaticPicExe1964 }
1965 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1966 (_, true, _) => LinkOutputKind::StaticDylib,
1967 (_, false, _) => LinkOutputKind::DynamicDylib,
1968 };
19691970// Adjust the output kind to target capabilities.
1971let opts = &sess.target;
1972let pic_exe_supported = opts.position_independent_executables;
1973let static_pic_exe_supported = opts.static_position_independent_executables;
1974let static_dylib_supported = opts.crt_static_allows_dylibs;
1975match kind {
1976 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1977 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1978 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1979_ => kind,
1980 }
1981}
19821983// Returns true if linker is located within sysroot
1984fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1985let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1986linker.with_extension("exe")
1987 } else {
1988linker.to_path_buf()
1989 };
1990for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1991let full_path = dir.join(&linker_with_extension);
1992// If linker comes from sysroot assume self-contained mode
1993if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1994return false;
1995 }
1996 }
1997true
1998}
19992000/// Various toolchain components used during linking are used from rustc distribution
2001/// instead of being found somewhere on the host system.
2002/// We only provide such support for a very limited number of targets.
2003fn self_contained_components(
2004 sess: &Session,
2005 crate_type: CrateType,
2006 linker: &Path,
2007) -> LinkSelfContainedComponents {
2008// Turn the backwards compatible bool values for `self_contained` into fully inferred
2009 // `LinkSelfContainedComponents`.
2010let self_contained =
2011if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
2012// Emit an error if the user requested self-contained mode on the CLI but the target
2013 // explicitly refuses it.
2014if sess.target.link_self_contained.is_disabled() {
2015sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
2016 }
2017self_contained2018 } else {
2019match sess.target.link_self_contained {
2020 LinkSelfContainedDefault::False => false,
2021 LinkSelfContainedDefault::True => true,
20222023 LinkSelfContainedDefault::WithComponents(components) => {
2024// For target specs with explicitly enabled components, we can return them
2025 // directly.
2026return components;
2027 }
20282029// FIXME: Find a better heuristic for "native musl toolchain is available",
2030 // based on host and linker path, for example.
2031 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2032LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2033 LinkSelfContainedDefault::InferredForMingw => {
2034sess.host == sess.target
2035 && sess.target.cfg_abi != CfgAbi::Uwp2036 && detect_self_contained_mingw(sess, linker)
2037 }
2038 }
2039 };
2040if self_contained {
2041LinkSelfContainedComponents::all()
2042 } else {
2043LinkSelfContainedComponents::empty()
2044 }
2045}
20462047/// Add pre-link object files defined by the target spec.
2048fn add_pre_link_objects(
2049 cmd: &mut dyn Linker,
2050 sess: &Session,
2051 flavor: LinkerFlavor,
2052 link_output_kind: LinkOutputKind,
2053 self_contained: bool,
2054) {
2055// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2056 // so Fuchsia has to be special-cased.
2057let opts = &sess.target;
2058let empty = Default::default();
2059let objects = if self_contained {
2060&opts.pre_link_objects_self_contained
2061 } 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, _))) {
2062&opts.pre_link_objects
2063 } else {
2064&empty2065 };
2066for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2067 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2068 }
2069}
20702071/// Add post-link object files defined by the target spec.
2072fn add_post_link_objects(
2073 cmd: &mut dyn Linker,
2074 sess: &Session,
2075 link_output_kind: LinkOutputKind,
2076 self_contained: bool,
2077) {
2078let objects = if self_contained {
2079&sess.target.post_link_objects_self_contained
2080 } else {
2081&sess.target.post_link_objects
2082 };
2083for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2084 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2085 }
2086}
20872088/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2089/// FIXME: Determine where exactly these args need to be inserted.
2090fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2091if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2092cmd.verbatim_args(args.iter().map(Deref::deref));
2093 }
20942095cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2096}
20972098/// Add a link script embedded in the target, if applicable.
2099fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2100match (crate_type, &sess.target.link_script) {
2101 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2102if !sess.target.linker_flavor.is_gnu() {
2103sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2104 }
21052106let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
21072108let path = tmpdir.join(file_name);
2109if let Err(error) = fs::write(&path, script.as_ref()) {
2110sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2111 }
21122113cmd.link_arg("--script").link_arg(path);
2114 }
2115_ => {}
2116 }
2117}
21182119/// Add arbitrary "user defined" args defined from command line.
2120/// FIXME: Determine where exactly these args need to be inserted.
2121fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2122cmd.verbatim_args(&sess.opts.cg.link_args);
2123}
21242125/// Add arbitrary "late link" args defined by the target spec.
2126/// FIXME: Determine where exactly these args need to be inserted.
2127fn add_late_link_args(
2128 cmd: &mut dyn Linker,
2129 sess: &Session,
2130 flavor: LinkerFlavor,
2131 crate_type: CrateType,
2132 crate_info: &CrateInfo,
2133) {
2134let any_dynamic_crate = crate_type == CrateType::Dylib2135 || crate_type == CrateType::Sdylib2136 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2137*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2138 });
2139if any_dynamic_crate {
2140if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2141cmd.verbatim_args(args.iter().map(Deref::deref));
2142 }
2143 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2144cmd.verbatim_args(args.iter().map(Deref::deref));
2145 }
2146if let Some(args) = sess.target.late_link_args.get(&flavor) {
2147cmd.verbatim_args(args.iter().map(Deref::deref));
2148 }
2149}
21502151/// Add arbitrary "post-link" args defined by the target spec.
2152/// FIXME: Determine where exactly these args need to be inserted.
2153fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2154if let Some(args) = sess.target.post_link_args.get(&flavor) {
2155cmd.verbatim_args(args.iter().map(Deref::deref));
2156 }
2157}
21582159/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2160/// the linker.
2161///
2162/// Background: we implement rlibs as static library (archives). Linkers treat archives
2163/// differently from object files: all object files participate in linking, while archives will
2164/// only participate in linking if they can satisfy at least one undefined reference (version
2165/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2166/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2167/// can't keep them either. This causes #47384.
2168///
2169/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2170/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2171/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2172/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2173/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2174/// from removing them, and this is especially problematic for embedded programming where every
2175/// byte counts.
2176///
2177/// This method creates a synthetic object file, which contains undefined references to all symbols
2178/// that are necessary for the linking. They are only present in symbol table but not actually
2179/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2180/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2181///
2182/// There's a few internal crates in the standard library (aka libcore and
2183/// libstd) which actually have a circular dependence upon one another. This
2184/// currently arises through "weak lang items" where libcore requires things
2185/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2186/// circular dependence to work correctly we declare some of these things
2187/// in this synthetic object.
2188fn add_linked_symbol_object(
2189 cmd: &mut dyn Linker,
2190 sess: &Session,
2191 tmpdir: &Path,
2192 symbols: &[(String, SymbolExportKind)],
2193) {
2194if symbols.is_empty() {
2195return;
2196 }
21972198let Some(mut file) = super::metadata::create_object_file(sess) else {
2199return;
2200 };
22012202if file.format() == object::BinaryFormat::Coff {
2203// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2204 // so add an empty section.
2205file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
22062207// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2208 // default mangler in `object` crate.
2209file.set_mangling(object::write::Mangling::None);
2210 }
22112212if file.format() == object::BinaryFormat::MachO {
2213// Divide up the sections into sub-sections via symbols for dead code stripping.
2214 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2215 // discard on MachO targets.
2216file.set_subsections_via_symbols();
2217 }
22182219// ld64 requires a relocation to load undefined symbols, see below.
2220 // Not strictly needed if linking with lld, but might as well do it there too.
2221let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2222Some(file.add_section(
2223file.segment_name(object::write::StandardSegment::Data).to_vec(),
2224"__data".into(),
2225 object::SectionKind::Data,
2226 ))
2227 } else {
2228None2229 };
22302231for (sym, kind) in symbols.iter() {
2232let symbol = file.add_symbol(object::write::Symbol {
2233 name: sym.clone().into(),
2234 value: 0,
2235 size: 0,
2236 kind: match kind {
2237 SymbolExportKind::Text => object::SymbolKind::Text,
2238 SymbolExportKind::Data => object::SymbolKind::Data,
2239 SymbolExportKind::Tls => object::SymbolKind::Tls,
2240 },
2241 scope: object::SymbolScope::Unknown,
2242 weak: false,
2243 section: object::write::SymbolSection::Undefined,
2244 flags: object::SymbolFlags::None,
2245 });
22462247// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2248 //
2249 // Code-wise, the relevant parts of ld64 are roughly:
2250 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2251 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2252 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2253 //
2254 // 2. Read the archive table of contents (__.SYMDEF file).
2255 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2256 //
2257 // 3. Begin linking by loading "atoms" from input files.
2258 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2259 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2260 //
2261 // a. Directly specified object files (`.o`) are parsed immediately.
2262 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2263 //
2264 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2265 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2266 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2267 //
2268 // - Relocations/fixups are atoms.
2269 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2270 //
2271 // b. Archives are not parsed yet.
2272 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2273 //
2274 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2275 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2276 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2277 //
2278 // All of the steps above are fairly similar to other linkers, except that **it completely
2279 // ignores undefined symbols**.
2280 //
2281 // So to make this trick work on ld64, we need to do something else to load the relevant
2282 // object files. We do this by inserting a relocation (fixup) for each symbol.
2283if let Some(section) = ld64_section_helper {
2284 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2285 .expect("failed adding relocation");
2286 }
2287 }
22882289let path = tmpdir.join("symbols.o");
2290let result = std::fs::write(&path, file.write().unwrap());
2291if let Err(error) = result {
2292sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2293 }
2294cmd.add_object(&path);
2295}
22962297/// Add object files containing code from the current crate.
2298fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2299for m in &compiled_modules.modules {
2300if let Some(obj) = &m.object {
2301 cmd.add_object(obj);
2302 }
2303if let Some(obj) = &m.global_asm_object {
2304 cmd.add_object(obj);
2305 }
2306 }
2307}
23082309/// Add object files for allocator code linked once for the whole crate tree.
2310fn add_local_crate_allocator_objects(
2311 cmd: &mut dyn Linker,
2312 compiled_modules: &CompiledModules,
2313 crate_info: &CrateInfo,
2314 crate_type: CrateType,
2315) {
2316if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2317 && let Some(m) = &compiled_modules.allocator_module
2318 {
2319if let Some(obj) = &m.object {
2320cmd.add_object(obj);
2321 }
2322if let Some(obj) = &m.global_asm_object {
2323cmd.add_object(obj);
2324 }
2325 }
2326}
23272328/// Add object files containing metadata for the current crate.
2329fn add_local_crate_metadata_objects(
2330 cmd: &mut dyn Linker,
2331 sess: &Session,
2332 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2333 crate_type: CrateType,
2334 tmpdir: &Path,
2335 crate_info: &CrateInfo,
2336 metadata: &EncodedMetadata,
2337) {
2338// When linking a dynamic library, we put the metadata into a section of the
2339 // executable. This metadata is in a separate object file from the main
2340 // object file, so we create and link it in here.
2341if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2342let data = archive_builder_builder.create_dylib_metadata_wrapper(
2343sess,
2344&metadata,
2345&crate_info.metadata_symbol,
2346 );
2347let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
23482349cmd.add_object(&obj);
2350 }
2351}
23522353/// Add sysroot and other globally set directories to the directory search list.
2354fn add_library_search_dirs(
2355 cmd: &mut dyn Linker,
2356 sess: &Session,
2357 self_contained_components: LinkSelfContainedComponents,
2358 apple_sdk_root: Option<&Path>,
2359) {
2360if !sess.opts.unstable_opts.link_native_libraries {
2361return;
2362 }
23632364let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2365let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2366if is_framework {
2367cmd.framework_path(dir);
2368 } else {
2369cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2370 }
2371 ControlFlow::<()>::Continue(())
2372 });
2373}
23742375/// Add options making relocation sections in the produced ELF files read-only
2376/// and suppressing lazy binding.
2377fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2378match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2379 RelroLevel::Full => cmd.full_relro(),
2380 RelroLevel::Partial => cmd.partial_relro(),
2381 RelroLevel::Off => cmd.no_relro(),
2382 RelroLevel::None => {}
2383 }
2384}
23852386/// Add library search paths used at runtime by dynamic linkers.
2387fn add_rpath_args(
2388 cmd: &mut dyn Linker,
2389 sess: &Session,
2390 crate_info: &CrateInfo,
2391 out_filename: &Path,
2392) {
2393if !sess.target.has_rpath {
2394return;
2395 }
23962397// FIXME (#2397): At some point we want to rpath our guesses as to
2398 // where extern libraries might live, based on the
2399 // add_lib_search_paths
2400if sess.opts.cg.rpath {
2401let libs = crate_info2402 .used_crates
2403 .iter()
2404 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2405 .collect::<Vec<_>>();
2406let rpath_config = RPathConfig {
2407 libs: &*libs,
2408 out_filename: out_filename.to_path_buf(),
2409 is_like_darwin: sess.target.is_like_darwin,
2410 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2411 };
2412cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2413 }
2414}
24152416fn add_c_staticlib_symbols(
2417 sess: &Session,
2418 lib: &NativeLib,
2419 out: &mut Vec<(String, SymbolExportKind)>,
2420) -> io::Result<()> {
2421let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
24222423let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
24242425let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2426 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24272428for member in archive.members() {
2429let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24302431let data = member
2432 .data(&*archive_map)
2433 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24342435// clang LTO: raw LLVM bitcode
2436if data.starts_with(b"BC\xc0\xde") {
2437return Err(io::Error::new(
2438 io::ErrorKind::InvalidData,
2439"LLVM bitcode object in C static library (LTO not supported)",
2440 ));
2441 }
24422443let object = object::File::parse(&*data)
2444 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24452446// gcc / clang ELF / Mach-O LTO
2447if object.sections().any(|s| {
2448 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2449 }) {
2450return Err(io::Error::new(
2451 io::ErrorKind::InvalidData,
2452"LTO object in C static library is not supported",
2453 ));
2454 }
24552456for symbol in object.symbols() {
2457if symbol.scope() != object::SymbolScope::Dynamic {
2458continue;
2459 }
24602461let name = match symbol.name() {
2462Ok(n) => n,
2463Err(_) => continue,
2464 };
24652466let export_kind = match symbol.kind() {
2467 object::SymbolKind::Text => SymbolExportKind::Text,
2468 object::SymbolKind::Data => SymbolExportKind::Data,
2469_ => continue,
2470 };
24712472// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2473 // Need to be resolved.
2474out.push((name.to_string(), export_kind));
2475 }
2476 }
24772478Ok(())
2479}
24802481/// Produce the linker command line containing linker path and arguments.
2482///
2483/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2484/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2485/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2486/// to the linking process as a whole.
2487/// Order-independent options may still override each other in order-dependent fashion,
2488/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2489fn linker_with_args(
2490 path: &Path,
2491 flavor: LinkerFlavor,
2492 sess: &Session,
2493 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2494 crate_type: CrateType,
2495 tmpdir: &Path,
2496 out_filename: &Path,
2497 compiled_modules: &CompiledModules,
2498 crate_info: &CrateInfo,
2499 metadata: &EncodedMetadata,
2500 self_contained_components: LinkSelfContainedComponents,
2501 codegen_backend: &'static str,
2502) -> Command {
2503let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2504let cmd = &mut *super::linker::get_linker(
2505sess,
2506path,
2507flavor,
2508self_contained_components.are_any_components_enabled(),
2509&crate_info.target_cpu,
2510codegen_backend,
2511 );
2512let link_output_kind = link_output_kind(sess, crate_type);
25132514let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
25152516if crate_type == CrateType::Cdylib {
2517let mut seen = FxHashSet::default();
25182519for lib in &crate_info.used_libraries {
2520if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2521 && seen.insert((lib.name, lib.verbatim))
2522 {
2523if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2524 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2525"failed to process C static library `{}`: {}",
2526 lib.name, err
2527 ));
2528 }
2529 }
2530 }
2531 }
25322533// ------------ Early order-dependent options ------------
25342535 // If we're building something like a dynamic library then some platforms
2536 // need to make sure that all symbols are exported correctly from the
2537 // dynamic library.
2538 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2539 // at least on some platforms (e.g. windows-gnu).
2540cmd.export_symbols(tmpdir, crate_type, &export_symbols);
25412542// Can be used for adding custom CRT objects or overriding order-dependent options above.
2543 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2544 // introduce a target spec option for order-independent linker options and migrate built-in
2545 // specs to it.
2546add_pre_link_args(cmd, sess, flavor);
25472548// ------------ Object code and libraries, order-dependent ------------
25492550 // Pre-link CRT objects.
2551add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
25522553add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
25542555// Sanitizer libraries.
2556add_sanitizer_libraries(sess, flavor, crate_type, cmd);
25572558// Object code from the current crate.
2559 // Take careful note of the ordering of the arguments we pass to the linker
2560 // here. Linkers will assume that things on the left depend on things to the
2561 // right. Things on the right cannot depend on things on the left. This is
2562 // all formally implemented in terms of resolving symbols (libs on the right
2563 // resolve unknown symbols of libs on the left, but not vice versa).
2564 //
2565 // For this reason, we have organized the arguments we pass to the linker as
2566 // such:
2567 //
2568 // 1. The local object that LLVM just generated
2569 // 2. Local native libraries
2570 // 3. Upstream rust libraries
2571 // 4. Upstream native libraries
2572 //
2573 // The rationale behind this ordering is that those items lower down in the
2574 // list can't depend on items higher up in the list. For example nothing can
2575 // depend on what we just generated (e.g., that'd be a circular dependency).
2576 // Upstream rust libraries are not supposed to depend on our local native
2577 // libraries as that would violate the structure of the DAG, in that
2578 // scenario they are required to link to them as well in a shared fashion.
2579 //
2580 // Note that upstream rust libraries may contain native dependencies as
2581 // well, but they also can't depend on what we just started to add to the
2582 // link line. And finally upstream native libraries can't depend on anything
2583 // in this DAG so far because they can only depend on other native libraries
2584 // and such dependencies are also required to be specified.
2585add_local_crate_regular_objects(cmd, compiled_modules);
2586add_local_crate_metadata_objects(
2587cmd,
2588sess,
2589archive_builder_builder,
2590crate_type,
2591tmpdir,
2592crate_info,
2593metadata,
2594 );
2595add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
25962597// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2598 // at the point at which they are specified on the command line.
2599 // Must be passed before any (dynamic) libraries to have effect on them.
2600 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2601 // so it will ignore unreferenced ELF sections from relocatable objects.
2602 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2603 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2604 // and move this option back to the top.
2605cmd.add_as_needed();
26062607// Local native libraries of all kinds.
2608add_local_native_libraries(
2609cmd,
2610sess,
2611archive_builder_builder,
2612crate_info,
2613tmpdir,
2614link_output_kind,
2615 );
26162617// Upstream rust crates and their non-dynamic native libraries.
2618add_upstream_rust_crates(
2619cmd,
2620sess,
2621archive_builder_builder,
2622crate_info,
2623crate_type,
2624tmpdir,
2625link_output_kind,
2626 );
26272628// Dynamic native libraries from upstream crates.
2629add_upstream_native_libraries(
2630cmd,
2631sess,
2632archive_builder_builder,
2633crate_info,
2634tmpdir,
2635link_output_kind,
2636 );
26372638// Raw-dylibs from all crates.
2639let raw_dylib_dir = tmpdir.join("raw-dylibs");
2640if sess.target.binary_format == BinaryFormat::Elf {
2641// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2642 // instead we need to pass them via -l. To find the stub, we need to add
2643 // the directory of the stub to the linker search path.
2644 // We make an extra directory for this to avoid polluting the search path.
2645if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2646sess.dcx().emit_fatal(errors::CreateTempDir { error })
2647 }
2648cmd.include_path(&raw_dylib_dir);
2649 }
26502651// Link with the import library generated for any raw-dylib functions.
2652if sess.target.is_like_windows {
2653for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2654 sess,
2655 archive_builder_builder,
2656 crate_info.used_libraries.iter(),
2657 tmpdir,
2658true,
2659 ) {
2660 cmd.add_object(&output_path);
2661 }
2662 } else {
2663for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2664 sess,
2665 crate_info.used_libraries.iter(),
2666&raw_dylib_dir,
2667 ) {
2668// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2669cmd.link_dylib_by_name(&link_path, true, as_needed);
2670 }
2671 }
2672// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2673 // they are used within inlined functions or instantiated generic functions. We do this *after*
2674 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2675 // by the linker.
2676let dependency_linkage = crate_info2677 .dependency_formats
2678 .get(&crate_type)
2679 .expect("failed to find crate type in dependency format list");
26802681// We sort the libraries below
2682#[allow(rustc::potential_query_instability)]
2683let mut native_libraries_from_nonstatics = crate_info2684 .native_libraries
2685 .iter()
2686 .filter_map(|(&cnum, libraries)| {
2687if sess.target.is_like_windows {
2688 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2689 } else {
2690Some(libraries)
2691 }
2692 })
2693 .flatten()
2694 .collect::<Vec<_>>();
2695native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
26962697if sess.target.is_like_windows {
2698for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2699 sess,
2700 archive_builder_builder,
2701 native_libraries_from_nonstatics,
2702 tmpdir,
2703false,
2704 ) {
2705 cmd.add_object(&output_path);
2706 }
2707 } else {
2708for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2709 sess,
2710 native_libraries_from_nonstatics,
2711&raw_dylib_dir,
2712 ) {
2713// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2714cmd.link_dylib_by_name(&link_path, true, as_needed);
2715 }
2716 }
27172718// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2719 // command line shorter, reset it to default here before adding more libraries.
2720cmd.reset_per_library_state();
27212722// FIXME: Built-in target specs occasionally use this for linking system libraries,
2723 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2724 // and remove the option.
2725add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
27262727// ------------ Arbitrary order-independent options ------------
27282729 // Add order-independent options determined by rustc from its compiler options,
2730 // target properties and source code.
2731add_order_independent_options(
2732cmd,
2733sess,
2734link_output_kind,
2735self_contained_components,
2736flavor,
2737crate_type,
2738crate_info,
2739out_filename,
2740tmpdir,
2741 );
27422743// Can be used for arbitrary order-independent options.
2744 // In practice may also be occasionally used for linking native libraries.
2745 // Passed after compiler-generated options to support manual overriding when necessary.
2746add_user_defined_link_args(cmd, sess);
27472748// ------------ Builtin configurable linker scripts ------------
2749 // The user's link args should be able to overwrite symbols in the compiler's
2750 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2751 // to work correctly, the user needs to be able to specify linker arguments like
2752 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2753add_link_script(cmd, sess, tmpdir, crate_type);
27542755// ------------ Object code and libraries, order-dependent ------------
27562757 // Post-link CRT objects.
2758add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
27592760// ------------ Late order-dependent options ------------
27612762 // Doesn't really make sense.
2763 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2764 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2765 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2766add_post_link_args(cmd, sess, flavor);
27672768cmd.take_cmd()
2769}
27702771fn add_order_independent_options(
2772 cmd: &mut dyn Linker,
2773 sess: &Session,
2774 link_output_kind: LinkOutputKind,
2775 self_contained_components: LinkSelfContainedComponents,
2776 flavor: LinkerFlavor,
2777 crate_type: CrateType,
2778 crate_info: &CrateInfo,
2779 out_filename: &Path,
2780 tmpdir: &Path,
2781) {
2782// Take care of the flavors and CLI options requesting the `lld` linker.
2783add_lld_args(cmd, sess, flavor, self_contained_components);
27842785add_apple_link_args(cmd, sess, flavor);
27862787let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
27882789if sess.target.os == Os::Fuchsia2790 && crate_type == CrateType::Executable2791 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2792 {
2793let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2794cmd.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"));
2795 }
27962797if sess.target.eh_frame_header {
2798cmd.add_eh_frame_header();
2799 }
28002801// Make the binary compatible with data execution prevention schemes.
2802cmd.add_no_exec();
28032804if self_contained_components.is_crt_objects_enabled() {
2805cmd.no_crt_objects();
2806 }
28072808if sess.target.os == Os::Emscripten {
2809cmd.cc_arg("-fwasm-exceptions");
2810 }
28112812if flavor == LinkerFlavor::Llbc {
2813cmd.link_args(&[
2814"--target",
2815&versioned_llvm_target(sess),
2816"--target-cpu",
2817&crate_info.target_cpu,
2818 ]);
2819if crate_info.target_features.len() > 0 {
2820cmd.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(",")));
2821 }
2822 } else if flavor == LinkerFlavor::Bpf {
2823cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2824if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2825 .into_iter()
2826 .find(|feat| !feat.is_empty())
2827 {
2828cmd.link_args(&["--cpu-features", feat]);
2829 }
2830 }
28312832cmd.linker_plugin_lto();
28332834add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
28352836cmd.output_filename(out_filename);
28372838if crate_type == CrateType::Executable2839 && sess.target.is_like_windows
2840 && let Some(s) = &crate_info.windows_subsystem
2841 {
2842cmd.windows_subsystem(*s);
2843 }
28442845// Try to strip as much out of the generated object by removing unused
2846 // sections if possible. See more comments in linker.rs
2847if !sess.link_dead_code() {
2848// If PGO is enabled sometimes gc_sections will remove the profile data section
2849 // as it appears to be unused. This can then cause the PGO profile file to lose
2850 // some functions. If we are generating a profile we shouldn't strip those metadata
2851 // sections to ensure we have all the data for PGO.
2852let keep_metadata =
2853crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2854cmd.gc_sections(keep_metadata);
2855 }
28562857cmd.set_output_kind(link_output_kind, crate_type, out_filename);
28582859add_relro_args(cmd, sess);
28602861// Pass optimization flags down to the linker.
2862cmd.optimize();
28632864// Gather the set of NatVis files, if any, and write them out to a temp directory.
2865let natvis_visualizers = collect_natvis_visualizers(
2866tmpdir,
2867sess,
2868&crate_info.local_crate_name,
2869&crate_info.natvis_debugger_visualizers,
2870 );
28712872// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2873cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
28742875// We want to prevent the compiler from accidentally leaking in any system libraries,
2876 // so by default we tell linkers not to link to any default libraries.
2877if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2878cmd.no_default_libraries();
2879 }
28802881if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2882cmd.pgo_gen();
2883 }
28842885if sess.opts.unstable_opts.instrument_mcount {
2886cmd.enable_profiling();
2887 }
28882889if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2890cmd.control_flow_guard();
2891 }
28922893// OBJECT-FILES-NO, AUDIT-ORDER
2894if sess.opts.unstable_opts.ehcont_guard {
2895cmd.ehcont_guard();
2896 }
28972898add_rpath_args(cmd, sess, crate_info, out_filename);
2899}
29002901// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2902fn collect_natvis_visualizers(
2903 tmpdir: &Path,
2904 sess: &Session,
2905 crate_name: &Symbol,
2906 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2907) -> Vec<PathBuf> {
2908let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
29092910for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2911let 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));
29122913match fs::write(&visualizer_out_file, &visualizer.src) {
2914Ok(()) => {
2915 visualizer_paths.push(visualizer_out_file);
2916 }
2917Err(error) => {
2918 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2919 path: visualizer_out_file,
2920 error,
2921 });
2922 }
2923 };
2924 }
2925visualizer_paths2926}
29272928fn add_native_libs_from_crate(
2929 cmd: &mut dyn Linker,
2930 sess: &Session,
2931 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2932 crate_info: &CrateInfo,
2933 tmpdir: &Path,
2934 bundled_libs: &FxIndexSet<Symbol>,
2935 cnum: CrateNum,
2936 link_static: bool,
2937 link_dynamic: bool,
2938 link_output_kind: LinkOutputKind,
2939) {
2940if !sess.opts.unstable_opts.link_native_libraries {
2941// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2942 // external build system already has the native dependencies defined, and it
2943 // will provide them to the linker itself.
2944return;
2945 }
29462947if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2948// If rlib contains native libs as archives, unpack them to tmpdir.
2949let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2950archive_builder_builder2951 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2952 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2953 }
29542955let native_libs = match cnum {
2956LOCAL_CRATE => &crate_info.used_libraries,
2957_ => &crate_info.native_libraries[&cnum],
2958 };
29592960let mut last = (None, NativeLibKind::Unspecified, false);
2961for lib in native_libs {
2962if !relevant_lib(sess, lib) {
2963continue;
2964 }
29652966// Skip if this library is the same as the last.
2967last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2968continue;
2969 } else {
2970 (Some(lib.name), lib.kind, lib.verbatim)
2971 };
29722973let name = lib.name.as_str();
2974let verbatim = lib.verbatim;
2975match lib.kind {
2976 NativeLibKind::Static { bundle, whole_archive, .. } => {
2977if link_static {
2978let bundle = bundle.unwrap_or(true);
2979let whole_archive = whole_archive == Some(true);
2980if bundle && cnum != LOCAL_CRATE {
2981if let Some(filename) = lib.filename {
2982// If rlib contains native libs as archives, they are unpacked to tmpdir.
2983let path = tmpdir.join(filename.as_str());
2984 cmd.link_staticlib_by_path(&path, whole_archive);
2985 }
2986 } else {
2987 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2988 }
2989 }
2990 }
2991 NativeLibKind::Dylib { as_needed } => {
2992if link_dynamic {
2993 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2994 }
2995 }
2996 NativeLibKind::Unspecified => {
2997// If we are generating a static binary, prefer static library when the
2998 // link kind is unspecified.
2999if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
3000if link_static {
3001 cmd.link_staticlib_by_name(name, verbatim, false);
3002 }
3003 } else if link_dynamic {
3004 cmd.link_dylib_by_name(name, verbatim, true);
3005 }
3006 }
3007 NativeLibKind::Framework { as_needed } => {
3008if link_dynamic {
3009 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
3010 }
3011 }
3012 NativeLibKind::RawDylib { as_needed: _ } => {
3013// Handled separately in `linker_with_args`.
3014}
3015 NativeLibKind::WasmImportModule => {}
3016 NativeLibKind::LinkArg => {
3017if link_static {
3018if verbatim {
3019 cmd.verbatim_arg(name);
3020 } else {
3021 cmd.link_arg(name);
3022 }
3023 }
3024 }
3025 }
3026 }
3027}
30283029fn add_local_native_libraries(
3030 cmd: &mut dyn Linker,
3031 sess: &Session,
3032 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3033 crate_info: &CrateInfo,
3034 tmpdir: &Path,
3035 link_output_kind: LinkOutputKind,
3036) {
3037// All static and dynamic native library dependencies are linked to the local crate.
3038let link_static = true;
3039let link_dynamic = true;
3040add_native_libs_from_crate(
3041cmd,
3042sess,
3043archive_builder_builder,
3044crate_info,
3045tmpdir,
3046&Default::default(),
3047LOCAL_CRATE,
3048link_static,
3049link_dynamic,
3050link_output_kind,
3051 );
3052}
30533054fn add_upstream_rust_crates(
3055 cmd: &mut dyn Linker,
3056 sess: &Session,
3057 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3058 crate_info: &CrateInfo,
3059 crate_type: CrateType,
3060 tmpdir: &Path,
3061 link_output_kind: LinkOutputKind,
3062) {
3063// All of the heavy lifting has previously been accomplished by the
3064 // dependency_format module of the compiler. This is just crawling the
3065 // output of that module, adding crates as necessary.
3066 //
3067 // Linking to a rlib involves just passing it to the linker (the linker
3068 // will slurp up the object files inside), and linking to a dynamic library
3069 // involves just passing the right -l flag.
3070let data = crate_info3071 .dependency_formats
3072 .get(&crate_type)
3073 .expect("failed to find crate type in dependency format list");
30743075if sess.target.is_like_aix {
3076// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3077 // the dependency name when outputting a shared library. Thus, `ld` will
3078 // use the full path to shared libraries as the dependency if passed it
3079 // by default unless `noipath` is passed.
3080 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3081cmd.link_or_cc_arg("-bnoipath");
3082 }
30833084for &cnum in &crate_info.used_crates {
3085// We may not pass all crates through to the linker. Some crates may appear statically in
3086 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3087 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3088 // Even if they were already included into a dylib
3089 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3090 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3091 // See the comment in inject_profiler_runtime for why this is the case.
3092let linkage = data[cnum];
3093let link_static_crate = linkage == Linkage::Static
3094 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3095 && (crate_info.compiler_builtins == Some(cnum)
3096 || crate_info.profiler_runtime == Some(cnum));
30973098let mut bundled_libs = Default::default();
3099match linkage {
3100 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3101if link_static_crate {
3102 bundled_libs = crate_info.native_libraries[&cnum]
3103 .iter()
3104 .filter_map(|lib| lib.filename)
3105 .collect();
3106 add_static_crate(
3107 cmd,
3108 sess,
3109 archive_builder_builder,
3110 crate_info,
3111 tmpdir,
3112 cnum,
3113&bundled_libs,
3114 );
3115 }
3116 }
3117 Linkage::Dynamic => {
3118let src = &crate_info.used_crate_source[&cnum];
3119 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3120 }
3121 }
31223123// Static libraries are linked for a subset of linked upstream crates.
3124 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3125 // because the rlib is just an archive.
3126 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3127 // the native library because it is already linked into the dylib, and even if
3128 // inline/const/generic functions from the dylib can refer to symbols from the native
3129 // library, those symbols should be exported and available from the dylib anyway.
3130 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3131let link_static = link_static_crate;
3132// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3133let link_dynamic = false;
3134 add_native_libs_from_crate(
3135 cmd,
3136 sess,
3137 archive_builder_builder,
3138 crate_info,
3139 tmpdir,
3140&bundled_libs,
3141 cnum,
3142 link_static,
3143 link_dynamic,
3144 link_output_kind,
3145 );
3146 }
3147}
31483149fn add_upstream_native_libraries(
3150 cmd: &mut dyn Linker,
3151 sess: &Session,
3152 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3153 crate_info: &CrateInfo,
3154 tmpdir: &Path,
3155 link_output_kind: LinkOutputKind,
3156) {
3157for &cnum in &crate_info.used_crates {
3158// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3159 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3160 // are linked together with their respective upstream crates, and in their originally
3161 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3162 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3163let link_static = false;
3164// Dynamic libraries are linked for all linked upstream crates.
3165 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3166 // because the rlib is just an archive.
3167 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3168 // the native library too because inline/const/generic functions from the dylib can refer
3169 // to symbols from the native library, so the native library providing those symbols should
3170 // be available when linking our final binary.
3171let link_dynamic = true;
3172 add_native_libs_from_crate(
3173 cmd,
3174 sess,
3175 archive_builder_builder,
3176 crate_info,
3177 tmpdir,
3178&Default::default(),
3179 cnum,
3180 link_static,
3181 link_dynamic,
3182 link_output_kind,
3183 );
3184 }
3185}
31863187// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3188// to be relative to the sysroot directory, which may be a relative path specified by the user.
3189//
3190// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3191// linker command line can be non-deterministic due to the paths including the current working
3192// directory. The linker command line needs to be deterministic since it appears inside the PDB
3193// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3194//
3195// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3196fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3197let sysroot_lib_path = &sess.target_tlib_path.dir;
3198let canonical_sysroot_lib_path =
3199 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
32003201let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3202if canonical_lib_dir == canonical_sysroot_lib_path {
3203// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3204sysroot_lib_path.clone()
3205 } else {
3206fix_windows_verbatim_for_gcc(lib_dir)
3207 }
3208}
32093210fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3211if let Some(dir) = path.parent() {
3212let file_name = path.file_name().expect("library path has no file name component");
3213rehome_sysroot_lib_dir(sess, dir).join(file_name)
3214 } else {
3215fix_windows_verbatim_for_gcc(path)
3216 }
3217}
32183219// Adds the static "rlib" versions of all crates to the command line.
3220// There's a bit of magic which happens here specifically related to LTO,
3221// namely that we remove upstream object files.
3222//
3223// When performing LTO, almost(*) all of the bytecode from the upstream
3224// libraries has already been included in our object file output. As a
3225// result we need to remove the object files in the upstream libraries so
3226// the linker doesn't try to include them twice (or whine about duplicate
3227// symbols). We must continue to include the rest of the rlib, however, as
3228// it may contain static native libraries which must be linked in.
3229//
3230// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3231// their bytecode wasn't included. The object files in those libraries must
3232// still be passed to the linker.
3233//
3234// Note, however, that if we're not doing LTO we can just pass the rlib
3235// blindly to the linker (fast) because it's fine if it's not actually
3236// included as we're at the end of the dependency chain.
3237fn add_static_crate(
3238 cmd: &mut dyn Linker,
3239 sess: &Session,
3240 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3241 crate_info: &CrateInfo,
3242 tmpdir: &Path,
3243 cnum: CrateNum,
3244 bundled_lib_file_names: &FxIndexSet<Symbol>,
3245) {
3246let src = &crate_info.used_crate_source[&cnum];
3247let cratepath = src.rlib.as_ref().unwrap();
32483249let mut link_upstream =
3250 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
32513252if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3253 {
3254link_upstream(cratepath);
3255return;
3256 }
32573258let dst = tmpdir.join(cratepath.file_name().unwrap());
3259let name = cratepath.file_name().unwrap().to_str().unwrap();
3260let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3261let bundled_lib_file_names = bundled_lib_file_names.clone();
32623263sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3264let upstream_rust_objects_already_included =
3265are_upstream_rust_objects_already_included(sess);
3266let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
32673268let mut archive = archive_builder_builder.new_archive_builder(sess);
3269if let Err(error) = archive.add_archive(
3270cratepath,
3271 AddArchiveKind::Rlib(&|f, entry_kind| {
3272if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3273return true;
3274 }
32753276// If we're performing LTO and this is a rust-generated object
3277 // file, then we don't need the object file as it's part of the
3278 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3279 // though, so we let that object file slide.
3280if upstream_rust_objects_already_included3281 && entry_kind == ArchiveEntryKind::RustObj3282 && is_builtins3283 {
3284return true;
3285 }
32863287// We skip native libraries because:
3288 // 1. This native libraries won't be used from the generated rlib,
3289 // so we can throw them away to avoid the copying work.
3290 // 2. We can't allow it to be a single remaining entry in archive
3291 // as some linkers may complain on that.
3292if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3293return true;
3294 }
32953296false
3297}),
3298 ) {
3299sess.dcx()
3300 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3301 }
3302if archive.build(&dst, None) {
3303link_upstream(&dst);
3304 }
3305 });
3306}
33073308// Same thing as above, but for dynamic crates instead of static crates.
3309fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3310cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3311}
33123313fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3314match lib.cfg {
3315Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3316None => true,
3317 }
3318}
33193320pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3321match sess.lto() {
3322 config::Lto::Fat => true,
3323 config::Lto::Thin => {
3324// If we defer LTO to the linker, we haven't run LTO ourselves, so
3325 // any upstream object files have not been copied yet.
3326!sess.opts.cg.linker_plugin_lto.enabled()
3327 }
3328 config::Lto::No | config::Lto::ThinLocal => false,
3329 }
3330}
33313332/// We need to communicate five things to the linker on Apple/Darwin targets:
3333/// - The architecture.
3334/// - The operating system (and that it's an Apple platform).
3335/// - The environment.
3336/// - The deployment target.
3337/// - The SDK version.
3338fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3339if !sess.target.is_like_darwin {
3340return;
3341 }
3342let LinkerFlavor::Darwin(cc, _) = flavorelse {
3343return;
3344 };
33453346// `sess.target.arch` (`target_arch`) is not detailed enough.
3347let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3348let target_os = &sess.target.os;
3349let target_env = &sess.target.env;
33503351// The architecture name to forward to the linker.
3352 //
3353 // Supported architecture names can be found in the source:
3354 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3355 //
3356 // Intentionally verbose to ensure that the list always matches correctly
3357 // with the list in the source above.
3358let ld64_arch = match llvm_arch {
3359"armv7k" => "armv7k",
3360"armv7s" => "armv7s",
3361"arm64" => "arm64",
3362"arm64e" => "arm64e",
3363"arm64_32" => "arm64_32",
3364// ld64 doesn't understand i686, so fall back to i386 instead.
3365 //
3366 // Same story when linking with cc, since that ends up invoking ld64.
3367"i386" | "i686" => "i386",
3368"x86_64" => "x86_64",
3369"x86_64h" => "x86_64h",
3370_ => ::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),
3371 };
33723373if cc == Cc::No {
3374// From the man page for ld64 (`man ld`):
3375 // > The linker accepts universal (multiple-architecture) input files,
3376 // > but always creates a "thin" (single-architecture), standard
3377 // > Mach-O output file. The architecture for the output file is
3378 // > specified using the -arch option.
3379 //
3380 // The linker has heuristics to determine the desired architecture,
3381 // but to be safe, and to avoid a warning, we set the architecture
3382 // explicitly.
3383cmd.link_args(&["-arch", ld64_arch]);
33843385// Man page says that ld64 supports the following platform names:
3386 // > - macos
3387 // > - ios
3388 // > - tvos
3389 // > - watchos
3390 // > - bridgeos
3391 // > - visionos
3392 // > - xros
3393 // > - mac-catalyst
3394 // > - ios-simulator
3395 // > - tvos-simulator
3396 // > - watchos-simulator
3397 // > - visionos-simulator
3398 // > - xros-simulator
3399 // > - driverkit
3400let platform_name = match (target_os, target_env) {
3401 (os, Env::Unspecified) => os.desc(),
3402 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3403 (Os::IOs, Env::Sim) => "ios-simulator",
3404 (Os::TvOs, Env::Sim) => "tvos-simulator",
3405 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3406 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3407_ => ::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}"),
3408 };
34093410let min_version = sess.apple_deployment_target().fmt_full().to_string();
34113412// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3413 // - By dyld to give extra warnings and errors, see e.g.:
3414 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3415 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3416 // - By system frameworks to change certain behaviour. For example, the default value of
3417 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3418 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3419 //
3420 // We do not currently know the actual SDK version though, so we have a few options:
3421 // 1. Use the minimum version supported by rustc.
3422 // 2. Use the same as the deployment target.
3423 // 3. Use an arbitrary recent version.
3424 // 4. Omit the version.
3425 //
3426 // The first option is too low / too conservative, and means that users will not get the
3427 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3428 //
3429 // The second option is similarly conservative, and also wrong since if the user specified a
3430 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3431 // make invalid assumptions about the capabilities of the binary.
3432 //
3433 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3434 // version, and is also wrong for similar reasons as above.
3435 //
3436 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3437 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3438 // it as 0.0, which is again too low/conservative.
3439 //
3440 // Currently, we lie about the SDK version, and choose the second option.
3441 //
3442 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3443 // <https://github.com/rust-lang/rust/issues/129432>
3444let sdk_version = &*min_version;
34453446// From the man page for ld64 (`man ld`):
3447 // > This is set to indicate the platform, oldest supported version of
3448 // > that platform that output is to be used on, and the SDK that the
3449 // > output was built against.
3450 //
3451 // Like with `-arch`, the linker can figure out the platform versions
3452 // itself from the binaries being linked, but to be safe, we specify
3453 // the desired versions here explicitly.
3454cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3455 } else {
3456// cc == Cc::Yes
3457 //
3458 // We'd _like_ to use `-target` everywhere, since that can uniquely
3459 // communicate all the required details except for the SDK version
3460 // (which is read by Clang itself from the SDKROOT), but that doesn't
3461 // work on GCC, and since we don't know whether the `cc` compiler is
3462 // Clang, GCC, or something else, we fall back to other options that
3463 // also work on GCC when compiling for macOS.
3464 //
3465 // Targets other than macOS are ill-supported by GCC (it doesn't even
3466 // support e.g. `-miphoneos-version-min`), so in those cases we can
3467 // fairly safely use `-target`. See also the following, where it is
3468 // made explicit that the recommendation by LLVM developers is to use
3469 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3470if *target_os == Os::MacOs {
3471// `-arch` communicates the architecture.
3472 //
3473 // CC forwards the `-arch` to the linker, so we use the same value
3474 // here intentionally.
3475cmd.cc_args(&["-arch", ld64_arch]);
34763477// The presence of `-mmacosx-version-min` makes CC default to
3478 // macOS, and it sets the deployment target.
3479let version = sess.apple_deployment_target().fmt_full();
3480// Intentionally pass this as a single argument, Clang doesn't
3481 // seem to like it otherwise.
3482cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
34833484// macOS has no environment, so with these two, we've told CC the
3485 // four desired parameters.
3486 //
3487 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3488} else {
3489cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3490 }
3491 }
3492}
34933494fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3495if !sess.target.is_like_darwin {
3496return None;
3497 }
3498let LinkerFlavor::Darwin(cc, _) = flavorelse {
3499return None;
3500 };
35013502// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3503 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3504 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3505 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3506 // instead we invoke `xcrun` manually.
3507 //
3508 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3509 // cause the trampoline binary to skip looking up the SDK itself).
3510let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
35113512if cc == Cc::Yes {
3513// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3514 // - The `--sysroot` flag.
3515 // - The `-isysroot` flag.
3516 // - The `SDKROOT` environment variable.
3517 //
3518 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3519 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3520 // only applies to include header files, but on Apple targets it also applies to libraries
3521 // and frameworks.
3522 //
3523 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3524 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3525 // primarily because that is the same interface that is used when invoking the tool under
3526 // `xcrun -sdk macosx $tool`.
3527 //
3528 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3529 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3530 //
3531 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3532 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3533 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3534 //
3535 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3536 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3537 // ignoring the value we set here, and instead use their built-in sysroot).
3538cmd.cmd().env("SDKROOT", &sdkroot);
3539 } else {
3540// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3541 // read by the linker, so it's really the only option.
3542 //
3543 // This is also what Clang does.
3544cmd.link_arg("-syslibroot");
3545cmd.link_arg(&sdkroot);
3546 }
35473548Some(sdkroot)
3549}
35503551fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3552if let Ok(sdkroot) = env::var("SDKROOT") {
3553let p = PathBuf::from(&sdkroot);
35543555// Ignore invalid SDKs, similar to what clang does:
3556 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3557 //
3558 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3559 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3560 // clearly set for the wrong platform.
3561 //
3562 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3563match &*apple::sdk_name(&sess.target).to_lowercase() {
3564"appletvos"
3565if sdkroot.contains("TVSimulator.platform")
3566 || sdkroot.contains("MacOSX.platform") => {}
3567"appletvsimulator"
3568if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3569"iphoneos"
3570if sdkroot.contains("iPhoneSimulator.platform")
3571 || sdkroot.contains("MacOSX.platform") => {}
3572"iphonesimulator"
3573if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3574 }
3575"macosx"
3576if sdkroot.contains("iPhoneOS.platform")
3577 || sdkroot.contains("iPhoneSimulator.platform")
3578 || sdkroot.contains("AppleTVOS.platform")
3579 || sdkroot.contains("AppleTVSimulator.platform")
3580 || sdkroot.contains("WatchOS.platform")
3581 || sdkroot.contains("WatchSimulator.platform")
3582 || sdkroot.contains("XROS.platform")
3583 || sdkroot.contains("XRSimulator.platform") => {}
3584"watchos"
3585if sdkroot.contains("WatchSimulator.platform")
3586 || sdkroot.contains("MacOSX.platform") => {}
3587"watchsimulator"
3588if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3589"xros"
3590if sdkroot.contains("XRSimulator.platform")
3591 || sdkroot.contains("MacOSX.platform") => {}
3592"xrsimulator"
3593if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3594// Ignore `SDKROOT` if it's not a valid path.
3595_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3596_ => return Some(p),
3597 }
3598 }
35993600 apple::get_sdk_root(sess)
3601}
36023603/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3604/// invoke it:
3605/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3606/// - or any `lld` available to `cc`.
3607fn add_lld_args(
3608 cmd: &mut dyn Linker,
3609 sess: &Session,
3610 flavor: LinkerFlavor,
3611 self_contained_components: LinkSelfContainedComponents,
3612) {
3613{
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:3613",
"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(3613u32),
::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!(
3614"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3615 flavor, self_contained_components,
3616 );
36173618// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3619 // we don't need to do anything.
3620if !(flavor.uses_cc() && flavor.uses_lld()) {
3621return;
3622 }
36233624// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3625 // directories to the tool's search path, depending on a mix between what users can specify on
3626 // the CLI, and what the target spec enables (as it can't disable components):
3627 // - if the self-contained linker is enabled on the CLI or by the target spec,
3628 // - and if the self-contained linker is not disabled on the CLI.
3629let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3630let self_contained_target = self_contained_components.is_linker_enabled();
36313632let self_contained_linker = self_contained_cli || self_contained_target;
3633if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3634let mut linker_path_exists = false;
3635for path in sess.get_tools_search_paths(false) {
3636let linker_path = path.join("gcc-ld");
3637 linker_path_exists |= linker_path.exists();
3638 cmd.cc_arg({
3639let mut arg = OsString::from("-B");
3640 arg.push(linker_path);
3641 arg
3642 });
3643 }
3644if !linker_path_exists {
3645// As a sanity check, we emit an error if none of these paths exist: we want
3646 // self-contained linking and have no linker.
3647sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3648 }
3649 }
36503651// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3652 // `lld` as the linker.
3653 //
3654 // Note that wasm targets skip this step since the only option there anyway
3655 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3656 // this, `wasm-component-ld`, which is overridden if this option is passed.
3657if !sess.target.is_like_wasm {
3658cmd.cc_arg("-fuse-ld=lld");
3659 }
36603661if !flavor.is_gnu() {
3662// Tell clang to use a non-default LLD flavor.
3663 // Gcc doesn't understand the target option, but we currently assume
3664 // that gcc is not used for Apple and Wasm targets (#97402).
3665 //
3666 // Note that we don't want to do that by default on macOS: e.g. passing a
3667 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3668 // shown in issue #101653 and the discussion in PR #101792.
3669 //
3670 // It could be required in some cases of cross-compiling with
3671 // LLD, but this is generally unspecified, and we don't know
3672 // which specific versions of clang, macOS SDK, host and target OS
3673 // combinations impact us here.
3674 //
3675 // So we do a simple first-approximation until we know more of what the
3676 // Apple targets require (and which would be handled prior to hitting this
3677 // LLD codepath anyway), but the expectation is that until then
3678 // this should be manually passed if needed. We specify the target when
3679 // targeting a different linker flavor on macOS, and that's also always
3680 // the case when targeting WASM.
3681if sess.target.linker_flavor != sess.host.linker_flavor {
3682cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3683 }
3684 }
3685}
36863687// gold has been deprecated with binutils 2.44
3688// and is known to behave incorrectly around Rust programs.
3689// There have been reports of being unable to bootstrap with gold:
3690// https://github.com/rust-lang/rust/issues/139425
3691// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3692// emitted with `#[used(linker)]`.
3693fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3694use object::read::elf::{FileHeader, SectionHeader};
3695use object::read::{ReadCache, ReadRef, Result};
3696use object::{Endianness, elf};
36973698fn elf_has_gold_version_note<'a>(
3699 elf: &impl FileHeader,
3700 data: impl ReadRef<'a>,
3701 ) -> Result<bool> {
3702let endian = elf.endian()?;
37033704let section =
3705 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3706if let Some((_, section)) = section3707 && let Some(mut notes) = section.notes(endian, data)?
3708{
3709return Ok(notes.any(|note| {
3710note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3711 }));
3712 }
37133714Ok(false)
3715 }
37163717let data = ReadCache::new(BufReader::new(File::open(path)?));
37183719let was_linked_with_gold = if sess.target.pointer_width == 64 {
3720let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3721 elf_has_gold_version_note(elf, &data)?
3722} else if sess.target.pointer_width == 32 {
3723let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3724 elf_has_gold_version_note(elf, &data)?
3725} else {
3726return Ok(());
3727 };
37283729if was_linked_with_gold {
3730let mut warn =
3731sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3732warn.help("consider using LLD or ld from GNU binutils instead");
3733warn.emit();
3734 }
3735Ok(())
3736}