1mod raw_dylib;
23use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
1112use find_msvc_tools;
13use itertools::Itertools;
14use object::{Object, ObjectSection, ObjectSymbol};
15use regex::Regex;
16use rustc_arena::TypedArena;
17use rustc_attr_parsing::eval_config_entry;
18use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::DiagCtxtHandle;
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_lint_defs::builtin::LINKER_INFO;
26use rustc_macros::Diagnostic;
27use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
28use rustc_metadata::{
29 EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
30 walk_native_lib_search_dirs,
31};
32use rustc_middle::bug;
33use rustc_middle::lint::emit_lint_base;
34use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
35use rustc_middle::middle::dependency_format::Linkage;
36use rustc_middle::middle::exported_symbols::SymbolExportKind;
37use rustc_session::config::{
38self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
39OutputType, PrintKind, SplitDwarfKind, Strip,
40};
41use rustc_session::lint::builtin::LINKER_MESSAGES;
42use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
43use rustc_session::search_paths::PathKind;
44/// For all the linkers we support, and information they might
45/// need out of the shared crate context before we get rid of it.
46use rustc_session::{Session, filesearch};
47use rustc_span::Symbol;
48use rustc_target::spec::crt_objects::CrtObjects;
49use rustc_target::spec::{
50BinaryFormat, Cc, CfgAbi, Env, LinkOutputKind, LinkSelfContainedComponents,
51LinkSelfContainedDefault, LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, Os, RelocModel,
52RelroLevel, SanitizerSet, SplitDebuginfo,
53};
54use tracing::{debug, info, warn};
5556use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
57use super::command::Command;
58use super::linker::{self, Linker};
59use super::metadata::{MetadataPosition, create_wrapper_file};
60use super::rpath::{self, RPathConfig};
61use super::{apple, rmeta_link, versioned_llvm_target};
62use crate::base::needs_allocator_shim_for_linking;
63use crate::{CodegenLintLevelSpecs, CompiledModule, CompiledModules, CrateInfo, NativeLib, errors};
6465pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
66if let Err(e) = fs::remove_file(path) {
67if e.kind() != io::ErrorKind::NotFound {
68dcx.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));
69 }
70 }
71}
7273/// Performs the linkage portion of the compilation phase. This will generate all
74/// of the requested outputs for this compilation session.
75pub fn link_binary(
76 sess: &Session,
77 archive_builder_builder: &dyn ArchiveBuilderBuilder,
78 compiled_modules: CompiledModules,
79 crate_info: CrateInfo,
80 metadata: EncodedMetadata,
81 outputs: &OutputFilenames,
82 codegen_backend: &'static str,
83) {
84let _timer = sess.timer("link_binary");
85let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
86let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
87for &crate_type in &crate_info.crate_types {
88// Ignore executable crates if we have -Z no-codegen, as they will error.
89if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
90 && !output_metadata
91 && crate_type == CrateType::Executable
92 {
93continue;
94 }
9596if invalid_output_for_target(sess, crate_type) {
97::rustc_middle::util::bug::bug_fmt(format_args!("invalid output type `{0:?}` for target `{1}`",
crate_type, sess.opts.target_triple));bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
98 }
99100 sess.time("link_binary_check_files_are_writeable", || {
101for m in &compiled_modules.modules {
102if let Some(obj) = &m.object {
103 check_file_is_writeable(obj, sess);
104 }
105if let Some(obj) = &m.global_asm_object {
106 check_file_is_writeable(obj, sess);
107 }
108 }
109 });
110111if outputs.outputs.should_link() {
112let output = out_filename(sess, crate_type, outputs, crate_info.local_crate_name);
113let tmpdir = TempDirBuilder::new()
114 .prefix("rustc")
115 .tempdir_in(output.parent().unwrap_or_else(|| Path::new(".")))
116 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
117let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
118119let crate_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", crate_info.local_crate_name))
})format!("{}", crate_info.local_crate_name);
120let out_filename = output.file_for_writing(outputs, OutputType::Exe, &crate_name);
121match crate_type {
122 CrateType::Rlib => {
123let _timer = sess.timer("link_rlib");
124{
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:124",
"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(124u32),
::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);
125 link_rlib(
126 sess,
127 archive_builder_builder,
128&compiled_modules,
129&crate_info,
130&metadata,
131 RlibFlavor::Normal,
132&path,
133 )
134 .build(&out_filename);
135 }
136 CrateType::StaticLib => {
137 link_staticlib(
138 sess,
139 archive_builder_builder,
140&compiled_modules,
141&crate_info,
142&metadata,
143&out_filename,
144&path,
145 );
146 }
147_ => {
148 link_natively(
149 sess,
150 archive_builder_builder,
151 crate_type,
152&out_filename,
153&compiled_modules,
154&crate_info,
155&metadata,
156 path.as_ref(),
157 codegen_backend,
158 );
159 }
160 }
161if sess.opts.json_artifact_notifications {
162 sess.dcx().emit_artifact_notification(&out_filename, "link");
163 }
164165if sess.prof.enabled()
166 && let Some(artifact_name) = out_filename.file_name()
167 {
168// Record size for self-profiling
169let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
170171 sess.prof.artifact_size(
172"linked_artifact",
173 artifact_name.to_string_lossy(),
174 file_size,
175 );
176 }
177178if sess.target.binary_format == BinaryFormat::Elf {
179if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
180{
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:180",
"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(180u32),
::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");
181 }
182 }
183184if output.is_stdout() {
185if output.is_tty() {
186 sess.dcx().emit_err(errors::BinaryOutputToTty {
187 shorthand: OutputType::Exe.shorthand(),
188 });
189 } else if let Err(e) = copy_to_stdout(&out_filename) {
190 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
191 }
192 tempfiles_for_stdout_output.push(out_filename);
193 }
194 }
195 }
196197// Remove the temporary object file and metadata if we aren't saving temps.
198sess.time("link_binary_remove_temps", || {
199// If the user requests that temporaries are saved, don't delete any.
200if sess.opts.cg.save_temps {
201return;
202 }
203204let maybe_remove_temps_from_module =
205 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
206if !preserve_objects && let Some(ref obj) = module.object {
207ensure_removed(sess.dcx(), obj);
208 }
209210if !preserve_objects && let Some(ref obj) = module.global_asm_object {
211ensure_removed(sess.dcx(), obj);
212 }
213214if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
215ensure_removed(sess.dcx(), dwo_obj);
216 }
217 };
218219let remove_temps_from_module =
220 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
221222// Otherwise, always remove the allocator module temporaries.
223if let Some(ref allocator_module) = compiled_modules.allocator_module {
224remove_temps_from_module(allocator_module);
225 }
226227// Remove the temporary files if output goes to stdout
228for temp in tempfiles_for_stdout_output {
229 ensure_removed(sess.dcx(), &temp);
230 }
231232// If no requested outputs require linking, then the object temporaries should
233 // be kept.
234if !sess.opts.output_types.should_link() {
235return;
236 }
237238// Potentially keep objects for their debuginfo.
239let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
240{
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:240",
"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(240u32),
::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);
241242for module in &compiled_modules.modules {
243 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
244 }
245 });
246}
247248// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
249// crate types must use the same dependency formats.
250pub fn each_linked_rlib(
251 info: &CrateInfo,
252 crate_type: Option<CrateType>,
253 f: &mut dyn FnMut(CrateNum, &Path),
254) -> Result<(), errors::LinkRlibError> {
255let fmts = if let Some(crate_type) = crate_type {
256let Some(fmts) = info.dependency_formats.get(&crate_type) else {
257return Err(errors::LinkRlibError::MissingFormat);
258 };
259260fmts261 } else {
262let mut dep_formats = info.dependency_formats.iter();
263let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
264if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
265return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
266 ty1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty1))
})format!("{ty1:?}"),
267 ty2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty2))
})format!("{ty2:?}"),
268 list1: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list1))
})format!("{list1:?}"),
269 list2: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", list2))
})format!("{list2:?}"),
270 });
271 }
272list1273 };
274275let used_dep_crates = info.used_crates.iter();
276for &cnum in used_dep_crates {
277match fmts.get(cnum) {
278Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
279Some(_) => {}
280None => return Err(errors::LinkRlibError::MissingFormat),
281 }
282let crate_name = info.crate_name[&cnum];
283let used_crate_source = &info.used_crate_source[&cnum];
284if let Some(path) = &used_crate_source.rlib {
285 f(cnum, path);
286 } else if used_crate_source.rmeta.is_some() {
287return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
288 } else {
289return Err(errors::LinkRlibError::NotFound { crate_name });
290 }
291 }
292Ok(())
293}
294295/// Create an 'rlib'.
296///
297/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
298/// The rlib primarily contains the object file of the crate, but it also some of the object files
299/// from native libraries.
300fn link_rlib<'a>(
301 sess: &'a Session,
302 archive_builder_builder: &dyn ArchiveBuilderBuilder,
303 compiled_modules: &CompiledModules,
304 crate_info: &CrateInfo,
305 metadata: &EncodedMetadata,
306 flavor: RlibFlavor,
307 tmpdir: &MaybeTempDir,
308) -> Box<dyn ArchiveBuilder + 'a> {
309let mut ab = archive_builder_builder.new_archive_builder(sess);
310311// Pre-compute the list of Rust object filenames and materialize the rmeta-link
312 // wrapper file before any `add_file` calls. This lets the rmeta-link member be
313 // placed immediately after metadata in the archive, so consumers can find
314 // it without iterating every archive member.
315let rust_object_files: Vec<String> = compiled_modules316 .modules
317 .iter()
318 .filter_map(|m| m.object.as_ref())
319 .chain(compiled_modules.modules.iter().filter_map(|m| m.global_asm_object.as_ref()))
320 .map(|obj| obj.file_name().unwrap().to_str().unwrap().to_string())
321 .collect();
322323let metadata_link_file = if #[allow(non_exhaustive_omitted_patterns)] match flavor {
RlibFlavor::Normal => true,
_ => false,
}matches!(flavor, RlibFlavor::Normal) {
324let metadata_link = rmeta_link::RmetaLink { rust_object_files };
325let metadata_link_data = metadata_link.encode();
326let (wrapper, _) =
327create_wrapper_file(sess, rmeta_link::SECTION.to_string(), &metadata_link_data);
328Some(emit_wrapper_file(sess, &wrapper, tmpdir.as_ref(), rmeta_link::FILENAME))
329 } else {
330None331 };
332333let trailing_metadata = match flavor {
334 RlibFlavor::Normal => {
335let (metadata, metadata_position) =
336create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
337let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
338match metadata_position {
339 MetadataPosition::First => {
340// Most of the time metadata in rlib files is wrapped in a "dummy" object
341 // file for the target platform so the rlib can be processed entirely by
342 // normal linkers for the platform. Sometimes this is not possible however.
343 // If it is possible however, placing the metadata object first improves
344 // performance of getting metadata from rlibs.
345ab.add_file(&metadata);
346// Place the rmeta-link member immediately after metadata so consumers
347 // can find it without iterating the whole archive.
348if let Some(file) = &metadata_link_file {
349ab.add_file(file);
350 }
351None352 }
353 MetadataPosition::Last => Some(metadata),
354 }
355 }
356357 RlibFlavor::StaticlibBase => None,
358 };
359360for m in &compiled_modules.modules {
361if let Some(obj) = m.object.as_ref() {
362 ab.add_file(obj);
363 }
364365if let Some(obj) = m.global_asm_object.as_ref() {
366 ab.add_file(obj);
367 }
368369if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
370 ab.add_file(dwarf_obj);
371 }
372 }
373374match flavor {
375 RlibFlavor::Normal => {}
376 RlibFlavor::StaticlibBase => {
377if let Some(m) = &compiled_modules.allocator_module {
378if let Some(obj) = &m.object {
379ab.add_file(obj);
380 }
381if let Some(obj) = &m.global_asm_object {
382ab.add_file(obj);
383 }
384 }
385 }
386 }
387388// Used if packed_bundled_libs flag enabled.
389let mut packed_bundled_libs = Vec::new();
390391// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
392 // we may not be configured to actually include a static library if we're
393 // adding it here. That's because later when we consume this rlib we'll
394 // decide whether we actually needed the static library or not.
395 //
396 // To do this "correctly" we'd need to keep track of which libraries added
397 // which object files to the archive. We don't do that here, however. The
398 // #[link(cfg(..))] feature is unstable, though, and only intended to get
399 // liblibc working. In that sense the check below just indicates that if
400 // there are any libraries we want to omit object files for at link time we
401 // just exclude all custom object files.
402 //
403 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
404 // feature then we'll need to figure out how to record what objects were
405 // loaded from the libraries found here and then encode that into the
406 // metadata of the rlib we're generating somehow.
407for lib in crate_info.used_libraries.iter() {
408let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
409continue;
410 };
411if flavor == RlibFlavor::Normal
412 && let Some(filename) = lib.filename
413 {
414let path = find_native_static_library(filename.as_str(), true, sess);
415let src = read(path)
416 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
417let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
418let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
419 packed_bundled_libs.push(wrapper_file);
420 } else {
421let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
422 ab.add_archive(&path, None).unwrap_or_else(|error| {
423 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
424 });
425 }
426 }
427428// On Windows, we add the raw-dylib import libraries to the rlibs already.
429 // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
430 // Instead, we add all raw-dylibs to the final link on ELF.
431if sess.target.is_like_windows {
432for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
433 sess,
434 archive_builder_builder,
435 crate_info.used_libraries.iter(),
436 tmpdir.as_ref(),
437true,
438 ) {
439 ab.add_archive(&output_path, None).unwrap_or_else(|error| {
440 sess.dcx()
441 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
442 });
443 }
444 }
445446if let Some(trailing_metadata) = trailing_metadata {
447// Note that it is important that we add all of our non-object "magical
448 // files" *after* all of the object files in the archive. The reason for
449 // this is as follows:
450 //
451 // * When performing LTO, this archive will be modified to remove
452 // objects from above. The reason for this is described below.
453 //
454 // * When the system linker looks at an archive, it will attempt to
455 // determine the architecture of the archive in order to see whether its
456 // linkable.
457 //
458 // The algorithm for this detection is: iterate over the files in the
459 // archive. Skip magical SYMDEF names. Interpret the first file as an
460 // object file. Read architecture from the object file.
461 //
462 // * As one can probably see, if "metadata" and "foo.bc" were placed
463 // before all of the objects, then the architecture of this archive would
464 // not be correctly inferred once 'foo.o' is removed.
465 //
466 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
467 // file for the target platform so the rlib can be processed entirely by
468 // normal linkers for the platform. Sometimes this is not possible however.
469 //
470 // Basically, all this means is that this code should not move above the
471 // code above.
472ab.add_file(&trailing_metadata);
473// Place the rmeta-link member immediately after metadata so consumers can
474 // find it without iterating the whole archive.
475if let Some(file) = &metadata_link_file {
476ab.add_file(file);
477 }
478 }
479480// Add all bundled static native library dependencies.
481 // Archives added to the end of .rlib archive, see comment above for the reason.
482for lib in packed_bundled_libs {
483 ab.add_file(&lib)
484 }
485486ab487}
488489/// Create a static archive.
490///
491/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
492/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
493/// dependencies as well.
494///
495/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
496/// library dependencies that they're not linked in.
497///
498/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
499/// object file (and also don't prepare the archive with a metadata file).
500fn link_staticlib(
501 sess: &Session,
502 archive_builder_builder: &dyn ArchiveBuilderBuilder,
503 compiled_modules: &CompiledModules,
504 crate_info: &CrateInfo,
505 metadata: &EncodedMetadata,
506 out_filename: &Path,
507 tempdir: &MaybeTempDir,
508) {
509{
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:509",
"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(509u32),
::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);
510let mut ab = link_rlib(
511sess,
512archive_builder_builder,
513compiled_modules,
514crate_info,
515metadata,
516 RlibFlavor::StaticlibBase,
517tempdir,
518 );
519let mut all_native_libs = ::alloc::vec::Vec::new()vec![];
520521let res = each_linked_rlib(crate_info, Some(CrateType::StaticLib), &mut |cnum, path| {
522let lto = are_upstream_rust_objects_already_included(sess)
523 && !ignored_for_lto(sess, crate_info, cnum);
524525let native_libs = crate_info.native_libraries[&cnum].iter();
526let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
527let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
528529let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
530ab.add_archive(
531path,
532Some(Box::new(move |fname: &str, metadata_link| {
533// Ignore metadata and rmeta-link files.
534if fname == METADATA_FILENAME || fname == rmeta_link::FILENAME {
535return true;
536 }
537538// Don't include Rust objects if LTO is enabled.
539if lto540 && metadata_link.is_some_and(|m| m.rust_object_files.iter().any(|f| f == fname))
541 {
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, None).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 }
570571ab.build(out_filename);
572573let crates = crate_info.used_crates.iter();
574575let fmts = crate_info576 .dependency_formats
577 .get(&CrateType::StaticLib)
578 .expect("no dependency formats for staticlib");
579580let mut all_rust_dylibs = ::alloc::vec::Vec::new()vec![];
581for &cnum in crates {
582let Some(Linkage::Dynamic) = fmts.get(cnum) else {
583continue;
584 };
585let crate_name = crate_info.crate_name[&cnum];
586let used_crate_source = &crate_info.used_crate_source[&cnum];
587if let Some(path) = &used_crate_source.dylib {
588 all_rust_dylibs.push(&**path);
589 } else if used_crate_source.rmeta.is_some() {
590 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
591 } else {
592 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
593 }
594 }
595596all_native_libs.extend_from_slice(&crate_info.used_libraries);
597598for print in &sess.opts.prints {
599if print.kind == PrintKind::NativeStaticLibs {
600 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
601 }
602 }
603}
604605/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
606/// DWARF package.
607fn link_dwarf_object(
608 sess: &Session,
609 compiled_modules: &CompiledModules,
610 crate_info: &CrateInfo,
611 executable_out_filename: &Path,
612) {
613let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
614dwp_out_filename.push(".dwp");
615{
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:615",
"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(615u32),
::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);
616617#[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)]
618struct ThorinSession<Relocations> {
619 arena_data: TypedArena<Vec<u8>>,
620 arena_mmap: TypedArena<Mmap>,
621 arena_relocations: TypedArena<Relocations>,
622 }
623624impl<Relocations> ThorinSession<Relocations> {
625fn alloc_mmap(&self, data: Mmap) -> &Mmap {
626&*self.arena_mmap.alloc(data)
627 }
628 }
629630impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
631fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
632&*self.arena_data.alloc(data)
633 }
634635fn alloc_relocation(&self, data: Relocations) -> &Relocations {
636&*self.arena_relocations.alloc(data)
637 }
638639fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
640let file = File::open(&path)?;
641let mmap = (unsafe { Mmap::map(file) })?;
642Ok(self.alloc_mmap(mmap))
643 }
644 }
645646match sess.time("run_thorin", || -> Result<(), thorin::Error> {
647let thorin_sess = ThorinSession::default();
648let mut package = thorin::DwarfPackage::new(&thorin_sess);
649650// Input objs contain .o/.dwo files from the current crate.
651match sess.opts.unstable_opts.split_dwarf_kind {
652 SplitDwarfKind::Single => {
653for m in &compiled_modules.modules {
654if let Some(input_obj) = &m.object {
655 package.add_input_object(input_obj)?;
656 }
657if let Some(input_obj) = &m.global_asm_object {
658 package.add_input_object(input_obj)?;
659 }
660 }
661 }
662 SplitDwarfKind::Split => {
663for input_obj in
664compiled_modules.modules.iter().filter_map(|m| m.dwarf_object.as_ref())
665 {
666 package.add_input_object(input_obj)?;
667 }
668 }
669 }
670671// Input rlibs contain .o/.dwo files from dependencies.
672let input_rlibs = crate_info673 .used_crate_source
674 .items()
675 .filter_map(|(_, csource)| csource.rlib.as_ref())
676 .into_sorted_stable_ord();
677678for input_rlib in input_rlibs {
679{
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:679",
"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(679u32),
::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);
680 package.add_input_object(input_rlib)?;
681 }
682683// Failing to read the referenced objects is expected for dependencies where the path in the
684 // executable will have been cleaned by Cargo, but the referenced objects will be contained
685 // within rlibs provided as inputs.
686 //
687 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
688 // found, but are provided explicitly above.
689 //
690 // Adding an executable is primarily done to make `thorin` check that all the referenced
691 // dwarf objects are found in the end.
692package.add_executable(
693 executable_out_filename,
694 thorin::MissingReferencedObjectBehaviour::Skip,
695 )?;
696697let output_stream = BufWriter::new(
698 OpenOptions::new()
699 .read(true)
700 .write(true)
701 .create(true)
702 .truncate(true)
703 .open(dwp_out_filename)?,
704 );
705let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
706 package.finish()?.emit(&mut output_stream)?;
707 output_stream.result()?;
708 output_stream.into_inner().flush()?;
709710Ok(())
711 }) {
712Ok(()) => {}
713Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
714 }
715}
716717#[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)]
718#[diag("{$inner}")]
719/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
720/// end up with inconsistent languages within the same diagnostic.
721struct LinkerOutput {
722 inner: String,
723}
724725fn is_msvc_link_exe(sess: &Session) -> bool {
726let (linker_path, flavor) = linker_and_flavor(sess);
727sess.target.is_like_msvc
728 && flavor == LinkerFlavor::Msvc(Lld::No)
729// Match exactly "link.exe"
730&& linker_path.to_str() == Some("link.exe")
731}
732733fn is_macos_ld(sess: &Session) -> bool {
734let (_, flavor) = linker_and_flavor(sess);
735sess.target.is_like_darwin && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Darwin(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Darwin(_, Lld::No))736}
737738fn is_windows_gnu_ld(sess: &Session) -> bool {
739let (_, flavor) = linker_and_flavor(sess);
740sess.target.is_like_windows
741 && !sess.target.is_like_msvc
742 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(_, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(_, Lld::No))743 && sess.target.options.cfg_abi != CfgAbi::Llvm744}
745746fn is_windows_gnu_clang(sess: &Session) -> bool {
747let (_, flavor) = linker_and_flavor(sess);
748sess.target.is_like_windows
749 && !sess.target.is_like_msvc
750 && #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::No) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::No))751 && sess.target.options.cfg_abi == CfgAbi::Llvm752}
753754fn report_linker_output(
755 sess: &Session,
756 levels: CodegenLintLevelSpecs,
757 stdout: &[u8],
758 stderr: &[u8],
759) {
760let mut escaped_stderr = escape_string(&stderr);
761let mut escaped_stdout = escape_string(&stdout);
762let mut linker_info = String::new();
763764{
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:764",
"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(764u32),
::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);
765{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:765",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(765u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("linker stdout:\n{0}",
&escaped_stdout) as &dyn Value))])
});
} else { ; }
};info!("linker stdout:\n{}", &escaped_stdout);
766767fn for_each(bytes: &[u8], mut f: impl FnMut(&str, &mut String)) -> String {
768let mut output = String::new();
769if let Ok(str) = str::from_utf8(bytes) {
770{
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:770",
"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(770u32),
::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}");
771output = String::with_capacity(str.len());
772for line in str.lines() {
773 f(line.trim(), &mut output);
774 }
775 }
776escape_string(output.trim().as_bytes())
777 }
778779if is_msvc_link_exe(sess) {
780{
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:780",
"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(780u32),
::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");
781782escaped_stdout = for_each(&stdout, |line, output| {
783// Hide some progress messages from link.exe that we don't care about.
784 // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
785 // When incremental linking is enabled and an .ilk exists, but its associated .exe is
786 // missing, link.exe prints the path of the missing .exe followed by:
787let ilk_but_no_exe =
788"not found or not built by the last incremental link; performing full link";
789let trimmed = line.trim_start();
790if trimmed.starts_with("Creating library")
791 || trimmed.starts_with("Generating code")
792 || trimmed.starts_with("Finished generating code")
793 || trimmed.ends_with(ilk_but_no_exe)
794 {
795linker_info += line;
796linker_info += "\r\n";
797 } else {
798*output += line;
799*output += "\r\n"
800}
801 });
802 } else if is_macos_ld(sess) {
803{
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:803",
"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(803u32),
::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");
804805// FIXME: Tracked by https://github.com/rust-lang/rust/issues/136113
806let deployment_mismatch = |line: &str| {
807// ld64 (object files + dylibs) and ld_prime (object files only):
808(line.starts_with("ld: ")
809 && line.contains("was built for newer")
810 && line.contains("than being linked"))
811// ld_prime (Xcode 15+, dylibs only):
812|| (line.starts_with("ld: ")
813 && line.contains("building for")
814 && line.contains("but linking with")
815 && line.contains("which was built for newer version"))
816 };
817// FIXME: This is a real warning we would like to show, but it hits too many crates
818 // to want to turn it on immediately.
819let search_path = |line: &str| {
820line.starts_with("ld: warning: search path '") && line.ends_with("' not found")
821 };
822escaped_stderr = for_each(&stderr, |line, output| {
823// This duplicate library warning is just not helpful at all.
824if line.starts_with("ld: warning: ignoring duplicate libraries: ")
825 || deployment_mismatch(line)
826 || search_path(line)
827 {
828linker_info += line;
829linker_info += "\n";
830 } else {
831*output += line;
832*output += "\n"
833}
834 });
835 } else if is_windows_gnu_ld(sess) {
836{
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:836",
"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(836u32),
::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");
837838let mut saw_exclude_symbol = false;
839// See https://github.com/rust-lang/rust/issues/112368.
840 // FIXME: maybe check that binutils is older than 2.40 before downgrading this warning?
841let exclude_symbols = |line: &str| {
842line.starts_with("Warning: .drectve `-exclude-symbols:")
843 && line.ends_with("' unrecognized")
844 };
845escaped_stderr = for_each(&stderr, |line, output| {
846if exclude_symbols(line) {
847saw_exclude_symbol = true;
848linker_info += line;
849linker_info += "\n";
850 } else if saw_exclude_symbol && line == "Warning: corrupt .drectve at end of def file" {
851linker_info += line;
852linker_info += "\n";
853 } else {
854*output += line;
855*output += "\n"
856}
857 });
858 } else if is_windows_gnu_clang(sess) {
859{
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:859",
"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(859u32),
::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)");
860escaped_stderr = for_each(&stderr, |line, output| {
861if line.contains("argument unused during compilation: '-nolibc'") {
862linker_info += line;
863linker_info += "\n";
864 } else {
865*output += line;
866*output += "\n"
867}
868 });
869 };
870871let lint_msg = |msg| {
872emit_lint_base(
873sess,
874LINKER_MESSAGES,
875levels.linker_messages,
876None,
877LinkerOutput { inner: msg },
878 );
879 };
880let lint_info = |msg| {
881emit_lint_base(sess, LINKER_INFO, levels.linker_info, None, LinkerOutput { inner: msg });
882 };
883884if !escaped_stderr.is_empty() {
885// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
886escaped_stderr =
887escaped_stderr.strip_prefix("warning: ").unwrap_or(&escaped_stderr).to_owned();
888// Windows GNU LD prints uppercase Warning
889escaped_stderr = escaped_stderr890 .strip_prefix("Warning: ")
891 .unwrap_or(&escaped_stderr)
892 .replace(": warning: ", ": ");
893lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stderr: {0}",
escaped_stderr.trim_end()))
})format!("linker stderr: {}", escaped_stderr.trim_end()));
894 }
895if !escaped_stdout.is_empty() {
896lint_msg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("linker stdout: {0}",
escaped_stdout.trim_end()))
})format!("linker stdout: {}", escaped_stdout.trim_end()))
897 }
898if !linker_info.is_empty() {
899lint_info(linker_info);
900 }
901}
902903/// Create a dynamic library or executable.
904///
905/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
906/// files as well.
907fn link_natively(
908 sess: &Session,
909 archive_builder_builder: &dyn ArchiveBuilderBuilder,
910 crate_type: CrateType,
911 out_filename: &Path,
912 compiled_modules: &CompiledModules,
913 crate_info: &CrateInfo,
914 metadata: &EncodedMetadata,
915 tmpdir: &Path,
916 codegen_backend: &'static str,
917) {
918{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/link.rs:918",
"rustc_codegen_ssa::back::link", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/link.rs"),
::tracing_core::__macro_support::Option::Some(918u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::link"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("preparing {0:?} to {1:?}",
crate_type, out_filename) as &dyn Value))])
});
} else { ; }
};info!("preparing {:?} to {:?}", crate_type, out_filename);
919let (linker_path, flavor) = linker_and_flavor(sess);
920let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
921922// On AIX, we ship all libraries as .a big_af archive
923 // the expected format is lib<name>.a(libname.so) for the actual
924 // dynamic library. So we link to a temporary .so file to be archived
925 // at the final out_filename location
926let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
927let archive_member =
928should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
929let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
930931let mut cmd = linker_with_args(
932&linker_path,
933flavor,
934sess,
935archive_builder_builder,
936crate_type,
937tmpdir,
938temp_filename,
939compiled_modules,
940crate_info,
941metadata,
942self_contained_components,
943codegen_backend,
944 );
945946 linker::disable_localization(&mut cmd);
947948for (k, v) in sess.target.link_env.as_ref() {
949 cmd.env(k.as_ref(), v.as_ref());
950 }
951for k in sess.target.link_env_remove.as_ref() {
952 cmd.env_remove(k.as_ref());
953 }
954955for print in &sess.opts.prints {
956if print.kind == PrintKind::LinkArgs {
957let content = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}\n", cmd))
})format!("{cmd:?}\n");
958 print.out.overwrite(&content, sess);
959 }
960 }
961962// May have not found libraries in the right formats.
963sess.dcx().abort_if_errors();
964965// Invoke the system linker
966{
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:966",
"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(966u32),
::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:?}");
967let unknown_arg_regex =
968Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
969let mut prog;
970loop {
971prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
972let Ok(ref output) = progelse {
973break;
974 };
975if output.status.success() {
976break;
977 }
978let mut out = output.stderr.clone();
979out.extend(&output.stdout);
980let out = String::from_utf8_lossy(&out);
981982// Check to see if the link failed with an error message that indicates it
983 // doesn't recognize the -no-pie option. If so, re-perform the link step
984 // without it. This is safe because if the linker doesn't support -no-pie
985 // then it should not default to linking executables as pie. Different
986 // versions of gcc seem to use different quotes in the error message so
987 // don't check for them.
988if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))989 && unknown_arg_regex.is_match(&out)
990 && out.contains("-no-pie")
991 && cmd.get_args().iter().any(|e| e == "-no-pie")
992 {
993{
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:993",
"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(993u32),
::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);
994{
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:994",
"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(994u32),
::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.");
995for arg in cmd.take_args() {
996if arg != "-no-pie" {
997 cmd.arg(arg);
998 }
999 }
1000{
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:1000",
"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(1000u32),
::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:?}");
1001continue;
1002 }
10031004// Check if linking failed with an error message that indicates the driver didn't recognize
1005 // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
1006 // to spawn multiple instances on the happy path to do version checking, and ensures things
1007 // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
1008 // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
1009if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, Lld::Yes) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))1010 && unknown_arg_regex.is_match(&out)
1011 && out.contains("-fuse-ld=lld")
1012 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
1013 {
1014{
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:1014",
"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(1014u32),
::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);
1015{
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:1015",
"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(1015u32),
::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.");
1016for arg in cmd.take_args() {
1017if arg.to_string_lossy() != "-fuse-ld=lld" {
1018 cmd.arg(arg);
1019 }
1020 }
1021{
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:1021",
"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(1021u32),
::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:?}");
1022continue;
1023 }
10241025// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
1026 // Fallback from '-static-pie' to '-static' in that case.
1027if #[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))1028 && unknown_arg_regex.is_match(&out)
1029 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
1030 && cmd.get_args().iter().any(|e| e == "-static-pie")
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!("linker output: {0:?}",
out) as &dyn Value))])
});
} else { ; }
};info!("linker output: {:?}", out);
1033{
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:1033",
"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(1033u32),
::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!(
1034"Linker does not support -static-pie command line option. Retrying with -static instead."
1035);
1036// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
1037let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
1038let opts = &sess.target;
1039let pre_objects = if self_contained_crt_objects {
1040&opts.pre_link_objects_self_contained
1041 } else {
1042&opts.pre_link_objects
1043 };
1044let post_objects = if self_contained_crt_objects {
1045&opts.post_link_objects_self_contained
1046 } else {
1047&opts.post_link_objects
1048 };
1049let get_objects = |objects: &CrtObjects, kind| {
1050objects1051 .get(&kind)
1052 .iter()
1053 .copied()
1054 .flatten()
1055 .map(|obj| {
1056get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
1057 })
1058 .collect::<Vec<_>>()
1059 };
1060let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
1061let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
1062let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
1063let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
1064// Assume that we know insertion positions for the replacement arguments from replaced
1065 // arguments, which is true for all supported targets.
1066if !(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());
1067if !(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());
1068for arg in cmd.take_args() {
1069if arg == "-static-pie" {
1070// Replace the output kind.
1071cmd.arg("-static");
1072 } else if pre_objects_static_pie.contains(&arg) {
1073// Replace the pre-link objects (replace the first and remove the rest).
1074cmd.args(mem::take(&mut pre_objects_static));
1075 } else if post_objects_static_pie.contains(&arg) {
1076// Replace the post-link objects (replace the first and remove the rest).
1077cmd.args(mem::take(&mut post_objects_static));
1078 } else {
1079 cmd.arg(arg);
1080 }
1081 }
1082{
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:1082",
"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(1082u32),
::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:?}");
1083continue;
1084 }
10851086break;
1087 }
10881089match prog {
1090Ok(prog) => {
1091if !prog.status.success() {
1092let mut output = prog.stderr.clone();
1093output.extend_from_slice(&prog.stdout);
1094let escaped_output = escape_linker_output(&output, flavor);
1095let err = errors::LinkingFailed {
1096 linker_path: &linker_path,
1097 exit_status: prog.status,
1098 command: cmd,
1099escaped_output,
1100 verbose: sess.opts.verbose,
1101 sysroot_dir: sess.opts.sysroot.path().to_owned(),
1102 };
1103sess.dcx().emit_err(err);
1104// If MSVC's `link.exe` was expected but the return code
1105 // is not a Microsoft LNK error then suggest a way to fix or
1106 // install the Visual Studio build tools.
1107if let Some(code) = prog.status.code() {
1108// All Microsoft `link.exe` linking ror codes are
1109 // four digit numbers in the range 1000 to 9999 inclusive
1110if is_msvc_link_exe(sess) && (code < 1000 || code > 9999) {
1111let is_vs_installed = find_msvc_tools::find_vs_version().is_ok();
1112let has_linker =
1113 find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe")
1114 .is_some();
11151116sess.dcx().emit_note(errors::LinkExeUnexpectedError);
11171118// STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
1119 // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
1120const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
1121if code == STATUS_STACK_BUFFER_OVERRUN {
1122sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
1123 }
11241125if is_vs_installed && has_linker {
1126// the linker is broken
1127sess.dcx().emit_note(errors::RepairVSBuildTools);
1128sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1129 } else if is_vs_installed {
1130// the linker is not installed
1131sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1132 } else {
1133// visual studio is not installed
1134sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1135 }
1136 }
1137 }
11381139sess.dcx().abort_if_errors();
1140 }
11411142{
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:1142",
"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(1142u32),
::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:?}");
1143report_linker_output(sess, crate_info.lint_level_specs, &prog.stdout, &prog.stderr);
1144 }
1145Err(e) => {
1146let linker_not_found = e.kind() == io::ErrorKind::NotFound;
11471148let err = if linker_not_found {
1149sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
1150 } else {
1151sess.dcx().emit_err(errors::UnableToExeLinker {
1152linker_path,
1153 error: e,
1154 command_formatted: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", cmd))
})format!("{cmd:?}"),
1155 })
1156 };
11571158if sess.target.is_like_msvc && linker_not_found {
1159sess.dcx().emit_note(errors::MsvcMissingLinker);
1160sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1161sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1162 }
1163err.raise_fatal();
1164 }
1165 }
11661167match sess.split_debuginfo() {
1168// If split debug information is disabled or located in individual files
1169 // there's nothing to do here.
1170SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
11711172// If packed split-debuginfo is requested, but the final compilation
1173 // doesn't actually have any debug information, then we skip this step.
1174SplitDebuginfo::Packedif sess.opts.debuginfo == DebugInfo::None => {}
11751176// On macOS the external `dsymutil` tool is used to create the packed
1177 // debug information. Note that this will read debug information from
1178 // the objects on the filesystem which we'll clean up later.
1179SplitDebuginfo::Packedif sess.target.is_like_darwin => {
1180let prog = Command::new("dsymutil").arg(out_filename).output();
1181match prog {
1182Ok(prog) => {
1183if !prog.status.success() {
1184let mut output = prog.stderr.clone();
1185output.extend_from_slice(&prog.stdout);
1186sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1187 status: prog.status,
1188 output: escape_string(&output),
1189 });
1190 }
1191 }
1192Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1193 }
1194 }
11951196// On MSVC packed debug information is produced by the linker itself so
1197 // there's no need to do anything else here.
1198SplitDebuginfo::Packedif sess.target.is_like_windows => {}
11991200// ... and otherwise we're processing a `*.dwp` packed dwarf file.
1201 //
1202 // We cannot rely on the .o paths in the executable because they may have been
1203 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1204 // the .o/.dwo paths explicitly.
1205SplitDebuginfo::Packed => {
1206link_dwarf_object(sess, compiled_modules, crate_info, out_filename)
1207 }
1208 }
12091210let strip = sess.opts.cg.strip;
12111212if sess.target.is_like_darwin {
1213let stripcmd = "rust-objcopy";
1214match (strip, crate_type) {
1215 (Strip::Debuginfo, _) => {
1216strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1217 }
12181219// Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1220(
1221 Strip::Symbols,
1222 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1223 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1224 (Strip::Symbols, _) => {
1225strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1226 }
1227 (Strip::None, _) => {}
1228 }
1229 }
12301231if sess.target.is_like_solaris {
1232// Many illumos systems will have both the native 'strip' utility and
1233 // the GNU one. Use the native version explicitly and do not rely on
1234 // what's in the path.
1235 //
1236 // If cross-compiling and there is not a native version, then use
1237 // `llvm-strip` and hope.
1238let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1239match strip {
1240// Always preserve the symbol table (-x).
1241Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1242// Strip::Symbols is handled via the --strip-all linker option.
1243Strip::Symbols => {}
1244 Strip::None => {}
1245 }
1246 }
12471248if sess.target.is_like_aix {
1249// `llvm-strip` doesn't work for AIX - their strip must be used.
1250if !sess.host.is_like_aix {
1251sess.dcx().emit_warn(errors::AixStripNotUsed);
1252 }
1253let stripcmd = "/usr/bin/strip";
1254match strip {
1255 Strip::Debuginfo => {
1256// FIXME: AIX's strip utility only offers option to strip line number information.
1257strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1258 }
1259 Strip::Symbols => {
1260// Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1261strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1262 }
1263 Strip::None => {}
1264 }
1265 }
12661267if should_archive {
1268let mut ab = archive_builder_builder.new_archive_builder(sess);
1269ab.add_file(temp_filename);
1270ab.build(out_filename);
1271 }
1272}
12731274fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1275let mut cmd = Command::new(util);
1276cmd.args(options);
12771278let mut new_path = sess.get_tools_search_paths(false);
1279if let Some(path) = env::var_os("PATH") {
1280new_path.extend(env::split_paths(&path));
1281 }
1282cmd.env("PATH", env::join_paths(new_path).unwrap());
12831284let prog = cmd.arg(out_filename).output();
1285match prog {
1286Ok(prog) => {
1287if !prog.status.success() {
1288let mut output = prog.stderr.clone();
1289output.extend_from_slice(&prog.stdout);
1290sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1291util,
1292 status: prog.status,
1293 output: escape_string(&output),
1294 });
1295 }
1296 }
1297Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1298 }
1299}
13001301fn escape_string(s: &[u8]) -> String {
1302match str::from_utf8(s) {
1303Ok(s) => s.to_owned(),
1304Err(_) => ::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()),
1305 }
1306}
13071308#[cfg(not(windows))]
1309fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1310escape_string(s)
1311}
13121313/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1314/// then try to convert the string from the OEM encoding.
1315#[cfg(windows)]
1316fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1317// This only applies to the actual MSVC linker.
1318if flavour != LinkerFlavor::Msvc(Lld::No) {
1319return escape_string(s);
1320 }
1321match str::from_utf8(s) {
1322Ok(s) => return s.to_owned(),
1323Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1324Some(s) => s,
1325// The string is not UTF-8 and isn't valid for the OEM code page
1326None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1327 },
1328 }
1329}
13301331/// Wrappers around the Windows API.
1332#[cfg(windows)]
1333mod win {
1334use windows::Win32::Globalization::{
1335 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1336 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1337 };
13381339/// Get the Windows system OEM code page. This is most notably the code page
1340 /// used for link.exe's output.
1341pub(super) fn oem_code_page() -> u32 {
1342unsafe {
1343let mut cp: u32 = 0;
1344// We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1345 // But the API requires us to pass the data as though it's a [u16] string.
1346let len = size_of::<u32>() / size_of::<u16>();
1347let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1348let len_written = GetLocaleInfoEx(
1349 LOCALE_NAME_SYSTEM_DEFAULT,
1350 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1351Some(data),
1352 );
1353if len_written as usize == len { cp } else { CP_OEMCP }
1354 }
1355 }
1356/// Try to convert a multi-byte string to a UTF-8 string using the given code page
1357 /// The string does not need to be null terminated.
1358 ///
1359 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1360 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1361 ///
1362 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1363 /// any invalid bytes for the expected encoding.
1364pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1365// `MultiByteToWideChar` requires a length to be a "positive integer".
1366if s.len() > isize::MAX as usize {
1367return None;
1368 }
1369// Error if the string is not valid for the expected code page.
1370let flags = MB_ERR_INVALID_CHARS;
1371// Call MultiByteToWideChar twice.
1372 // First to calculate the length then to convert the string.
1373let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1374if len > 0 {
1375let mut utf16 = vec![0; len as usize];
1376 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1377if len > 0 {
1378return utf16.get(..len as usize).map(String::from_utf16_lossy);
1379 }
1380 }
1381None
1382}
1383}
13841385fn add_sanitizer_libraries(
1386 sess: &Session,
1387 flavor: LinkerFlavor,
1388 crate_type: CrateType,
1389 linker: &mut dyn Linker,
1390) {
1391if sess.target.is_like_android {
1392// Sanitizer runtime libraries are provided dynamically on Android
1393 // targets.
1394return;
1395 }
13961397if sess.opts.unstable_opts.external_clangrt {
1398// Linking against in-tree sanitizer runtimes is disabled via
1399 // `-Z external-clangrt`
1400return;
1401 }
14021403if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib) {
1404return;
1405 }
14061407// On macOS and Windows using MSVC the runtimes are distributed as dylibs
1408 // which should be linked to both executables and dynamic libraries.
1409 // Everywhere else the runtimes are currently distributed as static
1410 // libraries which should be linked to executables only.
1411if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro |
CrateType::Sdylib => true,
_ => false,
}matches!(
1412 crate_type,
1413 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1414 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1415 {
1416return;
1417 }
14181419let sanitizer = sess.sanitizers();
1420if sanitizer.contains(SanitizerSet::ADDRESS) {
1421link_sanitizer_runtime(sess, flavor, linker, "asan");
1422 }
1423if sanitizer.contains(SanitizerSet::DATAFLOW) {
1424link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1425 }
1426if sanitizer.contains(SanitizerSet::LEAK)
1427 && !sanitizer.contains(SanitizerSet::ADDRESS)
1428 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1429 {
1430link_sanitizer_runtime(sess, flavor, linker, "lsan");
1431 }
1432if sanitizer.contains(SanitizerSet::MEMORY) {
1433link_sanitizer_runtime(sess, flavor, linker, "msan");
1434 }
1435if sanitizer.contains(SanitizerSet::THREAD) {
1436link_sanitizer_runtime(sess, flavor, linker, "tsan");
1437 }
1438if sanitizer.contains(SanitizerSet::HWADDRESS) {
1439link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1440 }
1441if sanitizer.contains(SanitizerSet::SAFESTACK) {
1442link_sanitizer_runtime(sess, flavor, linker, "safestack");
1443 }
1444if sanitizer.contains(SanitizerSet::REALTIME) {
1445link_sanitizer_runtime(sess, flavor, linker, "rtsan");
1446 }
1447}
14481449fn link_sanitizer_runtime(
1450 sess: &Session,
1451 flavor: LinkerFlavor,
1452 linker: &mut dyn Linker,
1453 name: &str,
1454) {
1455fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1456let path = sess.target_tlib_path.dir.join(filename);
1457if path.exists() {
1458sess.target_tlib_path.dir.clone()
1459 } else {
1460 filesearch::make_target_lib_path(
1461&sess.opts.sysroot.default,
1462sess.opts.target_triple.tuple(),
1463 )
1464 }
1465 }
14661467let channel =
1468::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();
14691470if sess.target.is_like_darwin {
1471// On Apple platforms, the sanitizer is always built as a dylib, and
1472 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1473 // rpath to the library as well (the rpath should be absolute, see
1474 // PR #41352 for details).
1475let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc{0}_rt.{1}", channel, name))
})format!("rustc{channel}_rt.{name}");
1476let path = find_sanitizer_runtime(sess, &filename);
1477let rpath = path.to_str().expect("non-utf8 component in path");
1478linker.link_args(&["-rpath", rpath]);
1479linker.link_dylib_by_name(&filename, false, true);
1480 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1481// MSVC provides the `/INFERASANLIBS` argument to automatically find the
1482 // compatible ASAN library.
1483linker.link_arg("/INFERASANLIBS");
1484 } else {
1485let filename = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("librustc{0}_rt.{1}.a", channel,
name))
})format!("librustc{channel}_rt.{name}.a");
1486let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1487linker.link_staticlib_by_path(&path, true);
1488 }
1489}
14901491/// Returns a boolean indicating whether the specified crate should be ignored
1492/// during LTO.
1493///
1494/// Crates ignored during LTO are not lumped together in the "massive object
1495/// file" that we create and are linked in their normal rlib states. See
1496/// comments below for what crates do not participate in LTO.
1497///
1498/// It's unusual for a crate to not participate in LTO. Typically only
1499/// compiler-specific and unstable crates have a reason to not participate in
1500/// LTO.
1501pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1502// If our target enables builtin function lowering in LLVM then the
1503 // crates providing these functions don't participate in LTO (e.g.
1504 // no_builtins or compiler builtins crates).
1505!sess.target.no_builtins
1506 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1507}
15081509/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1510pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1511fn infer_from(
1512 sess: &Session,
1513 linker: Option<PathBuf>,
1514 flavor: Option<LinkerFlavor>,
1515 features: LinkerFeaturesCli,
1516 ) -> Option<(PathBuf, LinkerFlavor)> {
1517let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1518match (linker, flavor) {
1519 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1520// only the linker flavor is known; use the default linker for the selected flavor
1521(None, Some(flavor)) => Some((
1522PathBuf::from(match flavor {
1523 LinkerFlavor::Gnu(Cc::Yes, _)
1524 | LinkerFlavor::Darwin(Cc::Yes, _)
1525 | LinkerFlavor::WasmLld(Cc::Yes)
1526 | LinkerFlavor::Unix(Cc::Yes) => {
1527if falsecfg!(any(target_os = "solaris", target_os = "illumos")) {
1528// On historical Solaris systems, "cc" may have
1529 // been Sun Studio, which is not flag-compatible
1530 // with "gcc". This history casts a long shadow,
1531 // and many modern illumos distributions today
1532 // ship GCC as "gcc" without also making it
1533 // available as "cc".
1534"gcc"
1535} else {
1536"cc"
1537}
1538 }
1539 LinkerFlavor::Gnu(_, Lld::Yes)
1540 | LinkerFlavor::Darwin(_, Lld::Yes)
1541 | LinkerFlavor::WasmLld(..)
1542 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1543 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1544"ld"
1545}
1546 LinkerFlavor::Msvc(..) => "link.exe",
1547 LinkerFlavor::EmCc => {
1548if falsecfg!(windows) {
1549"emcc.bat"
1550} else {
1551"emcc"
1552}
1553 }
1554 LinkerFlavor::Bpf => "bpf-linker",
1555 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1556 }),
1557flavor,
1558 )),
1559 (Some(linker), None) => {
1560let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1561sess.dcx().emit_fatal(errors::LinkerFileStem);
1562 });
1563let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1564let flavor = adjust_flavor_to_features(flavor, features);
1565Some((linker, flavor))
1566 }
1567 (None, None) => None,
1568 }
1569 }
15701571// While linker flavors and linker features are isomorphic (and thus targets don't need to
1572 // define features separately), we use the flavor as the root piece of data and have the
1573 // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1574 // both yet.
1575fn adjust_flavor_to_features(
1576 flavor: LinkerFlavor,
1577 features: LinkerFeaturesCli,
1578 ) -> LinkerFlavor {
1579// Note: a linker feature cannot be both enabled and disabled on the CLI.
1580if features.enabled.contains(LinkerFeatures::LLD) {
1581flavor.with_lld_enabled()
1582 } else if features.disabled.contains(LinkerFeatures::LLD) {
1583flavor.with_lld_disabled()
1584 } else {
1585flavor1586 }
1587 }
15881589let features = sess.opts.cg.linker_features;
15901591// linker and linker flavor specified via command line have precedence over what the target
1592 // specification specifies
1593let linker_flavor = match sess.opts.cg.linker_flavor {
1594// The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1595Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1596// The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1597linker_flavor => {
1598linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor))
1599 }
1600 };
1601if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1602return ret;
1603 }
16041605if let Some(ret) = infer_from(
1606sess,
1607sess.target.linker.as_deref().map(PathBuf::from),
1608Some(sess.target.linker_flavor),
1609features,
1610 ) {
1611return ret;
1612 }
16131614::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");
1615}
16161617/// Returns a pair of boolean indicating whether we should preserve the object and
1618/// dwarf object files on the filesystem for their debug information. This is often
1619/// useful with split-dwarf like schemes.
1620fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1621// If the objects don't have debuginfo there's nothing to preserve.
1622if sess.opts.debuginfo == config::DebugInfo::None {
1623return (false, false);
1624 }
16251626match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1627// If there is no split debuginfo then do not preserve objects.
1628(SplitDebuginfo::Off, _) => (false, false),
1629// If there is packed split debuginfo, then the debuginfo in the objects
1630 // has been packaged and the objects can be deleted.
1631(SplitDebuginfo::Packed, _) => (false, false),
1632// If there is unpacked split debuginfo and the current target can not use
1633 // split dwarf, then keep objects.
1634(SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1635// If there is unpacked split debuginfo and the target can use split dwarf, then
1636 // keep the object containing that debuginfo (whether that is an object file or
1637 // dwarf object file depends on the split dwarf kind).
1638(SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1639 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1640 }
1641}
16421643#[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)]
1644enum RlibFlavor {
1645 Normal,
1646 StaticlibBase,
1647}
16481649fn print_native_static_libs(
1650 sess: &Session,
1651 out: &OutFileName,
1652 all_native_libs: &[NativeLib],
1653 all_rust_dylibs: &[&Path],
1654) {
1655let mut lib_args: Vec<_> = all_native_libs1656 .iter()
1657 .filter(|l| relevant_lib(sess, l))
1658 .filter_map(|lib| {
1659let name = lib.name;
1660match lib.kind {
1661 NativeLibKind::Static { bundle: Some(false), .. }
1662 | NativeLibKind::Dylib { .. }
1663 | NativeLibKind::Unspecified => {
1664let verbatim = lib.verbatim;
1665if sess.target.is_like_msvc {
1666let (prefix, suffix) = sess.staticlib_components(verbatim);
1667Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, name, suffix))
})format!("{prefix}{name}{suffix}"))
1668 } else if sess.target.linker_flavor.is_gnu() {
1669Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}{1}",
if verbatim { ":" } else { "" }, name))
})format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1670 } else {
1671Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", name))
})format!("-l{name}"))
1672 }
1673 }
1674 NativeLibKind::Framework { .. } => {
1675// ld-only syntax, since there are no frameworks in MSVC
1676Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-framework {0}", name))
})format!("-framework {name}"))
1677 }
1678// These are included, no need to print them
1679NativeLibKind::Static { bundle: None | Some(true), .. }
1680 | NativeLibKind::LinkArg1681 | NativeLibKind::WasmImportModule1682 | NativeLibKind::RawDylib { .. } => None,
1683 }
1684 })
1685// deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1686.dedup()
1687 .collect();
1688for path in all_rust_dylibs {
1689// FIXME deduplicate with add_dynamic_crate
16901691 // Just need to tell the linker about where the library lives and
1692 // what its name is
1693let parent = path.parent();
1694if let Some(dir) = parent {
1695let dir = fix_windows_verbatim_for_gcc(dir);
1696if sess.target.is_like_msvc {
1697let mut arg = String::from("/LIBPATH:");
1698 arg.push_str(&dir.display().to_string());
1699 lib_args.push(arg);
1700 } else {
1701 lib_args.push("-L".to_owned());
1702 lib_args.push(dir.display().to_string());
1703 }
1704 }
1705let stem = path.file_stem().unwrap().to_str().unwrap();
1706// Convert library file-stem into a cc -l argument.
1707let lib = if let Some(lib) = stem.strip_prefix("lib")
1708 && !sess.target.is_like_windows
1709 {
1710 lib
1711 } else {
1712 stem
1713 };
1714let path = parent.unwrap_or_else(|| Path::new(""));
1715if sess.target.is_like_msvc {
1716// When producing a dll, the MSVC linker may not actually emit a
1717 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1718 // check to see if the file is there and just omit linking to it if it's
1719 // not present.
1720let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.dll.lib", lib))
})format!("{lib}.dll.lib");
1721if path.join(&name).exists() {
1722 lib_args.push(name);
1723 }
1724 } else {
1725 lib_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-l{0}", lib))
})format!("-l{lib}"));
1726 }
1727 }
17281729match out {
1730 OutFileName::Real(path) => {
1731out.overwrite(&lib_args.join(" "), sess);
1732sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1733 }
1734 OutFileName::Stdout => {
1735sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1736// Prefix for greppability
1737 // Note: This must not be translated as tools are allowed to depend on this exact string.
1738sess.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(" ")));
1739 }
1740 }
1741}
17421743fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1744let file_path = sess.target_tlib_path.dir.join(name);
1745if file_path.exists() {
1746return file_path;
1747 }
1748// Special directory with objects used only in self-contained linkage mode
1749if self_contained {
1750let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1751if file_path.exists() {
1752return file_path;
1753 }
1754 }
1755for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1756let file_path = search_path.dir.join(name);
1757if file_path.exists() {
1758return file_path;
1759 }
1760 }
1761PathBuf::from(name)
1762}
17631764fn exec_linker(
1765 sess: &Session,
1766 cmd: &Command,
1767 out_filename: &Path,
1768 flavor: LinkerFlavor,
1769 tmpdir: &Path,
1770) -> io::Result<Output> {
1771// When attempting to spawn the linker we run a risk of blowing out the
1772 // size limits for spawning a new process with respect to the arguments
1773 // we pass on the command line.
1774 //
1775 // Here we attempt to handle errors from the OS saying "your list of
1776 // arguments is too big" by reinvoking the linker again with an `@`-file
1777 // that contains all the arguments (aka 'response' files).
1778 // The theory is that this is then accepted on all linkers and the linker
1779 // will read all its options out of there instead of looking at the command line.
1780if !cmd.very_likely_to_exceed_some_spawn_limit() {
1781match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1782Ok(child) => {
1783let output = child.wait_with_output();
1784 flush_linked_file(&output, out_filename)?;
1785return output;
1786 }
1787Err(ref e) if command_line_too_big(e) => {
1788{
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:1788",
"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(1788u32),
::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);
1789 }
1790Err(e) => return Err(e),
1791 }
1792 }
17931794{
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:1794",
"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(1794u32),
::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");
1795let mut cmd2 = cmd.clone();
1796let mut args = String::new();
1797for arg in cmd2.take_args() {
1798 args.push_str(
1799&Escape {
1800 arg: arg.to_str().unwrap(),
1801// Windows-style escaping for @-files is used by
1802 // - all linkers targeting MSVC-like targets, including LLD
1803 // - all LLD flavors running on Windows hosts
1804 // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1805is_like_msvc: sess.target.is_like_msvc
1806 || (falsecfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1807 }
1808 .to_string(),
1809 );
1810 args.push('\n');
1811 }
1812let file = tmpdir.join("linker-arguments");
1813let bytes = if sess.target.is_like_msvc {
1814let mut out = Vec::with_capacity((1 + args.len()) * 2);
1815// start the stream with a UTF-16 BOM
1816for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1817// encode in little endian
1818out.push(c as u8);
1819 out.push((c >> 8) as u8);
1820 }
1821out1822 } else {
1823args.into_bytes()
1824 };
1825 fs::write(&file, &bytes)?;
1826cmd2.arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@{0}", file.display()))
})format!("@{}", file.display()));
1827{
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:1827",
"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(1827u32),
::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);
1828let output = cmd2.output();
1829 flush_linked_file(&output, out_filename)?;
1830return output;
18311832#[cfg(not(windows))]
1833fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1834Ok(())
1835 }
18361837#[cfg(windows)]
1838fn flush_linked_file(
1839 command_output: &io::Result<Output>,
1840 out_filename: &Path,
1841 ) -> io::Result<()> {
1842// On Windows, under high I/O load, output buffers are sometimes not flushed,
1843 // even long after process exit, causing nasty, non-reproducible output bugs.
1844 //
1845 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1846 //
1847 // А full writeup of the original Chrome bug can be found at
1848 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
18491850if let &Ok(ref out) = command_output {
1851if out.status.success() {
1852if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1853 of.sync_all()?;
1854 }
1855 }
1856 }
18571858Ok(())
1859 }
18601861#[cfg(unix)]
1862fn command_line_too_big(err: &io::Error) -> bool {
1863err.raw_os_error() == Some(::libc::E2BIG)
1864 }
18651866#[cfg(windows)]
1867fn command_line_too_big(err: &io::Error) -> bool {
1868const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1869 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1870 }
18711872#[cfg(not(any(unix, windows)))]
1873fn command_line_too_big(_: &io::Error) -> bool {
1874false
1875}
18761877struct Escape<'a> {
1878 arg: &'a str,
1879 is_like_msvc: bool,
1880 }
18811882impl<'a> fmt::Displayfor Escape<'a> {
1883fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1884if self.is_like_msvc {
1885// This is "documented" at
1886 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1887 //
1888 // Unfortunately there's not a great specification of the
1889 // syntax I could find online (at least) but some local
1890 // testing showed that this seemed sufficient-ish to catch
1891 // at least a few edge cases.
1892f.write_fmt(format_args!("\""))write!(f, "\"")?;
1893for c in self.arg.chars() {
1894match c {
1895'"' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1896 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1897 }
1898 }
1899f.write_fmt(format_args!("\""))write!(f, "\"")?;
1900 } else {
1901// This is documented at https://linux.die.net/man/1/ld, namely:
1902 //
1903 // > Options in file are separated by whitespace. A whitespace
1904 // > character may be included in an option by surrounding the
1905 // > entire option in either single or double quotes. Any
1906 // > character (including a backslash) may be included by
1907 // > prefixing the character to be included with a backslash.
1908 //
1909 // We put an argument on each line, so all we need to do is
1910 // ensure the line is interpreted as one whole argument.
1911for c in self.arg.chars() {
1912match c {
1913'\\' | ' ' => f.write_fmt(format_args!("\\{0}", c))write!(f, "\\{c}")?,
1914 c => f.write_fmt(format_args!("{0}", c))write!(f, "{c}")?,
1915 }
1916 }
1917 }
1918Ok(())
1919 }
1920 }
1921}
19221923fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1924let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1925 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1926 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1927 LinkOutputKind::DynamicPicExe1928 }
1929 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1930 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1931 LinkOutputKind::StaticPicExe1932 }
1933 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1934 (_, true, _) => LinkOutputKind::StaticDylib,
1935 (_, false, _) => LinkOutputKind::DynamicDylib,
1936 };
19371938// Adjust the output kind to target capabilities.
1939let opts = &sess.target;
1940let pic_exe_supported = opts.position_independent_executables;
1941let static_pic_exe_supported = opts.static_position_independent_executables;
1942let static_dylib_supported = opts.crt_static_allows_dylibs;
1943match kind {
1944 LinkOutputKind::DynamicPicExeif !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1945 LinkOutputKind::StaticPicExeif !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1946 LinkOutputKind::StaticDylibif !static_dylib_supported => LinkOutputKind::DynamicDylib,
1947_ => kind,
1948 }
1949}
19501951// Returns true if linker is located within sysroot
1952fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1953let linker_with_extension = if falsecfg!(windows) && linker.extension().is_none() {
1954linker.with_extension("exe")
1955 } else {
1956linker.to_path_buf()
1957 };
1958for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1959let full_path = dir.join(&linker_with_extension);
1960// If linker comes from sysroot assume self-contained mode
1961if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1962return false;
1963 }
1964 }
1965true
1966}
19671968/// Various toolchain components used during linking are used from rustc distribution
1969/// instead of being found somewhere on the host system.
1970/// We only provide such support for a very limited number of targets.
1971fn self_contained_components(
1972 sess: &Session,
1973 crate_type: CrateType,
1974 linker: &Path,
1975) -> LinkSelfContainedComponents {
1976// Turn the backwards compatible bool values for `self_contained` into fully inferred
1977 // `LinkSelfContainedComponents`.
1978let self_contained =
1979if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1980// Emit an error if the user requested self-contained mode on the CLI but the target
1981 // explicitly refuses it.
1982if sess.target.link_self_contained.is_disabled() {
1983sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1984 }
1985self_contained1986 } else {
1987match sess.target.link_self_contained {
1988 LinkSelfContainedDefault::False => false,
1989 LinkSelfContainedDefault::True => true,
19901991 LinkSelfContainedDefault::WithComponents(components) => {
1992// For target specs with explicitly enabled components, we can return them
1993 // directly.
1994return components;
1995 }
19961997// FIXME: Find a better heuristic for "native musl toolchain is available",
1998 // based on host and linker path, for example.
1999 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
2000LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
2001 LinkSelfContainedDefault::InferredForMingw => {
2002sess.host == sess.target
2003 && sess.target.cfg_abi != CfgAbi::Uwp2004 && detect_self_contained_mingw(sess, linker)
2005 }
2006 }
2007 };
2008if self_contained {
2009LinkSelfContainedComponents::all()
2010 } else {
2011LinkSelfContainedComponents::empty()
2012 }
2013}
20142015/// Add pre-link object files defined by the target spec.
2016fn add_pre_link_objects(
2017 cmd: &mut dyn Linker,
2018 sess: &Session,
2019 flavor: LinkerFlavor,
2020 link_output_kind: LinkOutputKind,
2021 self_contained: bool,
2022) {
2023// FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
2024 // so Fuchsia has to be special-cased.
2025let opts = &sess.target;
2026let empty = Default::default();
2027let objects = if self_contained {
2028&opts.pre_link_objects_self_contained
2029 } 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, _))) {
2030&opts.pre_link_objects
2031 } else {
2032&empty2033 };
2034for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2035 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2036 }
2037}
20382039/// Add post-link object files defined by the target spec.
2040fn add_post_link_objects(
2041 cmd: &mut dyn Linker,
2042 sess: &Session,
2043 link_output_kind: LinkOutputKind,
2044 self_contained: bool,
2045) {
2046let objects = if self_contained {
2047&sess.target.post_link_objects_self_contained
2048 } else {
2049&sess.target.post_link_objects
2050 };
2051for obj in objects.get(&link_output_kind).iter().copied().flatten() {
2052 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
2053 }
2054}
20552056/// Add arbitrary "pre-link" args defined by the target spec or from command line.
2057/// FIXME: Determine where exactly these args need to be inserted.
2058fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2059if let Some(args) = sess.target.pre_link_args.get(&flavor) {
2060cmd.verbatim_args(args.iter().map(Deref::deref));
2061 }
20622063cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
2064}
20652066/// Add a link script embedded in the target, if applicable.
2067fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
2068match (crate_type, &sess.target.link_script) {
2069 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
2070if !sess.target.linker_flavor.is_gnu() {
2071sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
2072 }
20732074let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
20752076let path = tmpdir.join(file_name);
2077if let Err(error) = fs::write(&path, script.as_ref()) {
2078sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
2079 }
20802081cmd.link_arg("--script").link_arg(path);
2082 }
2083_ => {}
2084 }
2085}
20862087/// Add arbitrary "user defined" args defined from command line.
2088/// FIXME: Determine where exactly these args need to be inserted.
2089fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
2090cmd.verbatim_args(&sess.opts.cg.link_args);
2091}
20922093/// Add arbitrary "late link" args defined by the target spec.
2094/// FIXME: Determine where exactly these args need to be inserted.
2095fn add_late_link_args(
2096 cmd: &mut dyn Linker,
2097 sess: &Session,
2098 flavor: LinkerFlavor,
2099 crate_type: CrateType,
2100 crate_info: &CrateInfo,
2101) {
2102let any_dynamic_crate = crate_type == CrateType::Dylib2103 || crate_type == CrateType::Sdylib2104 || crate_info.dependency_formats.iter().any(|(ty, list)| {
2105*ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
2106 });
2107if any_dynamic_crate {
2108if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
2109cmd.verbatim_args(args.iter().map(Deref::deref));
2110 }
2111 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
2112cmd.verbatim_args(args.iter().map(Deref::deref));
2113 }
2114if let Some(args) = sess.target.late_link_args.get(&flavor) {
2115cmd.verbatim_args(args.iter().map(Deref::deref));
2116 }
2117}
21182119/// Add arbitrary "post-link" args defined by the target spec.
2120/// FIXME: Determine where exactly these args need to be inserted.
2121fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2122if let Some(args) = sess.target.post_link_args.get(&flavor) {
2123cmd.verbatim_args(args.iter().map(Deref::deref));
2124 }
2125}
21262127/// Add a synthetic object file that contains reference to all symbols that we want to expose to
2128/// the linker.
2129///
2130/// Background: we implement rlibs as static library (archives). Linkers treat archives
2131/// differently from object files: all object files participate in linking, while archives will
2132/// only participate in linking if they can satisfy at least one undefined reference (version
2133/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
2134/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
2135/// can't keep them either. This causes #47384.
2136///
2137/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
2138/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
2139/// we instead just introduce an undefined reference to them. This could be done by `-u` command
2140/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
2141/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
2142/// from removing them, and this is especially problematic for embedded programming where every
2143/// byte counts.
2144///
2145/// This method creates a synthetic object file, which contains undefined references to all symbols
2146/// that are necessary for the linking. They are only present in symbol table but not actually
2147/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
2148/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
2149///
2150/// There's a few internal crates in the standard library (aka libcore and
2151/// libstd) which actually have a circular dependence upon one another. This
2152/// currently arises through "weak lang items" where libcore requires things
2153/// like `rust_begin_unwind` but libstd ends up defining it. To get this
2154/// circular dependence to work correctly we declare some of these things
2155/// in this synthetic object.
2156fn add_linked_symbol_object(
2157 cmd: &mut dyn Linker,
2158 sess: &Session,
2159 tmpdir: &Path,
2160 symbols: &[(String, SymbolExportKind)],
2161) {
2162if symbols.is_empty() {
2163return;
2164 }
21652166let Some(mut file) = super::metadata::create_object_file(sess) else {
2167return;
2168 };
21692170if file.format() == object::BinaryFormat::Coff {
2171// NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
2172 // so add an empty section.
2173file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
21742175// We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
2176 // default mangler in `object` crate.
2177file.set_mangling(object::write::Mangling::None);
2178 }
21792180if file.format() == object::BinaryFormat::MachO {
2181// Divide up the sections into sub-sections via symbols for dead code stripping.
2182 // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
2183 // discard on MachO targets.
2184file.set_subsections_via_symbols();
2185 }
21862187// ld64 requires a relocation to load undefined symbols, see below.
2188 // Not strictly needed if linking with lld, but might as well do it there too.
2189let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2190Some(file.add_section(
2191file.segment_name(object::write::StandardSegment::Data).to_vec(),
2192"__data".into(),
2193 object::SectionKind::Data,
2194 ))
2195 } else {
2196None2197 };
21982199for (sym, kind) in symbols.iter() {
2200let symbol = file.add_symbol(object::write::Symbol {
2201 name: sym.clone().into(),
2202 value: 0,
2203 size: 0,
2204 kind: match kind {
2205 SymbolExportKind::Text => object::SymbolKind::Text,
2206 SymbolExportKind::Data => object::SymbolKind::Data,
2207 SymbolExportKind::Tls => object::SymbolKind::Tls,
2208 },
2209 scope: object::SymbolScope::Unknown,
2210 weak: false,
2211 section: object::write::SymbolSection::Undefined,
2212 flags: object::SymbolFlags::None,
2213 });
22142215// The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2216 //
2217 // Code-wise, the relevant parts of ld64 are roughly:
2218 // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2219 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2220 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2221 //
2222 // 2. Read the archive table of contents (__.SYMDEF file).
2223 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2224 //
2225 // 3. Begin linking by loading "atoms" from input files.
2226 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2227 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2228 //
2229 // a. Directly specified object files (`.o`) are parsed immediately.
2230 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2231 //
2232 // - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2233 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2234 // https://maskray.me/blog/2022-02-06-all-about-common-symbols
2235 //
2236 // - Relocations/fixups are atoms.
2237 // https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2238 //
2239 // b. Archives are not parsed yet.
2240 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2241 //
2242 // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2243 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2244 // https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2245 //
2246 // All of the steps above are fairly similar to other linkers, except that **it completely
2247 // ignores undefined symbols**.
2248 //
2249 // So to make this trick work on ld64, we need to do something else to load the relevant
2250 // object files. We do this by inserting a relocation (fixup) for each symbol.
2251if let Some(section) = ld64_section_helper {
2252 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2253 .expect("failed adding relocation");
2254 }
2255 }
22562257let path = tmpdir.join("symbols.o");
2258let result = std::fs::write(&path, file.write().unwrap());
2259if let Err(error) = result {
2260sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2261 }
2262cmd.add_object(&path);
2263}
22642265/// Add object files containing code from the current crate.
2266fn add_local_crate_regular_objects(cmd: &mut dyn Linker, compiled_modules: &CompiledModules) {
2267for m in &compiled_modules.modules {
2268if let Some(obj) = &m.object {
2269 cmd.add_object(obj);
2270 }
2271if let Some(obj) = &m.global_asm_object {
2272 cmd.add_object(obj);
2273 }
2274 }
2275}
22762277/// Add object files for allocator code linked once for the whole crate tree.
2278fn add_local_crate_allocator_objects(
2279 cmd: &mut dyn Linker,
2280 compiled_modules: &CompiledModules,
2281 crate_info: &CrateInfo,
2282 crate_type: CrateType,
2283) {
2284if needs_allocator_shim_for_linking(&crate_info.dependency_formats, crate_type)
2285 && let Some(m) = &compiled_modules.allocator_module
2286 {
2287if let Some(obj) = &m.object {
2288cmd.add_object(obj);
2289 }
2290if let Some(obj) = &m.global_asm_object {
2291cmd.add_object(obj);
2292 }
2293 }
2294}
22952296/// Add object files containing metadata for the current crate.
2297fn add_local_crate_metadata_objects(
2298 cmd: &mut dyn Linker,
2299 sess: &Session,
2300 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2301 crate_type: CrateType,
2302 tmpdir: &Path,
2303 crate_info: &CrateInfo,
2304 metadata: &EncodedMetadata,
2305) {
2306// When linking a dynamic library, we put the metadata into a section of the
2307 // executable. This metadata is in a separate object file from the main
2308 // object file, so we create and link it in here.
2309if #[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Dylib | CrateType::ProcMacro => true,
_ => false,
}matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2310let data = archive_builder_builder.create_dylib_metadata_wrapper(
2311sess,
2312&metadata,
2313&crate_info.metadata_symbol,
2314 );
2315let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
23162317cmd.add_object(&obj);
2318 }
2319}
23202321/// Add sysroot and other globally set directories to the directory search list.
2322fn add_library_search_dirs(
2323 cmd: &mut dyn Linker,
2324 sess: &Session,
2325 self_contained_components: LinkSelfContainedComponents,
2326 apple_sdk_root: Option<&Path>,
2327) {
2328if !sess.opts.unstable_opts.link_native_libraries {
2329return;
2330 }
23312332let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2333let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2334if is_framework {
2335cmd.framework_path(dir);
2336 } else {
2337cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2338 }
2339 ControlFlow::<()>::Continue(())
2340 });
2341}
23422343/// Add options making relocation sections in the produced ELF files read-only
2344/// and suppressing lazy binding.
2345fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2346match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2347 RelroLevel::Full => cmd.full_relro(),
2348 RelroLevel::Partial => cmd.partial_relro(),
2349 RelroLevel::Off => cmd.no_relro(),
2350 RelroLevel::None => {}
2351 }
2352}
23532354/// Add library search paths used at runtime by dynamic linkers.
2355fn add_rpath_args(
2356 cmd: &mut dyn Linker,
2357 sess: &Session,
2358 crate_info: &CrateInfo,
2359 out_filename: &Path,
2360) {
2361if !sess.target.has_rpath {
2362return;
2363 }
23642365// FIXME (#2397): At some point we want to rpath our guesses as to
2366 // where extern libraries might live, based on the
2367 // add_lib_search_paths
2368if sess.opts.cg.rpath {
2369let libs = crate_info2370 .used_crates
2371 .iter()
2372 .filter_map(|cnum| crate_info.used_crate_source[cnum].dylib.as_deref())
2373 .collect::<Vec<_>>();
2374let rpath_config = RPathConfig {
2375 libs: &*libs,
2376 out_filename: out_filename.to_path_buf(),
2377 is_like_darwin: sess.target.is_like_darwin,
2378 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2379 };
2380cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2381 }
2382}
23832384fn add_c_staticlib_symbols(
2385 sess: &Session,
2386 lib: &NativeLib,
2387 out: &mut Vec<(String, SymbolExportKind)>,
2388) -> io::Result<()> {
2389let file_path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
23902391let archive_map = unsafe { Mmap::map(File::open(&file_path)?)? };
23922393let archive = object::read::archive::ArchiveFile::parse(&*archive_map)
2394 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23952396for member in archive.members() {
2397let member = member.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
23982399let data = member
2400 .data(&*archive_map)
2401 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24022403// clang LTO: raw LLVM bitcode
2404if data.starts_with(b"BC\xc0\xde") {
2405return Err(io::Error::new(
2406 io::ErrorKind::InvalidData,
2407"LLVM bitcode object in C static library (LTO not supported)",
2408 ));
2409 }
24102411let object = object::File::parse(&*data)
2412 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
24132414// gcc / clang ELF / Mach-O LTO
2415if object.sections().any(|s| {
2416 s.name().map(|n| n.starts_with(".gnu.lto_") || n == ".llvm.lto").unwrap_or(false)
2417 }) {
2418return Err(io::Error::new(
2419 io::ErrorKind::InvalidData,
2420"LTO object in C static library is not supported",
2421 ));
2422 }
24232424for symbol in object.symbols() {
2425if symbol.scope() != object::SymbolScope::Dynamic {
2426continue;
2427 }
24282429let name = match symbol.name() {
2430Ok(n) => n,
2431Err(_) => continue,
2432 };
24332434let export_kind = match symbol.kind() {
2435 object::SymbolKind::Text => SymbolExportKind::Text,
2436 object::SymbolKind::Data => SymbolExportKind::Data,
2437_ => continue,
2438 };
24392440// FIXME:The symbol mangle rules are slightly different in Windows(32-bit) and Apple.
2441 // Need to be resolved.
2442out.push((name.to_string(), export_kind));
2443 }
2444 }
24452446Ok(())
2447}
24482449/// Produce the linker command line containing linker path and arguments.
2450///
2451/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2452/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2453/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2454/// to the linking process as a whole.
2455/// Order-independent options may still override each other in order-dependent fashion,
2456/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2457fn linker_with_args(
2458 path: &Path,
2459 flavor: LinkerFlavor,
2460 sess: &Session,
2461 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2462 crate_type: CrateType,
2463 tmpdir: &Path,
2464 out_filename: &Path,
2465 compiled_modules: &CompiledModules,
2466 crate_info: &CrateInfo,
2467 metadata: &EncodedMetadata,
2468 self_contained_components: LinkSelfContainedComponents,
2469 codegen_backend: &'static str,
2470) -> Command {
2471let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2472let cmd = &mut *super::linker::get_linker(
2473sess,
2474path,
2475flavor,
2476self_contained_components.are_any_components_enabled(),
2477&crate_info.target_cpu,
2478codegen_backend,
2479 );
2480let link_output_kind = link_output_kind(sess, crate_type);
24812482let mut export_symbols = crate_info.exported_symbols[&crate_type].clone();
24832484if crate_type == CrateType::Cdylib {
2485let mut seen = FxHashSet::default();
24862487for lib in &crate_info.used_libraries {
2488if let NativeLibKind::Static { export_symbols: Some(true), .. } = lib.kind
2489 && seen.insert((lib.name, lib.verbatim))
2490 {
2491if let Err(err) = add_c_staticlib_symbols(&sess, lib, &mut export_symbols) {
2492 sess.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to process C static library `{0}`: {1}",
lib.name, err))
})format!(
2493"failed to process C static library `{}`: {}",
2494 lib.name, err
2495 ));
2496 }
2497 }
2498 }
2499 }
25002501// ------------ Early order-dependent options ------------
25022503 // If we're building something like a dynamic library then some platforms
2504 // need to make sure that all symbols are exported correctly from the
2505 // dynamic library.
2506 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2507 // at least on some platforms (e.g. windows-gnu).
2508cmd.export_symbols(tmpdir, crate_type, &export_symbols);
25092510// Can be used for adding custom CRT objects or overriding order-dependent options above.
2511 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2512 // introduce a target spec option for order-independent linker options and migrate built-in
2513 // specs to it.
2514add_pre_link_args(cmd, sess, flavor);
25152516// ------------ Object code and libraries, order-dependent ------------
25172518 // Pre-link CRT objects.
2519add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
25202521add_linked_symbol_object(cmd, sess, tmpdir, &crate_info.linked_symbols[&crate_type]);
25222523// Sanitizer libraries.
2524add_sanitizer_libraries(sess, flavor, crate_type, cmd);
25252526// Object code from the current crate.
2527 // Take careful note of the ordering of the arguments we pass to the linker
2528 // here. Linkers will assume that things on the left depend on things to the
2529 // right. Things on the right cannot depend on things on the left. This is
2530 // all formally implemented in terms of resolving symbols (libs on the right
2531 // resolve unknown symbols of libs on the left, but not vice versa).
2532 //
2533 // For this reason, we have organized the arguments we pass to the linker as
2534 // such:
2535 //
2536 // 1. The local object that LLVM just generated
2537 // 2. Local native libraries
2538 // 3. Upstream rust libraries
2539 // 4. Upstream native libraries
2540 //
2541 // The rationale behind this ordering is that those items lower down in the
2542 // list can't depend on items higher up in the list. For example nothing can
2543 // depend on what we just generated (e.g., that'd be a circular dependency).
2544 // Upstream rust libraries are not supposed to depend on our local native
2545 // libraries as that would violate the structure of the DAG, in that
2546 // scenario they are required to link to them as well in a shared fashion.
2547 //
2548 // Note that upstream rust libraries may contain native dependencies as
2549 // well, but they also can't depend on what we just started to add to the
2550 // link line. And finally upstream native libraries can't depend on anything
2551 // in this DAG so far because they can only depend on other native libraries
2552 // and such dependencies are also required to be specified.
2553add_local_crate_regular_objects(cmd, compiled_modules);
2554add_local_crate_metadata_objects(
2555cmd,
2556sess,
2557archive_builder_builder,
2558crate_type,
2559tmpdir,
2560crate_info,
2561metadata,
2562 );
2563add_local_crate_allocator_objects(cmd, compiled_modules, crate_info, crate_type);
25642565// Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2566 // at the point at which they are specified on the command line.
2567 // Must be passed before any (dynamic) libraries to have effect on them.
2568 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2569 // so it will ignore unreferenced ELF sections from relocatable objects.
2570 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2571 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2572 // and move this option back to the top.
2573cmd.add_as_needed();
25742575// Local native libraries of all kinds.
2576add_local_native_libraries(
2577cmd,
2578sess,
2579archive_builder_builder,
2580crate_info,
2581tmpdir,
2582link_output_kind,
2583 );
25842585// Upstream rust crates and their non-dynamic native libraries.
2586add_upstream_rust_crates(
2587cmd,
2588sess,
2589archive_builder_builder,
2590crate_info,
2591crate_type,
2592tmpdir,
2593link_output_kind,
2594 );
25952596// Dynamic native libraries from upstream crates.
2597add_upstream_native_libraries(
2598cmd,
2599sess,
2600archive_builder_builder,
2601crate_info,
2602tmpdir,
2603link_output_kind,
2604 );
26052606// Raw-dylibs from all crates.
2607let raw_dylib_dir = tmpdir.join("raw-dylibs");
2608if sess.target.binary_format == BinaryFormat::Elf {
2609// On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2610 // instead we need to pass them via -l. To find the stub, we need to add
2611 // the directory of the stub to the linker search path.
2612 // We make an extra directory for this to avoid polluting the search path.
2613if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2614sess.dcx().emit_fatal(errors::CreateTempDir { error })
2615 }
2616cmd.include_path(&raw_dylib_dir);
2617 }
26182619// Link with the import library generated for any raw-dylib functions.
2620if sess.target.is_like_windows {
2621for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2622 sess,
2623 archive_builder_builder,
2624 crate_info.used_libraries.iter(),
2625 tmpdir,
2626true,
2627 ) {
2628 cmd.add_object(&output_path);
2629 }
2630 } else {
2631for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2632 sess,
2633 crate_info.used_libraries.iter(),
2634&raw_dylib_dir,
2635 ) {
2636// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2637cmd.link_dylib_by_name(&link_path, true, as_needed);
2638 }
2639 }
2640// As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2641 // they are used within inlined functions or instantiated generic functions. We do this *after*
2642 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2643 // by the linker.
2644let dependency_linkage = crate_info2645 .dependency_formats
2646 .get(&crate_type)
2647 .expect("failed to find crate type in dependency format list");
26482649// We sort the libraries below
2650#[allow(rustc::potential_query_instability)]
2651let mut native_libraries_from_nonstatics = crate_info2652 .native_libraries
2653 .iter()
2654 .filter_map(|(&cnum, libraries)| {
2655if sess.target.is_like_windows {
2656 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2657 } else {
2658Some(libraries)
2659 }
2660 })
2661 .flatten()
2662 .collect::<Vec<_>>();
2663native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
26642665if sess.target.is_like_windows {
2666for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2667 sess,
2668 archive_builder_builder,
2669 native_libraries_from_nonstatics,
2670 tmpdir,
2671false,
2672 ) {
2673 cmd.add_object(&output_path);
2674 }
2675 } else {
2676for (link_path, as_needed) in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2677 sess,
2678 native_libraries_from_nonstatics,
2679&raw_dylib_dir,
2680 ) {
2681// Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2682cmd.link_dylib_by_name(&link_path, true, as_needed);
2683 }
2684 }
26852686// Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2687 // command line shorter, reset it to default here before adding more libraries.
2688cmd.reset_per_library_state();
26892690// FIXME: Built-in target specs occasionally use this for linking system libraries,
2691 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2692 // and remove the option.
2693add_late_link_args(cmd, sess, flavor, crate_type, crate_info);
26942695// ------------ Arbitrary order-independent options ------------
26962697 // Add order-independent options determined by rustc from its compiler options,
2698 // target properties and source code.
2699add_order_independent_options(
2700cmd,
2701sess,
2702link_output_kind,
2703self_contained_components,
2704flavor,
2705crate_type,
2706crate_info,
2707out_filename,
2708tmpdir,
2709 );
27102711// Can be used for arbitrary order-independent options.
2712 // In practice may also be occasionally used for linking native libraries.
2713 // Passed after compiler-generated options to support manual overriding when necessary.
2714add_user_defined_link_args(cmd, sess);
27152716// ------------ Builtin configurable linker scripts ------------
2717 // The user's link args should be able to overwrite symbols in the compiler's
2718 // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2719 // to work correctly, the user needs to be able to specify linker arguments like
2720 // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2721add_link_script(cmd, sess, tmpdir, crate_type);
27222723// ------------ Object code and libraries, order-dependent ------------
27242725 // Post-link CRT objects.
2726add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
27272728// ------------ Late order-dependent options ------------
27292730 // Doesn't really make sense.
2731 // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2732 // Introduce a target spec option for order-independent linker options, migrate built-in specs
2733 // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2734add_post_link_args(cmd, sess, flavor);
27352736cmd.take_cmd()
2737}
27382739fn add_order_independent_options(
2740 cmd: &mut dyn Linker,
2741 sess: &Session,
2742 link_output_kind: LinkOutputKind,
2743 self_contained_components: LinkSelfContainedComponents,
2744 flavor: LinkerFlavor,
2745 crate_type: CrateType,
2746 crate_info: &CrateInfo,
2747 out_filename: &Path,
2748 tmpdir: &Path,
2749) {
2750// Take care of the flavors and CLI options requesting the `lld` linker.
2751add_lld_args(cmd, sess, flavor, self_contained_components);
27522753add_apple_link_args(cmd, sess, flavor);
27542755let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
27562757if sess.target.os == Os::Fuchsia2758 && crate_type == CrateType::Executable2759 && !#[allow(non_exhaustive_omitted_patterns)] match flavor {
LinkerFlavor::Gnu(Cc::Yes, _) => true,
_ => false,
}matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))2760 {
2761let prefix = if sess.sanitizers().contains(SanitizerSet::ADDRESS) { "asan/" } else { "" };
2762cmd.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"));
2763 }
27642765if sess.target.eh_frame_header {
2766cmd.add_eh_frame_header();
2767 }
27682769// Make the binary compatible with data execution prevention schemes.
2770cmd.add_no_exec();
27712772if self_contained_components.is_crt_objects_enabled() {
2773cmd.no_crt_objects();
2774 }
27752776if sess.target.os == Os::Emscripten {
2777cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2778"-fwasm-exceptions"
2779} else if sess.panic_strategy().unwinds() {
2780"-sDISABLE_EXCEPTION_CATCHING=0"
2781} else {
2782"-sDISABLE_EXCEPTION_CATCHING=1"
2783});
2784 }
27852786if flavor == LinkerFlavor::Llbc {
2787cmd.link_args(&[
2788"--target",
2789&versioned_llvm_target(sess),
2790"--target-cpu",
2791&crate_info.target_cpu,
2792 ]);
2793if crate_info.target_features.len() > 0 {
2794cmd.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(",")));
2795 }
2796 } else if flavor == LinkerFlavor::Bpf {
2797cmd.link_args(&["--cpu", &crate_info.target_cpu]);
2798if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2799 .into_iter()
2800 .find(|feat| !feat.is_empty())
2801 {
2802cmd.link_args(&["--cpu-features", feat]);
2803 }
2804 }
28052806cmd.linker_plugin_lto();
28072808add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
28092810cmd.output_filename(out_filename);
28112812if crate_type == CrateType::Executable2813 && sess.target.is_like_windows
2814 && let Some(s) = &crate_info.windows_subsystem
2815 {
2816cmd.windows_subsystem(*s);
2817 }
28182819// Try to strip as much out of the generated object by removing unused
2820 // sections if possible. See more comments in linker.rs
2821if !sess.link_dead_code() {
2822// If PGO is enabled sometimes gc_sections will remove the profile data section
2823 // as it appears to be unused. This can then cause the PGO profile file to lose
2824 // some functions. If we are generating a profile we shouldn't strip those metadata
2825 // sections to ensure we have all the data for PGO.
2826let keep_metadata =
2827crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2828cmd.gc_sections(keep_metadata);
2829 }
28302831cmd.set_output_kind(link_output_kind, crate_type, out_filename);
28322833add_relro_args(cmd, sess);
28342835// Pass optimization flags down to the linker.
2836cmd.optimize();
28372838// Gather the set of NatVis files, if any, and write them out to a temp directory.
2839let natvis_visualizers = collect_natvis_visualizers(
2840tmpdir,
2841sess,
2842&crate_info.local_crate_name,
2843&crate_info.natvis_debugger_visualizers,
2844 );
28452846// Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2847cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
28482849// We want to prevent the compiler from accidentally leaking in any system libraries,
2850 // so by default we tell linkers not to link to any default libraries.
2851if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2852cmd.no_default_libraries();
2853 }
28542855if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2856cmd.pgo_gen();
2857 }
28582859if sess.opts.unstable_opts.instrument_mcount {
2860cmd.enable_profiling();
2861 }
28622863if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2864cmd.control_flow_guard();
2865 }
28662867// OBJECT-FILES-NO, AUDIT-ORDER
2868if sess.opts.unstable_opts.ehcont_guard {
2869cmd.ehcont_guard();
2870 }
28712872add_rpath_args(cmd, sess, crate_info, out_filename);
2873}
28742875// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2876fn collect_natvis_visualizers(
2877 tmpdir: &Path,
2878 sess: &Session,
2879 crate_name: &Symbol,
2880 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2881) -> Vec<PathBuf> {
2882let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
28832884for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2885let 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));
28862887match fs::write(&visualizer_out_file, &visualizer.src) {
2888Ok(()) => {
2889 visualizer_paths.push(visualizer_out_file);
2890 }
2891Err(error) => {
2892 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2893 path: visualizer_out_file,
2894 error,
2895 });
2896 }
2897 };
2898 }
2899visualizer_paths2900}
29012902fn add_native_libs_from_crate(
2903 cmd: &mut dyn Linker,
2904 sess: &Session,
2905 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2906 crate_info: &CrateInfo,
2907 tmpdir: &Path,
2908 bundled_libs: &FxIndexSet<Symbol>,
2909 cnum: CrateNum,
2910 link_static: bool,
2911 link_dynamic: bool,
2912 link_output_kind: LinkOutputKind,
2913) {
2914if !sess.opts.unstable_opts.link_native_libraries {
2915// If `-Zlink-native-libraries=false` is set, then the assumption is that an
2916 // external build system already has the native dependencies defined, and it
2917 // will provide them to the linker itself.
2918return;
2919 }
29202921if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2922// If rlib contains native libs as archives, unpack them to tmpdir.
2923let rlib = crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap();
2924archive_builder_builder2925 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2926 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2927 }
29282929let native_libs = match cnum {
2930LOCAL_CRATE => &crate_info.used_libraries,
2931_ => &crate_info.native_libraries[&cnum],
2932 };
29332934let mut last = (None, NativeLibKind::Unspecified, false);
2935for lib in native_libs {
2936if !relevant_lib(sess, lib) {
2937continue;
2938 }
29392940// Skip if this library is the same as the last.
2941last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2942continue;
2943 } else {
2944 (Some(lib.name), lib.kind, lib.verbatim)
2945 };
29462947let name = lib.name.as_str();
2948let verbatim = lib.verbatim;
2949match lib.kind {
2950 NativeLibKind::Static { bundle, whole_archive, .. } => {
2951if link_static {
2952let bundle = bundle.unwrap_or(true);
2953let whole_archive = whole_archive == Some(true);
2954if bundle && cnum != LOCAL_CRATE {
2955if let Some(filename) = lib.filename {
2956// If rlib contains native libs as archives, they are unpacked to tmpdir.
2957let path = tmpdir.join(filename.as_str());
2958 cmd.link_staticlib_by_path(&path, whole_archive);
2959 }
2960 } else {
2961 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2962 }
2963 }
2964 }
2965 NativeLibKind::Dylib { as_needed } => {
2966if link_dynamic {
2967 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2968 }
2969 }
2970 NativeLibKind::Unspecified => {
2971// If we are generating a static binary, prefer static library when the
2972 // link kind is unspecified.
2973if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2974if link_static {
2975 cmd.link_staticlib_by_name(name, verbatim, false);
2976 }
2977 } else if link_dynamic {
2978 cmd.link_dylib_by_name(name, verbatim, true);
2979 }
2980 }
2981 NativeLibKind::Framework { as_needed } => {
2982if link_dynamic {
2983 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2984 }
2985 }
2986 NativeLibKind::RawDylib { as_needed: _ } => {
2987// Handled separately in `linker_with_args`.
2988}
2989 NativeLibKind::WasmImportModule => {}
2990 NativeLibKind::LinkArg => {
2991if link_static {
2992if verbatim {
2993 cmd.verbatim_arg(name);
2994 } else {
2995 cmd.link_arg(name);
2996 }
2997 }
2998 }
2999 }
3000 }
3001}
30023003fn add_local_native_libraries(
3004 cmd: &mut dyn Linker,
3005 sess: &Session,
3006 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3007 crate_info: &CrateInfo,
3008 tmpdir: &Path,
3009 link_output_kind: LinkOutputKind,
3010) {
3011// All static and dynamic native library dependencies are linked to the local crate.
3012let link_static = true;
3013let link_dynamic = true;
3014add_native_libs_from_crate(
3015cmd,
3016sess,
3017archive_builder_builder,
3018crate_info,
3019tmpdir,
3020&Default::default(),
3021LOCAL_CRATE,
3022link_static,
3023link_dynamic,
3024link_output_kind,
3025 );
3026}
30273028fn add_upstream_rust_crates(
3029 cmd: &mut dyn Linker,
3030 sess: &Session,
3031 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3032 crate_info: &CrateInfo,
3033 crate_type: CrateType,
3034 tmpdir: &Path,
3035 link_output_kind: LinkOutputKind,
3036) {
3037// All of the heavy lifting has previously been accomplished by the
3038 // dependency_format module of the compiler. This is just crawling the
3039 // output of that module, adding crates as necessary.
3040 //
3041 // Linking to a rlib involves just passing it to the linker (the linker
3042 // will slurp up the object files inside), and linking to a dynamic library
3043 // involves just passing the right -l flag.
3044let data = crate_info3045 .dependency_formats
3046 .get(&crate_type)
3047 .expect("failed to find crate type in dependency format list");
30483049if sess.target.is_like_aix {
3050// Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
3051 // the dependency name when outputting a shared library. Thus, `ld` will
3052 // use the full path to shared libraries as the dependency if passed it
3053 // by default unless `noipath` is passed.
3054 // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
3055cmd.link_or_cc_arg("-bnoipath");
3056 }
30573058for &cnum in &crate_info.used_crates {
3059// We may not pass all crates through to the linker. Some crates may appear statically in
3060 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
3061 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
3062 // Even if they were already included into a dylib
3063 // (e.g. `libstd` when `-C prefer-dynamic` is used).
3064 // HACK: `dependency_formats` can report `profiler_builtins` as `NotLinked`.
3065 // See the comment in inject_profiler_runtime for why this is the case.
3066let linkage = data[cnum];
3067let link_static_crate = linkage == Linkage::Static
3068 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
3069 && (crate_info.compiler_builtins == Some(cnum)
3070 || crate_info.profiler_runtime == Some(cnum));
30713072let mut bundled_libs = Default::default();
3073match linkage {
3074 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
3075if link_static_crate {
3076 bundled_libs = crate_info.native_libraries[&cnum]
3077 .iter()
3078 .filter_map(|lib| lib.filename)
3079 .collect();
3080 add_static_crate(
3081 cmd,
3082 sess,
3083 archive_builder_builder,
3084 crate_info,
3085 tmpdir,
3086 cnum,
3087&bundled_libs,
3088 );
3089 }
3090 }
3091 Linkage::Dynamic => {
3092let src = &crate_info.used_crate_source[&cnum];
3093 add_dynamic_crate(cmd, sess, src.dylib.as_ref().unwrap());
3094 }
3095 }
30963097// Static libraries are linked for a subset of linked upstream crates.
3098 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3099 // because the rlib is just an archive.
3100 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
3101 // the native library because it is already linked into the dylib, and even if
3102 // inline/const/generic functions from the dylib can refer to symbols from the native
3103 // library, those symbols should be exported and available from the dylib anyway.
3104 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
3105let link_static = link_static_crate;
3106// Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
3107let link_dynamic = false;
3108 add_native_libs_from_crate(
3109 cmd,
3110 sess,
3111 archive_builder_builder,
3112 crate_info,
3113 tmpdir,
3114&bundled_libs,
3115 cnum,
3116 link_static,
3117 link_dynamic,
3118 link_output_kind,
3119 );
3120 }
3121}
31223123fn add_upstream_native_libraries(
3124 cmd: &mut dyn Linker,
3125 sess: &Session,
3126 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3127 crate_info: &CrateInfo,
3128 tmpdir: &Path,
3129 link_output_kind: LinkOutputKind,
3130) {
3131for &cnum in &crate_info.used_crates {
3132// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
3133 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
3134 // are linked together with their respective upstream crates, and in their originally
3135 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
3136 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
3137let link_static = false;
3138// Dynamic libraries are linked for all linked upstream crates.
3139 // 1. If the upstream crate is a directly linked rlib then we must link the native library
3140 // because the rlib is just an archive.
3141 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
3142 // the native library too because inline/const/generic functions from the dylib can refer
3143 // to symbols from the native library, so the native library providing those symbols should
3144 // be available when linking our final binary.
3145let link_dynamic = true;
3146 add_native_libs_from_crate(
3147 cmd,
3148 sess,
3149 archive_builder_builder,
3150 crate_info,
3151 tmpdir,
3152&Default::default(),
3153 cnum,
3154 link_static,
3155 link_dynamic,
3156 link_output_kind,
3157 );
3158 }
3159}
31603161// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
3162// to be relative to the sysroot directory, which may be a relative path specified by the user.
3163//
3164// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
3165// linker command line can be non-deterministic due to the paths including the current working
3166// directory. The linker command line needs to be deterministic since it appears inside the PDB
3167// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
3168//
3169// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
3170fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
3171let sysroot_lib_path = &sess.target_tlib_path.dir;
3172let canonical_sysroot_lib_path =
3173 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
31743175let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
3176if canonical_lib_dir == canonical_sysroot_lib_path {
3177// This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
3178sysroot_lib_path.clone()
3179 } else {
3180fix_windows_verbatim_for_gcc(lib_dir)
3181 }
3182}
31833184fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
3185if let Some(dir) = path.parent() {
3186let file_name = path.file_name().expect("library path has no file name component");
3187rehome_sysroot_lib_dir(sess, dir).join(file_name)
3188 } else {
3189fix_windows_verbatim_for_gcc(path)
3190 }
3191}
31923193// Adds the static "rlib" versions of all crates to the command line.
3194// There's a bit of magic which happens here specifically related to LTO,
3195// namely that we remove upstream object files.
3196//
3197// When performing LTO, almost(*) all of the bytecode from the upstream
3198// libraries has already been included in our object file output. As a
3199// result we need to remove the object files in the upstream libraries so
3200// the linker doesn't try to include them twice (or whine about duplicate
3201// symbols). We must continue to include the rest of the rlib, however, as
3202// it may contain static native libraries which must be linked in.
3203//
3204// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
3205// their bytecode wasn't included. The object files in those libraries must
3206// still be passed to the linker.
3207//
3208// Note, however, that if we're not doing LTO we can just pass the rlib
3209// blindly to the linker (fast) because it's fine if it's not actually
3210// included as we're at the end of the dependency chain.
3211fn add_static_crate(
3212 cmd: &mut dyn Linker,
3213 sess: &Session,
3214 archive_builder_builder: &dyn ArchiveBuilderBuilder,
3215 crate_info: &CrateInfo,
3216 tmpdir: &Path,
3217 cnum: CrateNum,
3218 bundled_lib_file_names: &FxIndexSet<Symbol>,
3219) {
3220let src = &crate_info.used_crate_source[&cnum];
3221let cratepath = src.rlib.as_ref().unwrap();
32223223let mut link_upstream =
3224 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
32253226if !are_upstream_rust_objects_already_included(sess) || ignored_for_lto(sess, crate_info, cnum)
3227 {
3228link_upstream(cratepath);
3229return;
3230 }
32313232let dst = tmpdir.join(cratepath.file_name().unwrap());
3233let name = cratepath.file_name().unwrap().to_str().unwrap();
3234let name = &name[3..name.len() - 5]; // chop off lib/.rlib
3235let bundled_lib_file_names = bundled_lib_file_names.clone();
32363237sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
3238let upstream_rust_objects_already_included =
3239are_upstream_rust_objects_already_included(sess);
3240let is_builtins = sess.target.no_builtins || !crate_info.is_no_builtins.contains(&cnum);
32413242let mut archive = archive_builder_builder.new_archive_builder(sess);
3243if let Err(error) = archive.add_archive(
3244cratepath,
3245Some(Box::new(move |f, metadata_link| {
3246if f == METADATA_FILENAME || f == rmeta_link::FILENAME {
3247return true;
3248 }
32493250let is_rust_object =
3251metadata_link.is_some_and(|m| m.rust_object_files.iter().any(|rf| rf == f));
32523253// If we're performing LTO and this is a rust-generated object
3254 // file, then we don't need the object file as it's part of the
3255 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
3256 // though, so we let that object file slide.
3257if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3258return true;
3259 }
32603261// We skip native libraries because:
3262 // 1. This native libraries won't be used from the generated rlib,
3263 // so we can throw them away to avoid the copying work.
3264 // 2. We can't allow it to be a single remaining entry in archive
3265 // as some linkers may complain on that.
3266if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3267return true;
3268 }
32693270false
3271})),
3272 ) {
3273sess.dcx()
3274 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3275 }
3276if archive.build(&dst) {
3277link_upstream(&dst);
3278 }
3279 });
3280}
32813282// Same thing as above, but for dynamic crates instead of static crates.
3283fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3284cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3285}
32863287fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3288match lib.cfg {
3289Some(ref cfg) => eval_config_entry(sess, cfg).as_bool(),
3290None => true,
3291 }
3292}
32933294pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3295match sess.lto() {
3296 config::Lto::Fat => true,
3297 config::Lto::Thin => {
3298// If we defer LTO to the linker, we haven't run LTO ourselves, so
3299 // any upstream object files have not been copied yet.
3300!sess.opts.cg.linker_plugin_lto.enabled()
3301 }
3302 config::Lto::No | config::Lto::ThinLocal => false,
3303 }
3304}
33053306/// We need to communicate five things to the linker on Apple/Darwin targets:
3307/// - The architecture.
3308/// - The operating system (and that it's an Apple platform).
3309/// - The environment.
3310/// - The deployment target.
3311/// - The SDK version.
3312fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3313if !sess.target.is_like_darwin {
3314return;
3315 }
3316let LinkerFlavor::Darwin(cc, _) = flavorelse {
3317return;
3318 };
33193320// `sess.target.arch` (`target_arch`) is not detailed enough.
3321let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3322let target_os = &sess.target.os;
3323let target_env = &sess.target.env;
33243325// The architecture name to forward to the linker.
3326 //
3327 // Supported architecture names can be found in the source:
3328 // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3329 //
3330 // Intentionally verbose to ensure that the list always matches correctly
3331 // with the list in the source above.
3332let ld64_arch = match llvm_arch {
3333"armv7k" => "armv7k",
3334"armv7s" => "armv7s",
3335"arm64" => "arm64",
3336"arm64e" => "arm64e",
3337"arm64_32" => "arm64_32",
3338// ld64 doesn't understand i686, so fall back to i386 instead.
3339 //
3340 // Same story when linking with cc, since that ends up invoking ld64.
3341"i386" | "i686" => "i386",
3342"x86_64" => "x86_64",
3343"x86_64h" => "x86_64h",
3344_ => ::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),
3345 };
33463347if cc == Cc::No {
3348// From the man page for ld64 (`man ld`):
3349 // > The linker accepts universal (multiple-architecture) input files,
3350 // > but always creates a "thin" (single-architecture), standard
3351 // > Mach-O output file. The architecture for the output file is
3352 // > specified using the -arch option.
3353 //
3354 // The linker has heuristics to determine the desired architecture,
3355 // but to be safe, and to avoid a warning, we set the architecture
3356 // explicitly.
3357cmd.link_args(&["-arch", ld64_arch]);
33583359// Man page says that ld64 supports the following platform names:
3360 // > - macos
3361 // > - ios
3362 // > - tvos
3363 // > - watchos
3364 // > - bridgeos
3365 // > - visionos
3366 // > - xros
3367 // > - mac-catalyst
3368 // > - ios-simulator
3369 // > - tvos-simulator
3370 // > - watchos-simulator
3371 // > - visionos-simulator
3372 // > - xros-simulator
3373 // > - driverkit
3374let platform_name = match (target_os, target_env) {
3375 (os, Env::Unspecified) => os.desc(),
3376 (Os::IOs, Env::MacAbi) => "mac-catalyst",
3377 (Os::IOs, Env::Sim) => "ios-simulator",
3378 (Os::TvOs, Env::Sim) => "tvos-simulator",
3379 (Os::WatchOs, Env::Sim) => "watchos-simulator",
3380 (Os::VisionOs, Env::Sim) => "visionos-simulator",
3381_ => ::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}"),
3382 };
33833384let min_version = sess.apple_deployment_target().fmt_full().to_string();
33853386// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3387 // - By dyld to give extra warnings and errors, see e.g.:
3388 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3389 // <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3390 // - By system frameworks to change certain behaviour. For example, the default value of
3391 // `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3392 // <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3393 //
3394 // We do not currently know the actual SDK version though, so we have a few options:
3395 // 1. Use the minimum version supported by rustc.
3396 // 2. Use the same as the deployment target.
3397 // 3. Use an arbitrary recent version.
3398 // 4. Omit the version.
3399 //
3400 // The first option is too low / too conservative, and means that users will not get the
3401 // same behaviour from a binary compiled with rustc as with one compiled by clang.
3402 //
3403 // The second option is similarly conservative, and also wrong since if the user specified a
3404 // higher deployment target than the SDK they're compiling/linking with, the runtime might
3405 // make invalid assumptions about the capabilities of the binary.
3406 //
3407 // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3408 // version, and is also wrong for similar reasons as above.
3409 //
3410 // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3411 // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3412 // it as 0.0, which is again too low/conservative.
3413 //
3414 // Currently, we lie about the SDK version, and choose the second option.
3415 //
3416 // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3417 // <https://github.com/rust-lang/rust/issues/129432>
3418let sdk_version = &*min_version;
34193420// From the man page for ld64 (`man ld`):
3421 // > This is set to indicate the platform, oldest supported version of
3422 // > that platform that output is to be used on, and the SDK that the
3423 // > output was built against.
3424 //
3425 // Like with `-arch`, the linker can figure out the platform versions
3426 // itself from the binaries being linked, but to be safe, we specify
3427 // the desired versions here explicitly.
3428cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3429 } else {
3430// cc == Cc::Yes
3431 //
3432 // We'd _like_ to use `-target` everywhere, since that can uniquely
3433 // communicate all the required details except for the SDK version
3434 // (which is read by Clang itself from the SDKROOT), but that doesn't
3435 // work on GCC, and since we don't know whether the `cc` compiler is
3436 // Clang, GCC, or something else, we fall back to other options that
3437 // also work on GCC when compiling for macOS.
3438 //
3439 // Targets other than macOS are ill-supported by GCC (it doesn't even
3440 // support e.g. `-miphoneos-version-min`), so in those cases we can
3441 // fairly safely use `-target`. See also the following, where it is
3442 // made explicit that the recommendation by LLVM developers is to use
3443 // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3444if *target_os == Os::MacOs {
3445// `-arch` communicates the architecture.
3446 //
3447 // CC forwards the `-arch` to the linker, so we use the same value
3448 // here intentionally.
3449cmd.cc_args(&["-arch", ld64_arch]);
34503451// The presence of `-mmacosx-version-min` makes CC default to
3452 // macOS, and it sets the deployment target.
3453let version = sess.apple_deployment_target().fmt_full();
3454// Intentionally pass this as a single argument, Clang doesn't
3455 // seem to like it otherwise.
3456cmd.cc_arg(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-mmacosx-version-min={0}",
version))
})format!("-mmacosx-version-min={version}"));
34573458// macOS has no environment, so with these two, we've told CC the
3459 // four desired parameters.
3460 //
3461 // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3462} else {
3463cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3464 }
3465 }
3466}
34673468fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3469if !sess.target.is_like_darwin {
3470return None;
3471 }
3472let LinkerFlavor::Darwin(cc, _) = flavorelse {
3473return None;
3474 };
34753476// The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3477 // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3478 // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3479 // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3480 // instead we invoke `xcrun` manually.
3481 //
3482 // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3483 // cause the trampoline binary to skip looking up the SDK itself).
3484let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
34853486if cc == Cc::Yes {
3487// There are a few options to pass the SDK root when linking with a C/C++ compiler:
3488 // - The `--sysroot` flag.
3489 // - The `-isysroot` flag.
3490 // - The `SDKROOT` environment variable.
3491 //
3492 // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3493 // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3494 // only applies to include header files, but on Apple targets it also applies to libraries
3495 // and frameworks.
3496 //
3497 // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3498 // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3499 // primarily because that is the same interface that is used when invoking the tool under
3500 // `xcrun -sdk macosx $tool`.
3501 //
3502 // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3503 // clearly in the tool in question, since they also don't support being run under `xcrun`.
3504 //
3505 // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3506 // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3507 // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3508 //
3509 // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3510 // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3511 // ignoring the value we set here, and instead use their built-in sysroot).
3512cmd.cmd().env("SDKROOT", &sdkroot);
3513 } else {
3514// When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3515 // read by the linker, so it's really the only option.
3516 //
3517 // This is also what Clang does.
3518cmd.link_arg("-syslibroot");
3519cmd.link_arg(&sdkroot);
3520 }
35213522Some(sdkroot)
3523}
35243525fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3526if let Ok(sdkroot) = env::var("SDKROOT") {
3527let p = PathBuf::from(&sdkroot);
35283529// Ignore invalid SDKs, similar to what clang does:
3530 // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3531 //
3532 // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3533 // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3534 // clearly set for the wrong platform.
3535 //
3536 // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3537match &*apple::sdk_name(&sess.target).to_lowercase() {
3538"appletvos"
3539if sdkroot.contains("TVSimulator.platform")
3540 || sdkroot.contains("MacOSX.platform") => {}
3541"appletvsimulator"
3542if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3543"iphoneos"
3544if sdkroot.contains("iPhoneSimulator.platform")
3545 || sdkroot.contains("MacOSX.platform") => {}
3546"iphonesimulator"
3547if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3548 }
3549"macosx"
3550if sdkroot.contains("iPhoneOS.platform")
3551 || sdkroot.contains("iPhoneSimulator.platform")
3552 || sdkroot.contains("AppleTVOS.platform")
3553 || sdkroot.contains("AppleTVSimulator.platform")
3554 || sdkroot.contains("WatchOS.platform")
3555 || sdkroot.contains("WatchSimulator.platform")
3556 || sdkroot.contains("XROS.platform")
3557 || sdkroot.contains("XRSimulator.platform") => {}
3558"watchos"
3559if sdkroot.contains("WatchSimulator.platform")
3560 || sdkroot.contains("MacOSX.platform") => {}
3561"watchsimulator"
3562if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3563"xros"
3564if sdkroot.contains("XRSimulator.platform")
3565 || sdkroot.contains("MacOSX.platform") => {}
3566"xrsimulator"
3567if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3568// Ignore `SDKROOT` if it's not a valid path.
3569_ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3570_ => return Some(p),
3571 }
3572 }
35733574 apple::get_sdk_root(sess)
3575}
35763577/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3578/// invoke it:
3579/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3580/// - or any `lld` available to `cc`.
3581fn add_lld_args(
3582 cmd: &mut dyn Linker,
3583 sess: &Session,
3584 flavor: LinkerFlavor,
3585 self_contained_components: LinkSelfContainedComponents,
3586) {
3587{
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:3587",
"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(3587u32),
::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!(
3588"add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3589 flavor, self_contained_components,
3590 );
35913592// If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3593 // we don't need to do anything.
3594if !(flavor.uses_cc() && flavor.uses_lld()) {
3595return;
3596 }
35973598// 1. Implement the "self-contained" part of this feature by adding rustc distribution
3599 // directories to the tool's search path, depending on a mix between what users can specify on
3600 // the CLI, and what the target spec enables (as it can't disable components):
3601 // - if the self-contained linker is enabled on the CLI or by the target spec,
3602 // - and if the self-contained linker is not disabled on the CLI.
3603let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3604let self_contained_target = self_contained_components.is_linker_enabled();
36053606let self_contained_linker = self_contained_cli || self_contained_target;
3607if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3608let mut linker_path_exists = false;
3609for path in sess.get_tools_search_paths(false) {
3610let linker_path = path.join("gcc-ld");
3611 linker_path_exists |= linker_path.exists();
3612 cmd.cc_arg({
3613let mut arg = OsString::from("-B");
3614 arg.push(linker_path);
3615 arg
3616 });
3617 }
3618if !linker_path_exists {
3619// As a sanity check, we emit an error if none of these paths exist: we want
3620 // self-contained linking and have no linker.
3621sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3622 }
3623 }
36243625// 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3626 // `lld` as the linker.
3627 //
3628 // Note that wasm targets skip this step since the only option there anyway
3629 // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3630 // this, `wasm-component-ld`, which is overridden if this option is passed.
3631if !sess.target.is_like_wasm {
3632cmd.cc_arg("-fuse-ld=lld");
3633 }
36343635if !flavor.is_gnu() {
3636// Tell clang to use a non-default LLD flavor.
3637 // Gcc doesn't understand the target option, but we currently assume
3638 // that gcc is not used for Apple and Wasm targets (#97402).
3639 //
3640 // Note that we don't want to do that by default on macOS: e.g. passing a
3641 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3642 // shown in issue #101653 and the discussion in PR #101792.
3643 //
3644 // It could be required in some cases of cross-compiling with
3645 // LLD, but this is generally unspecified, and we don't know
3646 // which specific versions of clang, macOS SDK, host and target OS
3647 // combinations impact us here.
3648 //
3649 // So we do a simple first-approximation until we know more of what the
3650 // Apple targets require (and which would be handled prior to hitting this
3651 // LLD codepath anyway), but the expectation is that until then
3652 // this should be manually passed if needed. We specify the target when
3653 // targeting a different linker flavor on macOS, and that's also always
3654 // the case when targeting WASM.
3655if sess.target.linker_flavor != sess.host.linker_flavor {
3656cmd.cc_arg(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--target={0}",
versioned_llvm_target(sess)))
})format!("--target={}", versioned_llvm_target(sess)));
3657 }
3658 }
3659}
36603661// gold has been deprecated with binutils 2.44
3662// and is known to behave incorrectly around Rust programs.
3663// There have been reports of being unable to bootstrap with gold:
3664// https://github.com/rust-lang/rust/issues/139425
3665// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3666// emitted with `#[used(linker)]`.
3667fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3668use object::read::elf::{FileHeader, SectionHeader};
3669use object::read::{ReadCache, ReadRef, Result};
3670use object::{Endianness, elf};
36713672fn elf_has_gold_version_note<'a>(
3673 elf: &impl FileHeader,
3674 data: impl ReadRef<'a>,
3675 ) -> Result<bool> {
3676let endian = elf.endian()?;
36773678let section =
3679 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3680if let Some((_, section)) = section3681 && let Some(mut notes) = section.notes(endian, data)?
3682{
3683return Ok(notes.any(|note| {
3684note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3685 }));
3686 }
36873688Ok(false)
3689 }
36903691let data = ReadCache::new(BufReader::new(File::open(path)?));
36923693let was_linked_with_gold = if sess.target.pointer_width == 64 {
3694let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3695 elf_has_gold_version_note(elf, &data)?
3696} else if sess.target.pointer_width == 32 {
3697let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3698 elf_has_gold_version_note(elf, &data)?
3699} else {
3700return Ok(());
3701 };
37023703if was_linked_with_gold {
3704let mut warn =
3705sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3706warn.help("consider using LLD or ld from GNU binutils instead");
3707warn.emit();
3708 }
3709Ok(())
3710}