1 use rustc_arena::TypedArena;
2 use rustc_ast::CRATE_NODE_ID;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::fx::FxIndexMap;
5 use rustc_data_structures::memmap::Mmap;
6 use rustc_data_structures::temp_dir::MaybeTempDir;
7 use rustc_errors::{ErrorGuaranteed, Handler};
8 use rustc_fs_util::fix_windows_verbatim_for_gcc;
9 use rustc_hir::def_id::CrateNum;
10 use rustc_metadata::find_native_static_library;
11 use rustc_metadata::fs::{emit_metadata, METADATA_FILENAME};
12 use rustc_middle::middle::dependency_format::Linkage;
13 use rustc_middle::middle::exported_symbols::SymbolExportKind;
14 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, LdImpl, Lto, Strip};
15 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SplitDwarfKind};
16 use rustc_session::cstore::DllImport;
17 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
18 use rustc_session::search_paths::PathKind;
19 use rustc_session::utils::NativeLibKind;
20 /// For all the linkers we support, and information they might
21 /// need out of the shared crate context before we get rid of it.
22 use rustc_session::{filesearch, Session};
23 use rustc_span::symbol::Symbol;
24 use rustc_span::DebuggerVisualizerFile;
25 use rustc_target::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
26 use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy};
27 use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, Target};
29 use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
30 use super::command::Command;
31 use super::linker::{self, Linker};
32 use super::metadata::{create_rmeta_file, MetadataPosition};
33 use super::rpath::{self, RPathConfig};
35 errors, looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib,
38 use cc::windows_registry;
40 use tempfile::Builder as TempFileBuilder;
42 use itertools::Itertools;
43 use std::borrow::Borrow;
44 use std::cell::OnceCell;
45 use std::collections::BTreeSet;
46 use std::ffi::OsString;
47 use std::fs::{File, OpenOptions};
48 use std::io::{BufWriter, Write};
50 use std::path::{Path, PathBuf};
51 use std::process::{ExitStatus, Output, Stdio};
52 use std::{env, fmt, fs, io, mem, str};
54 pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
55 if let Err(e) = fs::remove_file(path) {
56 if e.kind() != io::ErrorKind::NotFound {
57 diag_handler.err(&format!("failed to remove {}: {}", path.display(), e));
62 /// Performs the linkage portion of the compilation phase. This will generate all
63 /// of the requested outputs for this compilation session.
64 pub fn link_binary<'a>(
66 archive_builder_builder: &dyn ArchiveBuilderBuilder,
67 codegen_results: &CodegenResults,
68 outputs: &OutputFilenames,
69 ) -> Result<(), ErrorGuaranteed> {
70 let _timer = sess.timer("link_binary");
71 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
72 for &crate_type in sess.crate_types().iter() {
73 // Ignore executable crates if we have -Z no-codegen, as they will error.
74 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
76 && crate_type == CrateType::Executable
81 if invalid_output_for_target(sess, crate_type) {
83 "invalid output type `{:?}` for target os `{}`",
85 sess.opts.target_triple
89 sess.time("link_binary_check_files_are_writeable", || {
90 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
91 check_file_is_writeable(obj, sess);
95 if outputs.outputs.should_link() {
96 let tmpdir = TempFileBuilder::new()
99 .unwrap_or_else(|error| sess.emit_fatal(errors::CreateTempDir { error }));
100 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
101 let out_filename = out_filename(
105 codegen_results.crate_info.local_crate_name.as_str(),
109 let _timer = sess.timer("link_rlib");
110 info!("preparing rlib to {:?}", out_filename);
113 archive_builder_builder,
118 .build(&out_filename);
120 CrateType::Staticlib => {
123 archive_builder_builder,
132 archive_builder_builder,
140 if sess.opts.json_artifact_notifications {
141 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
144 if sess.prof.enabled() {
145 if let Some(artifact_name) = out_filename.file_name() {
146 // Record size for self-profiling
147 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
149 sess.prof.artifact_size(
151 artifact_name.to_string_lossy(),
159 // Remove the temporary object file and metadata if we aren't saving temps.
160 sess.time("link_binary_remove_temps", || {
161 // If the user requests that temporaries are saved, don't delete any.
162 if sess.opts.cg.save_temps {
166 let maybe_remove_temps_from_module =
167 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
168 if !preserve_objects {
169 if let Some(ref obj) = module.object {
170 ensure_removed(sess.diagnostic(), obj);
174 if !preserve_dwarf_objects {
175 if let Some(ref dwo_obj) = module.dwarf_object {
176 ensure_removed(sess.diagnostic(), dwo_obj);
181 let remove_temps_from_module =
182 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
184 // Otherwise, always remove the metadata and allocator module temporaries.
185 if let Some(ref metadata_module) = codegen_results.metadata_module {
186 remove_temps_from_module(metadata_module);
189 if let Some(ref allocator_module) = codegen_results.allocator_module {
190 remove_temps_from_module(allocator_module);
193 // If no requested outputs require linking, then the object temporaries should
195 if !sess.opts.output_types.should_link() {
199 // Potentially keep objects for their debuginfo.
200 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
201 debug!(?preserve_objects, ?preserve_dwarf_objects);
203 for module in &codegen_results.modules {
204 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
211 pub fn each_linked_rlib(
214 f: &mut dyn FnMut(CrateNum, &Path),
215 ) -> Result<(), errors::LinkRlibError> {
216 let crates = info.used_crates.iter();
219 let lto_active = matches!(sess.lto(), Lto::Fat | Lto::Thin);
221 for combination in info.dependency_formats.iter().combinations(2) {
222 let (ty1, list1) = &combination[0];
223 let (ty2, list2) = &combination[1];
225 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
226 ty1: format!("{ty1:?}"),
227 ty2: format!("{ty2:?}"),
228 list1: format!("{list1:?}"),
229 list2: format!("{list2:?}"),
235 for (ty, list) in info.dependency_formats.iter() {
237 CrateType::Executable
238 | CrateType::Staticlib
240 | CrateType::ProcMacro => {
244 CrateType::Dylib if lto_active => {
251 let Some(fmts) = fmts else {
252 return Err(errors::LinkRlibError::MissingFormat);
254 for &cnum in crates {
255 match fmts.get(cnum.as_usize() - 1) {
256 Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
258 None => return Err(errors::LinkRlibError::MissingFormat),
260 let crate_name = info.crate_name[&cnum];
261 let used_crate_source = &info.used_crate_source[&cnum];
262 if let Some((path, _)) = &used_crate_source.rlib {
265 if used_crate_source.rmeta.is_some() {
266 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
268 return Err(errors::LinkRlibError::NotFound { crate_name });
275 /// Create an 'rlib'.
277 /// An rlib in its current incarnation is essentially a renamed .a file. The rlib primarily contains
278 /// the object file of the crate, but it also contains all of the object files from native
279 /// libraries. This is done by unzipping native libraries and inserting all of the contents into
283 archive_builder_builder: &dyn ArchiveBuilderBuilder,
284 codegen_results: &CodegenResults,
286 tmpdir: &MaybeTempDir,
287 ) -> Result<Box<dyn ArchiveBuilder<'a> + 'a>, ErrorGuaranteed> {
288 let lib_search_paths = archive_search_paths(sess);
290 let mut ab = archive_builder_builder.new_archive_builder(sess);
292 let trailing_metadata = match flavor {
293 RlibFlavor::Normal => {
294 let (metadata, metadata_position) =
295 create_rmeta_file(sess, codegen_results.metadata.raw_data());
296 let metadata = emit_metadata(sess, &metadata, tmpdir);
297 match metadata_position {
298 MetadataPosition::First => {
299 // Most of the time metadata in rlib files is wrapped in a "dummy" object
300 // file for the target platform so the rlib can be processed entirely by
301 // normal linkers for the platform. Sometimes this is not possible however.
302 // If it is possible however, placing the metadata object first improves
303 // performance of getting metadata from rlibs.
304 ab.add_file(&metadata);
307 MetadataPosition::Last => Some(metadata),
311 RlibFlavor::StaticlibBase => None,
314 for m in &codegen_results.modules {
315 if let Some(obj) = m.object.as_ref() {
319 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
320 ab.add_file(dwarf_obj);
325 RlibFlavor::Normal => {}
326 RlibFlavor::StaticlibBase => {
327 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
328 if let Some(obj) = obj {
334 // Used if packed_bundled_libs flag enabled.
335 let mut packed_bundled_libs = Vec::new();
337 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
338 // we may not be configured to actually include a static library if we're
339 // adding it here. That's because later when we consume this rlib we'll
340 // decide whether we actually needed the static library or not.
342 // To do this "correctly" we'd need to keep track of which libraries added
343 // which object files to the archive. We don't do that here, however. The
344 // #[link(cfg(..))] feature is unstable, though, and only intended to get
345 // liblibc working. In that sense the check below just indicates that if
346 // there are any libraries we want to omit object files for at link time we
347 // just exclude all custom object files.
349 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
350 // feature then we'll need to figure out how to record what objects were
351 // loaded from the libraries found here and then encode that into the
352 // metadata of the rlib we're generating somehow.
353 for lib in codegen_results.crate_info.used_libraries.iter() {
355 NativeLibKind::Static { bundle: None | Some(true), whole_archive: Some(true) }
356 if flavor == RlibFlavor::Normal && sess.opts.unstable_opts.packed_bundled_libs => {}
357 NativeLibKind::Static { bundle: None | Some(true), whole_archive: Some(true) }
358 if flavor == RlibFlavor::Normal =>
360 // Don't allow mixing +bundle with +whole_archive since an rlib may contain
361 // multiple native libs, some of which are +whole-archive and some of which are
362 // -whole-archive and it isn't clear how we can currently handle such a
363 // situation correctly.
364 // See https://github.com/rust-lang/rust/issues/88085#issuecomment-901050897
365 sess.emit_err(errors::IncompatibleLinkingModifiers);
367 NativeLibKind::Static { bundle: None | Some(true), .. } => {}
368 NativeLibKind::Static { bundle: Some(false), .. }
369 | NativeLibKind::Dylib { .. }
370 | NativeLibKind::Framework { .. }
371 | NativeLibKind::RawDylib
372 | NativeLibKind::LinkArg
373 | NativeLibKind::Unspecified => continue,
375 if let Some(name) = lib.name {
377 find_native_static_library(name.as_str(), lib.verbatim, &lib_search_paths, sess);
378 if sess.opts.unstable_opts.packed_bundled_libs && flavor == RlibFlavor::Normal {
379 packed_bundled_libs.push(find_native_static_library(
380 lib.filename.unwrap().as_str(),
387 ab.add_archive(&location, Box::new(|_| false)).unwrap_or_else(|error| {
388 sess.emit_fatal(errors::AddNativeLibrary { library_path: location, error });
393 for (raw_dylib_name, raw_dylib_imports) in
394 collate_raw_dylibs(sess, codegen_results.crate_info.used_libraries.iter())?
396 let output_path = archive_builder_builder.create_dll_import_lib(
404 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
405 sess.emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
409 if let Some(trailing_metadata) = trailing_metadata {
410 // Note that it is important that we add all of our non-object "magical
411 // files" *after* all of the object files in the archive. The reason for
412 // this is as follows:
414 // * When performing LTO, this archive will be modified to remove
415 // objects from above. The reason for this is described below.
417 // * When the system linker looks at an archive, it will attempt to
418 // determine the architecture of the archive in order to see whether its
421 // The algorithm for this detection is: iterate over the files in the
422 // archive. Skip magical SYMDEF names. Interpret the first file as an
423 // object file. Read architecture from the object file.
425 // * As one can probably see, if "metadata" and "foo.bc" were placed
426 // before all of the objects, then the architecture of this archive would
427 // not be correctly inferred once 'foo.o' is removed.
429 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
430 // file for the target platform so the rlib can be processed entirely by
431 // normal linkers for the platform. Sometimes this is not possible however.
433 // Basically, all this means is that this code should not move above the
435 ab.add_file(&trailing_metadata);
438 // Add all bundled static native library dependencies.
439 // Archives added to the end of .rlib archive, see comment above for the reason.
440 for lib in packed_bundled_libs {
447 /// Extract all symbols defined in raw-dylib libraries, collated by library name.
449 /// If we have multiple extern blocks that specify symbols defined in the same raw-dylib library,
450 /// then the CodegenResults value contains one NativeLib instance for each block. However, the
451 /// linker appears to expect only a single import library for each library used, so we need to
452 /// collate the symbols together by library name before generating the import libraries.
453 fn collate_raw_dylibs<'a, 'b>(
455 used_libraries: impl IntoIterator<Item = &'b NativeLib>,
456 ) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed> {
457 // Use index maps to preserve original order of imports and libraries.
458 let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
460 for lib in used_libraries {
461 if lib.kind == NativeLibKind::RawDylib {
462 let ext = if matches!(lib.verbatim, Some(true)) { "" } else { ".dll" };
463 let name = format!("{}{}", lib.name.expect("unnamed raw-dylib library"), ext);
464 let imports = dylib_table.entry(name.clone()).or_default();
465 for import in &lib.dll_imports {
466 if let Some(old_import) = imports.insert(import.name, import) {
467 // FIXME: when we add support for ordinals, figure out if we need to do anything
468 // if we have two DllImport values with the same name but different ordinals.
469 if import.calling_convention != old_import.calling_convention {
470 sess.emit_err(errors::MultipleExternalFuncDecl {
472 function: import.name,
480 sess.compile_status()?;
483 .map(|(name, imports)| {
484 (name, imports.into_iter().map(|(_, import)| import.clone()).collect())
489 /// Create a static archive.
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.
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.
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).
500 fn link_staticlib<'a>(
502 archive_builder_builder: &dyn ArchiveBuilderBuilder,
503 codegen_results: &CodegenResults,
505 tempdir: &MaybeTempDir,
506 ) -> Result<(), ErrorGuaranteed> {
507 info!("preparing staticlib to {:?}", out_filename);
508 let mut ab = link_rlib(
510 archive_builder_builder,
512 RlibFlavor::StaticlibBase,
515 let mut all_native_libs = vec![];
517 let res = each_linked_rlib(sess, &codegen_results.crate_info, &mut |cnum, path| {
518 let name = codegen_results.crate_info.crate_name[&cnum];
519 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
521 // Here when we include the rlib into our staticlib we need to make a
522 // decision whether to include the extra object files along the way.
523 // These extra object files come from statically included native
524 // libraries, but they may be cfg'd away with #[link(cfg(..))].
526 // This unstable feature, though, only needs liblibc to work. The only
527 // use case there is where musl is statically included in liblibc.rlib,
528 // so if we don't want the included version we just need to skip it. As
529 // a result the logic here is that if *any* linked library is cfg'd away
530 // we just skip all object files.
532 // Clearly this is not sufficient for a general purpose feature, and
533 // we'd want to read from the library's metadata to determine which
534 // object files come from where and selectively skip them.
535 let skip_object_files = native_libs.iter().any(|lib| {
536 matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
537 && !relevant_lib(sess, lib)
540 let lto = are_upstream_rust_objects_already_included(sess)
541 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
543 // Ignoring obj file starting with the crate name
544 // as simple comparison is not enough - there
545 // might be also an extra name suffix
546 let obj_start = name.as_str().to_owned();
550 Box::new(move |fname: &str| {
551 // Ignore metadata files, no matter the name.
552 if fname == METADATA_FILENAME {
556 // Don't include Rust objects if LTO is enabled
557 if lto && looks_like_rust_object_file(fname) {
561 // Otherwise if this is *not* a rust object and we're skipping
562 // objects then skip this file
563 if skip_object_files && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
567 // ok, don't skip this
573 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
575 if let Err(e) = res {
579 ab.build(out_filename);
581 if !all_native_libs.is_empty() {
582 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
583 print_native_static_libs(sess, &all_native_libs);
590 /// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
592 fn link_dwarf_object<'a>(
594 cg_results: &CodegenResults,
595 executable_out_filename: &Path,
597 let dwp_out_filename = executable_out_filename.with_extension("dwp");
598 debug!(?dwp_out_filename, ?executable_out_filename);
601 struct ThorinSession<Relocations> {
602 arena_data: TypedArena<Vec<u8>>,
603 arena_mmap: TypedArena<Mmap>,
604 arena_relocations: TypedArena<Relocations>,
607 impl<Relocations> ThorinSession<Relocations> {
608 fn alloc_mmap<'arena>(&'arena self, data: Mmap) -> &'arena Mmap {
609 (*self.arena_mmap.alloc(data)).borrow()
613 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
614 fn alloc_data<'arena>(&'arena self, data: Vec<u8>) -> &'arena [u8] {
615 (*self.arena_data.alloc(data)).borrow()
618 fn alloc_relocation<'arena>(&'arena self, data: Relocations) -> &'arena Relocations {
619 (*self.arena_relocations.alloc(data)).borrow()
622 fn read_input<'arena>(&'arena self, path: &Path) -> std::io::Result<&'arena [u8]> {
623 let file = File::open(&path)?;
624 let mmap = (unsafe { Mmap::map(file) })?;
625 Ok(self.alloc_mmap(mmap))
629 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
630 let thorin_sess = ThorinSession::default();
631 let mut package = thorin::DwarfPackage::new(&thorin_sess);
633 // Input objs contain .o/.dwo files from the current crate.
634 match sess.opts.unstable_opts.split_dwarf_kind {
635 SplitDwarfKind::Single => {
636 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
637 package.add_input_object(input_obj)?;
640 SplitDwarfKind::Split => {
641 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
642 package.add_input_object(input_obj)?;
647 // Input rlibs contain .o/.dwo files from dependencies.
648 let input_rlibs = cg_results
652 .filter_map(|csource| csource.rlib.as_ref())
653 .map(|(path, _)| path);
654 for input_rlib in input_rlibs {
656 package.add_input_object(input_rlib)?;
659 // Failing to read the referenced objects is expected for dependencies where the path in the
660 // executable will have been cleaned by Cargo, but the referenced objects will be contained
661 // within rlibs provided as inputs.
663 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
664 // found, but are provided explicitly above.
666 // Adding an executable is primarily done to make `thorin` check that all the referenced
667 // dwarf objects are found in the end.
668 package.add_executable(
669 &executable_out_filename,
670 thorin::MissingReferencedObjectBehaviour::Skip,
673 let output = package.finish()?.write()?;
674 let mut output_stream = BufWriter::new(
680 .open(dwp_out_filename)?,
682 output_stream.write_all(&output)?;
683 output_stream.flush()?;
689 sess.emit_err(errors::ThorinErrorWrapper(e));
690 sess.abort_if_errors();
695 /// Create a dynamic library or executable.
697 /// This will invoke the system linker/cc to create the resulting file. This links to all upstream
699 fn link_natively<'a>(
701 archive_builder_builder: &dyn ArchiveBuilderBuilder,
702 crate_type: CrateType,
704 codegen_results: &CodegenResults,
706 ) -> Result<(), ErrorGuaranteed> {
707 info!("preparing {:?} to {:?}", crate_type, out_filename);
708 let (linker_path, flavor) = linker_and_flavor(sess);
709 let mut cmd = linker_with_args(
713 archive_builder_builder,
720 linker::disable_localization(&mut cmd);
722 for &(ref k, ref v) in sess.target.link_env.as_ref() {
723 cmd.env(k.as_ref(), v.as_ref());
725 for k in sess.target.link_env_remove.as_ref() {
726 cmd.env_remove(k.as_ref());
729 if sess.opts.prints.contains(&PrintRequest::LinkArgs) {
730 println!("{:?}", &cmd);
733 // May have not found libraries in the right formats.
734 sess.abort_if_errors();
736 // Invoke the system linker
738 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
739 let unknown_arg_regex =
740 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
745 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
746 let Ok(ref output) = prog else {
749 if output.status.success() {
752 let mut out = output.stderr.clone();
753 out.extend(&output.stdout);
754 let out = String::from_utf8_lossy(&out);
756 // Check to see if the link failed with an error message that indicates it
757 // doesn't recognize the -no-pie option. If so, re-perform the link step
758 // without it. This is safe because if the linker doesn't support -no-pie
759 // then it should not default to linking executables as pie. Different
760 // versions of gcc seem to use different quotes in the error message so
761 // don't check for them.
762 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
763 && unknown_arg_regex.is_match(&out)
764 && out.contains("-no-pie")
765 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
767 info!("linker output: {:?}", out);
768 warn!("Linker does not support -no-pie command line option. Retrying without.");
769 for arg in cmd.take_args() {
770 if arg.to_string_lossy() != "-no-pie" {
778 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
779 // Fallback from '-static-pie' to '-static' in that case.
780 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
781 && unknown_arg_regex.is_match(&out)
782 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
783 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
785 info!("linker output: {:?}", out);
787 "Linker does not support -static-pie command line option. Retrying with -static instead."
789 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
790 let self_contained = self_contained(sess, crate_type);
791 let opts = &sess.target;
792 let pre_objects = if self_contained {
793 &opts.pre_link_objects_self_contained
795 &opts.pre_link_objects
797 let post_objects = if self_contained {
798 &opts.post_link_objects_self_contained
800 &opts.post_link_objects
802 let get_objects = |objects: &CrtObjects, kind| {
808 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
811 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
812 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
813 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
814 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
815 // Assume that we know insertion positions for the replacement arguments from replaced
816 // arguments, which is true for all supported targets.
817 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
818 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
819 for arg in cmd.take_args() {
820 if arg.to_string_lossy() == "-static-pie" {
821 // Replace the output kind.
823 } else if pre_objects_static_pie.contains(&arg) {
824 // Replace the pre-link objects (replace the first and remove the rest).
825 cmd.args(mem::take(&mut pre_objects_static));
826 } else if post_objects_static_pie.contains(&arg) {
827 // Replace the post-link objects (replace the first and remove the rest).
828 cmd.args(mem::take(&mut post_objects_static));
837 // Here's a terribly awful hack that really shouldn't be present in any
838 // compiler. Here an environment variable is supported to automatically
839 // retry the linker invocation if the linker looks like it segfaulted.
841 // Gee that seems odd, normally segfaults are things we want to know
842 // about! Unfortunately though in rust-lang/rust#38878 we're
843 // experiencing the linker segfaulting on Travis quite a bit which is
844 // causing quite a bit of pain to land PRs when they spuriously fail
845 // due to a segfault.
847 // The issue #38878 has some more debugging information on it as well,
848 // but this unfortunately looks like it's just a race condition in
849 // macOS's linker with some thread pool working in the background. It
850 // seems that no one currently knows a fix for this so in the meantime
851 // we're left with this...
852 if !retry_on_segfault || i > 3 {
855 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
856 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
857 if out.contains(msg_segv) || out.contains(msg_bus) {
860 "looks like the linker segfaulted when we tried to call it, \
861 automatically retrying again",
866 if is_illegal_instruction(&output.status) {
868 ?cmd, %out, status = %output.status,
869 "looks like the linker hit an illegal instruction when we \
870 tried to call it, automatically retrying again.",
876 fn is_illegal_instruction(status: &ExitStatus) -> bool {
877 use std::os::unix::prelude::*;
878 status.signal() == Some(libc::SIGILL)
882 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
889 if !prog.status.success() {
890 let mut output = prog.stderr.clone();
891 output.extend_from_slice(&prog.stdout);
892 let escaped_output = escape_string(&output);
893 // FIXME: Add UI tests for this error.
894 let err = errors::LinkingFailed {
895 linker_path: &linker_path,
896 exit_status: prog.status,
898 escaped_output: &escaped_output,
900 sess.diagnostic().emit_err(err);
901 // If MSVC's `link.exe` was expected but the return code
902 // is not a Microsoft LNK error then suggest a way to fix or
903 // install the Visual Studio build tools.
904 if let Some(code) = prog.status.code() {
905 if sess.target.is_like_msvc
906 && flavor == LinkerFlavor::Msvc(Lld::No)
907 // Respect the command line override
908 && sess.opts.cg.linker.is_none()
909 // Match exactly "link.exe"
910 && linker_path.to_str() == Some("link.exe")
911 // All Microsoft `link.exe` linking error codes are
912 // four digit numbers in the range 1000 to 9999 inclusive
913 && (code < 1000 || code > 9999)
915 let is_vs_installed = windows_registry::find_vs_version().is_ok();
916 let has_linker = windows_registry::find_tool(
917 &sess.opts.target_triple.triple(),
922 sess.emit_note(errors::LinkExeUnexpectedError);
923 if is_vs_installed && has_linker {
924 // the linker is broken
925 sess.emit_note(errors::RepairVSBuildTools);
926 sess.emit_note(errors::MissingCppBuildToolComponent);
927 } else if is_vs_installed {
928 // the linker is not installed
929 sess.emit_note(errors::SelectCppBuildToolWorkload);
931 // visual studio is not installed
932 sess.emit_note(errors::VisualStudioNotInstalled);
937 sess.abort_if_errors();
939 info!("linker stderr:\n{}", escape_string(&prog.stderr));
940 info!("linker stdout:\n{}", escape_string(&prog.stdout));
943 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
945 if linker_not_found {
946 sess.emit_err(errors::LinkerNotFound { linker_path, error: e });
948 sess.emit_err(errors::UnableToExeLinker {
951 command_formatted: format!("{:?}", &cmd),
955 if sess.target.is_like_msvc && linker_not_found {
956 sess.emit_note(errors::MsvcMissingLinker);
957 sess.emit_note(errors::CheckInstalledVisualStudio);
958 sess.emit_note(errors::UnsufficientVSCodeProduct);
960 sess.abort_if_errors();
964 match sess.split_debuginfo() {
965 // If split debug information is disabled or located in individual files
966 // there's nothing to do here.
967 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
969 // If packed split-debuginfo is requested, but the final compilation
970 // doesn't actually have any debug information, then we skip this step.
971 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
973 // On macOS the external `dsymutil` tool is used to create the packed
974 // debug information. Note that this will read debug information from
975 // the objects on the filesystem which we'll clean up later.
976 SplitDebuginfo::Packed if sess.target.is_like_osx => {
977 let prog = Command::new("dsymutil").arg(out_filename).output();
980 if !prog.status.success() {
981 let mut output = prog.stderr.clone();
982 output.extend_from_slice(&prog.stdout);
983 sess.emit_warning(errors::ProcessingDymutilFailed {
985 output: escape_string(&output),
989 Err(error) => sess.emit_fatal(errors::UnableToRunDsymutil { error }),
993 // On MSVC packed debug information is produced by the linker itself so
994 // there's no need to do anything else here.
995 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
997 // ... and otherwise we're processing a `*.dwp` packed dwarf file.
999 // We cannot rely on the .o paths in the executable because they may have been
1000 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1001 // the .o/.dwo paths explicitly.
1002 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1005 let strip = strip_value(sess);
1007 if sess.target.is_like_osx {
1008 match (strip, crate_type) {
1009 (Strip::Debuginfo, _) => {
1010 strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-S"))
1012 // Per the manpage, `-x` is the maximum safe strip level for dynamic libraries. (#93988)
1013 (Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro) => {
1014 strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-x"))
1016 (Strip::Symbols, _) => {
1017 strip_symbols_with_external_utility(sess, "strip", &out_filename, None)
1019 (Strip::None, _) => {}
1023 if sess.target.os == "illumos" {
1024 // Many illumos systems will have both the native 'strip' utility and
1025 // the GNU one. Use the native version explicitly and do not rely on
1026 // what's in the path.
1027 let stripcmd = "/usr/bin/strip";
1029 // Always preserve the symbol table (-x).
1030 Strip::Debuginfo => {
1031 strip_symbols_with_external_utility(sess, stripcmd, &out_filename, Some("-x"))
1033 // Strip::Symbols is handled via the --strip-all linker option.
1034 Strip::Symbols => {}
1042 // Temporarily support both -Z strip and -C strip
1043 fn strip_value(sess: &Session) -> Strip {
1044 match (sess.opts.unstable_opts.strip, sess.opts.cg.strip) {
1045 (s, Strip::None) => s,
1050 fn strip_symbols_with_external_utility<'a>(
1053 out_filename: &Path,
1054 option: Option<&str>,
1056 let mut cmd = Command::new(util);
1057 if let Some(option) = option {
1060 let prog = cmd.arg(out_filename).output();
1063 if !prog.status.success() {
1064 let mut output = prog.stderr.clone();
1065 output.extend_from_slice(&prog.stdout);
1066 sess.emit_warning(errors::StrippingDebuInfoFailed {
1068 status: prog.status,
1069 output: escape_string(&output),
1073 Err(error) => sess.emit_fatal(errors::UnableToRun { util, error }),
1077 fn escape_string(s: &[u8]) -> String {
1078 match str::from_utf8(s) {
1079 Ok(s) => s.to_owned(),
1080 // FIXME: return a type that can conform to IntoDiagnosticArg
1081 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1085 fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
1086 // On macOS the runtimes are distributed as dylibs which should be linked to
1087 // both executables and dynamic shared objects. Everywhere else the runtimes
1088 // are currently distributed as static libraries which should be linked to
1089 // executables only.
1090 let needs_runtime = !sess.target.is_like_android
1091 && match crate_type {
1092 CrateType::Executable => true,
1093 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
1094 CrateType::Rlib | CrateType::Staticlib => false,
1101 let sanitizer = sess.opts.unstable_opts.sanitizer;
1102 if sanitizer.contains(SanitizerSet::ADDRESS) {
1103 link_sanitizer_runtime(sess, linker, "asan");
1105 if sanitizer.contains(SanitizerSet::LEAK) {
1106 link_sanitizer_runtime(sess, linker, "lsan");
1108 if sanitizer.contains(SanitizerSet::MEMORY) {
1109 link_sanitizer_runtime(sess, linker, "msan");
1111 if sanitizer.contains(SanitizerSet::THREAD) {
1112 link_sanitizer_runtime(sess, linker, "tsan");
1114 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1115 link_sanitizer_runtime(sess, linker, "hwasan");
1119 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
1120 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1122 filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
1123 let path = session_tlib.join(filename);
1125 return session_tlib;
1127 let default_sysroot = filesearch::get_or_default_sysroot();
1128 let default_tlib = filesearch::make_target_lib_path(
1130 sess.opts.target_triple.triple(),
1132 return default_tlib;
1136 let channel = option_env!("CFG_RELEASE_CHANNEL")
1137 .map(|channel| format!("-{}", channel))
1138 .unwrap_or_default();
1140 if sess.target.is_like_osx {
1141 // On Apple platforms, the sanitizer is always built as a dylib, and
1142 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1143 // rpath to the library as well (the rpath should be absolute, see
1144 // PR #41352 for details).
1145 let filename = format!("rustc{}_rt.{}", channel, name);
1146 let path = find_sanitizer_runtime(&sess, &filename);
1147 let rpath = path.to_str().expect("non-utf8 component in path");
1148 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
1149 linker.link_dylib(&filename, false, true);
1151 let filename = format!("librustc{}_rt.{}.a", channel, name);
1152 let path = find_sanitizer_runtime(&sess, &filename).join(&filename);
1153 linker.link_whole_rlib(&path);
1157 /// Returns a boolean indicating whether the specified crate should be ignored
1160 /// Crates ignored during LTO are not lumped together in the "massive object
1161 /// file" that we create and are linked in their normal rlib states. See
1162 /// comments below for what crates do not participate in LTO.
1164 /// It's unusual for a crate to not participate in LTO. Typically only
1165 /// compiler-specific and unstable crates have a reason to not participate in
1167 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1168 // If our target enables builtin function lowering in LLVM then the
1169 // crates providing these functions don't participate in LTO (e.g.
1170 // no_builtins or compiler builtins crates).
1171 !sess.target.no_builtins
1172 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1175 // This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1176 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1179 linker: Option<PathBuf>,
1180 flavor: Option<LinkerFlavor>,
1181 ) -> Option<(PathBuf, LinkerFlavor)> {
1182 match (linker, flavor) {
1183 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1184 // only the linker flavor is known; use the default linker for the selected flavor
1185 (None, Some(flavor)) => Some((
1186 PathBuf::from(match flavor {
1187 LinkerFlavor::Gnu(Cc::Yes, _)
1188 | LinkerFlavor::Darwin(Cc::Yes, _)
1189 | LinkerFlavor::WasmLld(Cc::Yes)
1190 | LinkerFlavor::Unix(Cc::Yes) => {
1191 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1192 // On historical Solaris systems, "cc" may have
1193 // been Sun Studio, which is not flag-compatible
1194 // with "gcc". This history casts a long shadow,
1195 // and many modern illumos distributions today
1196 // ship GCC as "gcc" without also making it
1197 // available as "cc".
1203 LinkerFlavor::Gnu(_, Lld::Yes)
1204 | LinkerFlavor::Darwin(_, Lld::Yes)
1205 | LinkerFlavor::WasmLld(..)
1206 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1207 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1210 LinkerFlavor::Msvc(..) => "link.exe",
1211 LinkerFlavor::EmCc => {
1218 LinkerFlavor::Bpf => "bpf-linker",
1219 LinkerFlavor::Ptx => "rust-ptx-linker",
1223 (Some(linker), None) => {
1224 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1225 sess.emit_fatal(errors::LinkerFileStem);
1228 let flavor = if stem == "emcc" {
1230 } else if stem == "gcc"
1231 || stem.ends_with("-gcc")
1233 || stem.ends_with("-clang")
1235 LinkerFlavor::from_cli(LinkerFlavorCli::Gcc, &sess.target)
1236 } else if stem == "wasm-ld" || stem.ends_with("-wasm-ld") {
1237 LinkerFlavor::WasmLld(Cc::No)
1238 } else if stem == "ld" || stem.ends_with("-ld") {
1239 LinkerFlavor::from_cli(LinkerFlavorCli::Ld, &sess.target)
1240 } else if stem == "ld.lld" {
1241 LinkerFlavor::Gnu(Cc::No, Lld::Yes)
1242 } else if stem == "link" {
1243 LinkerFlavor::Msvc(Lld::No)
1244 } else if stem == "lld-link" {
1245 LinkerFlavor::Msvc(Lld::Yes)
1246 } else if stem == "lld" || stem == "rust-lld" {
1247 let lld_flavor = sess.target.linker_flavor.lld_flavor();
1248 LinkerFlavor::from_cli(LinkerFlavorCli::Lld(lld_flavor), &sess.target)
1250 // fall back to the value in the target spec
1251 sess.target.linker_flavor
1254 Some((linker, flavor))
1256 (None, None) => None,
1260 // linker and linker flavor specified via command line have precedence over what the target
1261 // specification specifies
1263 sess.opts.cg.linker_flavor.map(|flavor| LinkerFlavor::from_cli(flavor, &sess.target));
1264 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor) {
1268 if let Some(ret) = infer_from(
1270 sess.target.linker.as_deref().map(PathBuf::from),
1271 Some(sess.target.linker_flavor),
1276 bug!("Not enough information provided to determine how to invoke the linker");
1279 /// Returns a pair of boolean indicating whether we should preserve the object and
1280 /// dwarf object files on the filesystem for their debug information. This is often
1281 /// useful with split-dwarf like schemes.
1282 fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1283 // If the objects don't have debuginfo there's nothing to preserve.
1284 if sess.opts.debuginfo == config::DebugInfo::None {
1285 return (false, false);
1288 // If we're only producing artifacts that are archives, no need to preserve
1289 // the objects as they're losslessly contained inside the archives.
1290 if sess.crate_types().iter().all(|&x| x.is_archive()) {
1291 return (false, false);
1294 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1295 // If there is no split debuginfo then do not preserve objects.
1296 (SplitDebuginfo::Off, _) => (false, false),
1297 // If there is packed split debuginfo, then the debuginfo in the objects
1298 // has been packaged and the objects can be deleted.
1299 (SplitDebuginfo::Packed, _) => (false, false),
1300 // If there is unpacked split debuginfo and the current target can not use
1301 // split dwarf, then keep objects.
1302 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1303 // If there is unpacked split debuginfo and the target can use split dwarf, then
1304 // keep the object containing that debuginfo (whether that is an object file or
1305 // dwarf object file depends on the split dwarf kind).
1306 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1307 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1311 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
1312 sess.target_filesearch(PathKind::Native).search_path_dirs()
1315 #[derive(PartialEq)]
1321 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
1322 let lib_args: Vec<_> = all_native_libs
1324 .filter(|l| relevant_lib(sess, l))
1326 let name = lib.name?;
1328 NativeLibKind::Static { bundle: Some(false), .. }
1329 | NativeLibKind::Dylib { .. }
1330 | NativeLibKind::Unspecified => {
1331 let verbatim = lib.verbatim.unwrap_or(false);
1332 if sess.target.is_like_msvc {
1333 Some(format!("{}{}", name, if verbatim { "" } else { ".lib" }))
1334 } else if sess.target.linker_flavor.is_gnu() {
1335 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1337 Some(format!("-l{}", name))
1340 NativeLibKind::Framework { .. } => {
1341 // ld-only syntax, since there are no frameworks in MSVC
1342 Some(format!("-framework {}", name))
1344 // These are included, no need to print them
1345 NativeLibKind::Static { bundle: None | Some(true), .. }
1346 | NativeLibKind::LinkArg
1347 | NativeLibKind::RawDylib => None,
1351 if !lib_args.is_empty() {
1352 sess.emit_note(errors::StaticLibraryNativeArtifacts);
1353 // Prefix for greppability
1354 sess.emit_note(errors::NativeStaticLibs { arguments: lib_args.join(" ") });
1358 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1359 let fs = sess.target_filesearch(PathKind::Native);
1360 let file_path = fs.get_lib_path().join(name);
1361 if file_path.exists() {
1364 // Special directory with objects used only in self-contained linkage mode
1366 let file_path = fs.get_self_contained_lib_path().join(name);
1367 if file_path.exists() {
1371 for search_path in fs.search_paths() {
1372 let file_path = search_path.dir.join(name);
1373 if file_path.exists() {
1383 out_filename: &Path,
1385 ) -> io::Result<Output> {
1386 // When attempting to spawn the linker we run a risk of blowing out the
1387 // size limits for spawning a new process with respect to the arguments
1388 // we pass on the command line.
1390 // Here we attempt to handle errors from the OS saying "your list of
1391 // arguments is too big" by reinvoking the linker again with an `@`-file
1392 // that contains all the arguments. The theory is that this is then
1393 // accepted on all linkers and the linker will read all its options out of
1394 // there instead of looking at the command line.
1395 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1396 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1398 let output = child.wait_with_output();
1399 flush_linked_file(&output, out_filename)?;
1402 Err(ref e) if command_line_too_big(e) => {
1403 info!("command line to linker was too big: {}", e);
1405 Err(e) => return Err(e),
1409 info!("falling back to passing arguments to linker via an @-file");
1410 let mut cmd2 = cmd.clone();
1411 let mut args = String::new();
1412 for arg in cmd2.take_args() {
1414 &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1419 let file = tmpdir.join("linker-arguments");
1420 let bytes = if sess.target.is_like_msvc {
1421 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1422 // start the stream with a UTF-16 BOM
1423 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1424 // encode in little endian
1426 out.push((c >> 8) as u8);
1432 fs::write(&file, &bytes)?;
1433 cmd2.arg(format!("@{}", file.display()));
1434 info!("invoking linker {:?}", cmd2);
1435 let output = cmd2.output();
1436 flush_linked_file(&output, out_filename)?;
1439 #[cfg(not(windows))]
1440 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1445 fn flush_linked_file(
1446 command_output: &io::Result<Output>,
1447 out_filename: &Path,
1448 ) -> io::Result<()> {
1449 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1450 // even long after process exit, causing nasty, non-reproducible output bugs.
1452 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1454 // А full writeup of the original Chrome bug can be found at
1455 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1457 if let &Ok(ref out) = command_output {
1458 if out.status.success() {
1459 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1469 fn command_line_too_big(err: &io::Error) -> bool {
1470 err.raw_os_error() == Some(::libc::E2BIG)
1474 fn command_line_too_big(err: &io::Error) -> bool {
1475 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1476 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1479 #[cfg(not(any(unix, windows)))]
1480 fn command_line_too_big(_: &io::Error) -> bool {
1489 impl<'a> fmt::Display for Escape<'a> {
1490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1491 if self.is_like_msvc {
1492 // This is "documented" at
1493 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1495 // Unfortunately there's not a great specification of the
1496 // syntax I could find online (at least) but some local
1497 // testing showed that this seemed sufficient-ish to catch
1498 // at least a few edge cases.
1500 for c in self.arg.chars() {
1502 '"' => write!(f, "\\{}", c)?,
1503 c => write!(f, "{}", c)?,
1508 // This is documented at https://linux.die.net/man/1/ld, namely:
1510 // > Options in file are separated by whitespace. A whitespace
1511 // > character may be included in an option by surrounding the
1512 // > entire option in either single or double quotes. Any
1513 // > character (including a backslash) may be included by
1514 // > prefixing the character to be included with a backslash.
1516 // We put an argument on each line, so all we need to do is
1517 // ensure the line is interpreted as one whole argument.
1518 for c in self.arg.chars() {
1520 '\\' | ' ' => write!(f, "\\{}", c)?,
1521 c => write!(f, "{}", c)?,
1530 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1531 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1532 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1533 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1534 LinkOutputKind::DynamicPicExe
1536 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1537 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1538 LinkOutputKind::StaticPicExe
1540 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1541 (_, true, _) => LinkOutputKind::StaticDylib,
1542 (_, false, _) => LinkOutputKind::DynamicDylib,
1545 // Adjust the output kind to target capabilities.
1546 let opts = &sess.target;
1547 let pic_exe_supported = opts.position_independent_executables;
1548 let static_pic_exe_supported = opts.static_position_independent_executables;
1549 let static_dylib_supported = opts.crt_static_allows_dylibs;
1551 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1552 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1553 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1558 // Returns true if linker is located within sysroot
1559 fn detect_self_contained_mingw(sess: &Session) -> bool {
1560 let (linker, _) = linker_and_flavor(&sess);
1561 // Assume `-C linker=rust-lld` as self-contained mode
1562 if linker == Path::new("rust-lld") {
1565 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1566 linker.with_extension("exe")
1570 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1571 let full_path = dir.join(&linker_with_extension);
1572 // If linker comes from sysroot assume self-contained mode
1573 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1580 /// Various toolchain components used during linking are used from rustc distribution
1581 /// instead of being found somewhere on the host system.
1582 /// We only provide such support for a very limited number of targets.
1583 fn self_contained(sess: &Session, crate_type: CrateType) -> bool {
1584 if let Some(self_contained) = sess.opts.cg.link_self_contained {
1585 return self_contained;
1588 match sess.target.link_self_contained {
1589 LinkSelfContainedDefault::False => false,
1590 LinkSelfContainedDefault::True => true,
1591 // FIXME: Find a better heuristic for "native musl toolchain is available",
1592 // based on host and linker path, for example.
1593 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1594 LinkSelfContainedDefault::Musl => sess.crt_static(Some(crate_type)),
1595 LinkSelfContainedDefault::Mingw => {
1596 sess.host == sess.target
1597 && sess.target.vendor != "uwp"
1598 && detect_self_contained_mingw(&sess)
1603 /// Add pre-link object files defined by the target spec.
1604 fn add_pre_link_objects(
1605 cmd: &mut dyn Linker,
1607 flavor: LinkerFlavor,
1608 link_output_kind: LinkOutputKind,
1609 self_contained: bool,
1611 // FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1612 // so Fuchsia has to be special-cased.
1613 let opts = &sess.target;
1614 let empty = Default::default();
1615 let objects = if self_contained {
1616 &opts.pre_link_objects_self_contained
1617 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1618 &opts.pre_link_objects
1622 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1623 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1627 /// Add post-link object files defined by the target spec.
1628 fn add_post_link_objects(
1629 cmd: &mut dyn Linker,
1631 link_output_kind: LinkOutputKind,
1632 self_contained: bool,
1634 let objects = if self_contained {
1635 &sess.target.post_link_objects_self_contained
1637 &sess.target.post_link_objects
1639 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1640 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1644 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1645 /// FIXME: Determine where exactly these args need to be inserted.
1646 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1647 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1648 cmd.args(args.iter().map(Deref::deref));
1650 cmd.args(&sess.opts.unstable_opts.pre_link_args);
1653 /// Add a link script embedded in the target, if applicable.
1654 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1655 match (crate_type, &sess.target.link_script) {
1656 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1657 if !sess.target.linker_flavor.is_gnu() {
1658 sess.emit_fatal(errors::LinkScriptUnavailable);
1661 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1663 let path = tmpdir.join(file_name);
1664 if let Err(error) = fs::write(&path, script.as_ref()) {
1665 sess.emit_fatal(errors::LinkScriptWriteFailure { path, error });
1668 cmd.arg("--script");
1675 /// Add arbitrary "user defined" args defined from command line.
1676 /// FIXME: Determine where exactly these args need to be inserted.
1677 fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1678 cmd.args(&sess.opts.cg.link_args);
1681 /// Add arbitrary "late link" args defined by the target spec.
1682 /// FIXME: Determine where exactly these args need to be inserted.
1683 fn add_late_link_args(
1684 cmd: &mut dyn Linker,
1686 flavor: LinkerFlavor,
1687 crate_type: CrateType,
1688 codegen_results: &CodegenResults,
1690 let any_dynamic_crate = crate_type == CrateType::Dylib
1691 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1692 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1694 if any_dynamic_crate {
1695 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1696 cmd.args(args.iter().map(Deref::deref));
1699 if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1700 cmd.args(args.iter().map(Deref::deref));
1703 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1704 cmd.args(args.iter().map(Deref::deref));
1708 /// Add arbitrary "post-link" args defined by the target spec.
1709 /// FIXME: Determine where exactly these args need to be inserted.
1710 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1711 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1712 cmd.args(args.iter().map(Deref::deref));
1716 /// Add a synthetic object file that contains reference to all symbols that we want to expose to
1719 /// Background: we implement rlibs as static library (archives). Linkers treat archives
1720 /// differently from object files: all object files participate in linking, while archives will
1721 /// only participate in linking if they can satisfy at least one undefined reference (version
1722 /// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1723 /// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1724 /// can't keep them either. This causes #47384.
1726 /// To keep them around, we could use `--whole-archive` and equivalents to force rlib to
1727 /// participate in linking like object files, but this proves to be expensive (#93791). Therefore
1728 /// we instead just introduce an undefined reference to them. This could be done by `-u` command
1729 /// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1730 /// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1731 /// from removing them, and this is especially problematic for embedded programming where every
1734 /// This method creates a synthetic object file, which contains undefined references to all symbols
1735 /// that are necessary for the linking. They are only present in symbol table but not actually
1736 /// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1737 /// unused `#[no_mangle]` or `#[used]` can still be discard by GC sections.
1739 /// There's a few internal crates in the standard library (aka libcore and
1740 /// libstd) which actually have a circular dependence upon one another. This
1741 /// currently arises through "weak lang items" where libcore requires things
1742 /// like `rust_begin_unwind` but libstd ends up defining it. To get this
1743 /// circular dependence to work correctly we declare some of these things
1744 /// in this synthetic object.
1745 fn add_linked_symbol_object(
1746 cmd: &mut dyn Linker,
1749 symbols: &[(String, SymbolExportKind)],
1751 if symbols.is_empty() {
1755 let Some(mut file) = super::metadata::create_object_file(sess) else {
1759 // NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1760 // so add an empty section.
1761 if file.format() == object::BinaryFormat::Coff {
1762 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1764 // We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1765 // default mangler in `object` crate.
1766 file.set_mangling(object::write::Mangling::None);
1768 // Add feature flags to the object file. On MSVC this is optional but LLD will complain if
1770 let mut feature = 0;
1772 if file.architecture() == object::Architecture::I386 {
1773 // Indicate that all SEH handlers are registered in .sxdata section.
1774 // We don't have generate any code, so we don't need .sxdata section but LLD still
1775 // expects us to set this bit (see #96498).
1776 // Reference: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
1780 file.add_symbol(object::write::Symbol {
1781 name: "@feat.00".into(),
1784 kind: object::SymbolKind::Data,
1785 scope: object::SymbolScope::Compilation,
1787 section: object::write::SymbolSection::Absolute,
1788 flags: object::SymbolFlags::None,
1792 for (sym, kind) in symbols.iter() {
1793 file.add_symbol(object::write::Symbol {
1794 name: sym.clone().into(),
1798 SymbolExportKind::Text => object::SymbolKind::Text,
1799 SymbolExportKind::Data => object::SymbolKind::Data,
1800 SymbolExportKind::Tls => object::SymbolKind::Tls,
1802 scope: object::SymbolScope::Unknown,
1804 section: object::write::SymbolSection::Undefined,
1805 flags: object::SymbolFlags::None,
1809 let path = tmpdir.join("symbols.o");
1810 let result = std::fs::write(&path, file.write().unwrap());
1811 if let Err(error) = result {
1812 sess.emit_fatal(errors::FailedToWrite { path, error });
1814 cmd.add_object(&path);
1817 /// Add object files containing code from the current crate.
1818 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1819 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1820 cmd.add_object(obj);
1824 /// Add object files for allocator code linked once for the whole crate tree.
1825 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1826 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1827 cmd.add_object(obj);
1831 /// Add object files containing metadata for the current crate.
1832 fn add_local_crate_metadata_objects(
1833 cmd: &mut dyn Linker,
1834 crate_type: CrateType,
1835 codegen_results: &CodegenResults,
1837 // When linking a dynamic library, we put the metadata into a section of the
1838 // executable. This metadata is in a separate object file from the main
1839 // object file, so we link that in here.
1840 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1841 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1843 cmd.add_object(obj);
1848 /// Add sysroot and other globally set directories to the directory search list.
1849 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1850 // The default library location, we need this to find the runtime.
1851 // The location of crates will be determined as needed.
1852 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1853 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1855 // Special directory with libraries used only in self-contained linkage mode
1857 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1858 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1862 /// Add options making relocation sections in the produced ELF files read-only
1863 /// and suppressing lazy binding.
1864 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1865 match sess.opts.unstable_opts.relro_level.unwrap_or(sess.target.relro_level) {
1866 RelroLevel::Full => cmd.full_relro(),
1867 RelroLevel::Partial => cmd.partial_relro(),
1868 RelroLevel::Off => cmd.no_relro(),
1869 RelroLevel::None => {}
1873 /// Add library search paths used at runtime by dynamic linkers.
1875 cmd: &mut dyn Linker,
1877 codegen_results: &CodegenResults,
1878 out_filename: &Path,
1880 // FIXME (#2397): At some point we want to rpath our guesses as to
1881 // where extern libraries might live, based on the
1882 // add_lib_search_paths
1883 if sess.opts.cg.rpath {
1884 let libs = codegen_results
1888 .filter_map(|cnum| {
1889 codegen_results.crate_info.used_crate_source[cnum]
1892 .map(|(path, _)| &**path)
1894 .collect::<Vec<_>>();
1895 let mut rpath_config = RPathConfig {
1897 out_filename: out_filename.to_path_buf(),
1898 has_rpath: sess.target.has_rpath,
1899 is_like_osx: sess.target.is_like_osx,
1900 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
1902 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1906 /// Produce the linker command line containing linker path and arguments.
1908 /// When comments in the function say "order-(in)dependent" they mean order-dependence between
1909 /// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
1910 /// to specific libraries passed after it, and `-o` (output file, order-independent) applies
1911 /// to the linking process as a whole.
1912 /// Order-independent options may still override each other in order-dependent fashion,
1913 /// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
1914 fn linker_with_args<'a>(
1916 flavor: LinkerFlavor,
1918 archive_builder_builder: &dyn ArchiveBuilderBuilder,
1919 crate_type: CrateType,
1921 out_filename: &Path,
1922 codegen_results: &CodegenResults,
1923 ) -> Result<Command, ErrorGuaranteed> {
1924 let self_contained = self_contained(sess, crate_type);
1925 let cmd = &mut *super::linker::get_linker(
1930 &codegen_results.crate_info.target_cpu,
1932 let link_output_kind = link_output_kind(sess, crate_type);
1934 // ------------ Early order-dependent options ------------
1936 // If we're building something like a dynamic library then some platforms
1937 // need to make sure that all symbols are exported correctly from the
1939 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
1940 // at least on some platforms (e.g. windows-gnu).
1944 &codegen_results.crate_info.exported_symbols[&crate_type],
1947 // Can be used for adding custom CRT objects or overriding order-dependent options above.
1948 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
1949 // introduce a target spec option for order-independent linker options and migrate built-in
1951 add_pre_link_args(cmd, sess, flavor);
1953 // ------------ Object code and libraries, order-dependent ------------
1955 // Pre-link CRT objects.
1956 add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained);
1958 add_linked_symbol_object(
1962 &codegen_results.crate_info.linked_symbols[&crate_type],
1965 // Sanitizer libraries.
1966 add_sanitizer_libraries(sess, crate_type, cmd);
1968 // Object code from the current crate.
1969 // Take careful note of the ordering of the arguments we pass to the linker
1970 // here. Linkers will assume that things on the left depend on things to the
1971 // right. Things on the right cannot depend on things on the left. This is
1972 // all formally implemented in terms of resolving symbols (libs on the right
1973 // resolve unknown symbols of libs on the left, but not vice versa).
1975 // For this reason, we have organized the arguments we pass to the linker as
1978 // 1. The local object that LLVM just generated
1979 // 2. Local native libraries
1980 // 3. Upstream rust libraries
1981 // 4. Upstream native libraries
1983 // The rationale behind this ordering is that those items lower down in the
1984 // list can't depend on items higher up in the list. For example nothing can
1985 // depend on what we just generated (e.g., that'd be a circular dependency).
1986 // Upstream rust libraries are not supposed to depend on our local native
1987 // libraries as that would violate the structure of the DAG, in that
1988 // scenario they are required to link to them as well in a shared fashion.
1990 // Note that upstream rust libraries may contain native dependencies as
1991 // well, but they also can't depend on what we just started to add to the
1992 // link line. And finally upstream native libraries can't depend on anything
1993 // in this DAG so far because they can only depend on other native libraries
1994 // and such dependencies are also required to be specified.
1995 add_local_crate_regular_objects(cmd, codegen_results);
1996 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1997 add_local_crate_allocator_objects(cmd, codegen_results);
1999 // Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2000 // at the point at which they are specified on the command line.
2001 // Must be passed before any (dynamic) libraries to have effect on them.
2002 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2003 // so it will ignore unreferenced ELF sections from relocatable objects.
2004 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2005 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2006 // and move this option back to the top.
2007 cmd.add_as_needed();
2009 // Local native libraries of all kinds.
2011 // If `-Zlink-native-libraries=false` is set, then the assumption is that an
2012 // external build system already has the native dependencies defined, and it
2013 // will provide them to the linker itself.
2014 if sess.opts.unstable_opts.link_native_libraries {
2015 add_local_native_libraries(cmd, sess, codegen_results);
2018 // Upstream rust libraries and their (possibly bundled) static native libraries.
2019 add_upstream_rust_crates(
2022 archive_builder_builder,
2028 // Dynamic native libraries from upstream crates.
2030 // FIXME: Merge this to `add_upstream_rust_crates` so that all native libraries are linked
2031 // together with their respective upstream crates, and in their originally specified order.
2032 // This may be slightly breaking due to our use of `--as-needed` and needs a crater run.
2033 if sess.opts.unstable_opts.link_native_libraries {
2034 add_upstream_native_libraries(cmd, sess, codegen_results);
2037 // Link with the import library generated for any raw-dylib functions.
2038 for (raw_dylib_name, raw_dylib_imports) in
2039 collate_raw_dylibs(sess, codegen_results.crate_info.used_libraries.iter())?
2041 cmd.add_object(&archive_builder_builder.create_dll_import_lib(
2049 // As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2050 // they are used within inlined functions or instantiated generic functions. We do this *after*
2051 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2053 let (_, dependency_linkage) = codegen_results
2057 .find(|(ty, _)| *ty == crate_type)
2058 .expect("failed to find crate type in dependency format list");
2059 let native_libraries_from_nonstatics = codegen_results
2063 .filter_map(|(cnum, libraries)| {
2064 (dependency_linkage[cnum.as_usize() - 1] != Linkage::Static).then(|| libraries)
2067 for (raw_dylib_name, raw_dylib_imports) in
2068 collate_raw_dylibs(sess, native_libraries_from_nonstatics)?
2070 cmd.add_object(&archive_builder_builder.create_dll_import_lib(
2079 // Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2080 // command line shorter, reset it to default here before adding more libraries.
2081 cmd.reset_per_library_state();
2083 // FIXME: Built-in target specs occasionally use this for linking system libraries,
2084 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2085 // and remove the option.
2086 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2088 // ------------ Arbitrary order-independent options ------------
2090 // Add order-independent options determined by rustc from its compiler options,
2091 // target properties and source code.
2092 add_order_independent_options(
2104 // Can be used for arbitrary order-independent options.
2105 // In practice may also be occasionally used for linking native libraries.
2106 // Passed after compiler-generated options to support manual overriding when necessary.
2107 add_user_defined_link_args(cmd, sess);
2109 // ------------ Object code and libraries, order-dependent ------------
2111 // Post-link CRT objects.
2112 add_post_link_objects(cmd, sess, link_output_kind, self_contained);
2114 // ------------ Late order-dependent options ------------
2116 // Doesn't really make sense.
2117 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2118 // introduce a target spec option for order-independent linker options, migrate built-in specs
2119 // to it and remove the option.
2120 add_post_link_args(cmd, sess, flavor);
2125 fn add_order_independent_options(
2126 cmd: &mut dyn Linker,
2128 link_output_kind: LinkOutputKind,
2129 self_contained: bool,
2130 flavor: LinkerFlavor,
2131 crate_type: CrateType,
2132 codegen_results: &CodegenResults,
2133 out_filename: &Path,
2136 add_gcc_ld_path(cmd, sess, flavor);
2138 add_apple_sdk(cmd, sess, flavor);
2140 add_link_script(cmd, sess, tmpdir, crate_type);
2142 if sess.target.os == "fuchsia"
2143 && crate_type == CrateType::Executable
2144 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2146 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2151 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
2154 if sess.target.eh_frame_header {
2155 cmd.add_eh_frame_header();
2158 // Make the binary compatible with data execution prevention schemes.
2162 cmd.no_crt_objects();
2165 if sess.target.os == "emscripten" {
2167 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
2168 "DISABLE_EXCEPTION_CATCHING=1"
2170 "DISABLE_EXCEPTION_CATCHING=0"
2174 if flavor == LinkerFlavor::Ptx {
2175 // Provide the linker with fallback to internal `target-cpu`.
2176 cmd.arg("--fallback-arch");
2177 cmd.arg(&codegen_results.crate_info.target_cpu);
2178 } else if flavor == LinkerFlavor::Bpf {
2180 cmd.arg(&codegen_results.crate_info.target_cpu);
2181 cmd.arg("--cpu-features");
2182 cmd.arg(match &sess.opts.cg.target_feature {
2183 feat if !feat.is_empty() => feat.as_ref(),
2184 _ => sess.target.options.features.as_ref(),
2188 cmd.linker_plugin_lto();
2190 add_library_search_dirs(cmd, sess, self_contained);
2192 cmd.output_filename(out_filename);
2194 if crate_type == CrateType::Executable && sess.target.is_like_windows {
2195 if let Some(ref s) = codegen_results.crate_info.windows_subsystem {
2200 // Try to strip as much out of the generated object by removing unused
2201 // sections if possible. See more comments in linker.rs
2202 if !sess.link_dead_code() {
2203 // If PGO is enabled sometimes gc_sections will remove the profile data section
2204 // as it appears to be unused. This can then cause the PGO profile file to lose
2205 // some functions. If we are generating a profile we shouldn't strip those metadata
2206 // sections to ensure we have all the data for PGO.
2208 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2209 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2211 cmd.gc_sections(keep_metadata);
2213 cmd.no_gc_sections();
2217 cmd.set_output_kind(link_output_kind, out_filename);
2219 add_relro_args(cmd, sess);
2221 // Pass optimization flags down to the linker.
2224 // Gather the set of NatVis files, if any, and write them out to a temp directory.
2225 let natvis_visualizers = collect_natvis_visualizers(
2228 &codegen_results.crate_info.local_crate_name,
2229 &codegen_results.crate_info.natvis_debugger_visualizers,
2232 // Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2233 cmd.debuginfo(strip_value(sess), &natvis_visualizers);
2235 // We want to prevent the compiler from accidentally leaking in any system libraries,
2236 // so by default we tell linkers not to link to any default libraries.
2237 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2238 cmd.no_default_libraries();
2241 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2245 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2246 cmd.control_flow_guard();
2249 add_rpath_args(cmd, sess, codegen_results, out_filename);
2252 // Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2253 fn collect_natvis_visualizers(
2256 crate_name: &Symbol,
2257 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2259 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2261 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2262 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2264 match fs::write(&visualizer_out_file, &visualizer.src) {
2266 visualizer_paths.push(visualizer_out_file);
2269 sess.emit_warning(errors::UnableToWriteDebuggerVisualizer {
2270 path: visualizer_out_file,
2279 /// # Native library linking
2281 /// User-supplied library search paths (-L on the command line). These are the same paths used to
2282 /// find Rust crates, so some of them may have been added already by the previous crate linking
2283 /// code. This only allows them to be found at compile time so it is still entirely up to outside
2284 /// forces to make sure that library can be found at runtime.
2286 /// Also note that the native libraries linked here are only the ones located in the current crate.
2287 /// Upstream crates with native library dependencies may have their native library pulled in above.
2288 fn add_local_native_libraries(
2289 cmd: &mut dyn Linker,
2291 codegen_results: &CodegenResults,
2293 let filesearch = sess.target_filesearch(PathKind::All);
2294 for search_path in filesearch.search_paths() {
2295 match search_path.kind {
2296 PathKind::Framework => {
2297 cmd.framework_path(&search_path.dir);
2300 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
2306 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
2308 let search_path = OnceCell::new();
2309 let mut last = (None, NativeLibKind::Unspecified, None);
2310 for lib in relevant_libs {
2311 let Some(name) = lib.name else {
2314 let name = name.as_str();
2316 // Skip if this library is the same as the last.
2317 last = if (lib.name, lib.kind, lib.verbatim) == last {
2320 (lib.name, lib.kind, lib.verbatim)
2323 let verbatim = lib.verbatim.unwrap_or(false);
2325 NativeLibKind::Dylib { as_needed } => {
2326 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2328 NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
2329 NativeLibKind::Framework { as_needed } => {
2330 cmd.link_framework(name, as_needed.unwrap_or(true))
2332 NativeLibKind::Static { whole_archive, bundle, .. } => {
2333 if whole_archive == Some(true)
2334 // Backward compatibility case: this can be a rlib (so `+whole-archive` cannot
2335 // be added explicitly if necessary, see the error in `fn link_rlib`) compiled
2336 // as an executable due to `--test`. Use whole-archive implicitly, like before
2337 // the introduction of native lib modifiers.
2338 || (whole_archive == None && bundle != Some(false) && sess.opts.test)
2340 cmd.link_whole_staticlib(
2343 &search_path.get_or_init(|| archive_search_paths(sess)),
2346 cmd.link_staticlib(name, verbatim)
2349 NativeLibKind::RawDylib => {
2350 // Ignore RawDylib here, they are handled separately in linker_with_args().
2352 NativeLibKind::LinkArg => {
2359 /// # Linking Rust crates and their non-bundled static libraries
2361 /// Rust crates are not considered at all when creating an rlib output. All dependencies will be
2362 /// linked when producing the final output (instead of the intermediate rlib version).
2363 fn add_upstream_rust_crates<'a>(
2364 cmd: &mut dyn Linker,
2366 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2367 codegen_results: &CodegenResults,
2368 crate_type: CrateType,
2371 // All of the heavy lifting has previously been accomplished by the
2372 // dependency_format module of the compiler. This is just crawling the
2373 // output of that module, adding crates as necessary.
2375 // Linking to a rlib involves just passing it to the linker (the linker
2376 // will slurp up the object files inside), and linking to a dynamic library
2377 // involves just passing the right -l flag.
2379 let (_, data) = codegen_results
2383 .find(|(ty, _)| *ty == crate_type)
2384 .expect("failed to find crate type in dependency format list");
2386 // Invoke get_used_crates to ensure that we get a topological sorting of
2388 let deps = &codegen_results.crate_info.used_crates;
2390 let mut compiler_builtins = None;
2391 let search_path = OnceCell::new();
2393 for &cnum in deps.iter() {
2394 // We may not pass all crates through to the linker. Some crates may
2395 // appear statically in an existing dylib, meaning we'll pick up all the
2396 // symbols from the dylib.
2397 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2398 match data[cnum.as_usize() - 1] {
2399 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
2403 archive_builder_builder,
2407 &Default::default(),
2410 // compiler-builtins are always placed last to ensure that they're
2411 // linked correctly.
2412 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
2413 assert!(compiler_builtins.is_none());
2414 compiler_builtins = Some(cnum);
2416 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
2417 Linkage::Static => {
2418 let bundled_libs = if sess.opts.unstable_opts.packed_bundled_libs {
2419 codegen_results.crate_info.native_libraries[&cnum]
2421 .filter_map(|lib| lib.filename)
2422 .collect::<FxHashSet<_>>()
2429 archive_builder_builder,
2436 // Link static native libs with "-bundle" modifier only if the crate they originate from
2437 // is being linked statically to the current crate. If it's linked dynamically
2438 // or is an rlib already included via some other dylib crate, the symbols from
2439 // native libs will have already been included in that dylib.
2441 // If `-Zlink-native-libraries=false` is set, then the assumption is that an
2442 // external build system already has the native dependencies defined, and it
2443 // will provide them to the linker itself.
2444 if sess.opts.unstable_opts.link_native_libraries {
2445 if sess.opts.unstable_opts.packed_bundled_libs {
2446 // If rlib contains native libs as archives, unpack them to tmpdir.
2447 let rlib = &src.rlib.as_ref().unwrap().0;
2448 archive_builder_builder
2449 .extract_bundled_libs(rlib, tmpdir, &bundled_libs)
2450 .unwrap_or_else(|e| sess.emit_fatal(e));
2453 let mut last = (None, NativeLibKind::Unspecified, None);
2454 for lib in &codegen_results.crate_info.native_libraries[&cnum] {
2455 let Some(name) = lib.name else {
2458 let name = name.as_str();
2459 if !relevant_lib(sess, lib) {
2463 // Skip if this library is the same as the last.
2464 last = if (lib.name, lib.kind, lib.verbatim) == last {
2467 (lib.name, lib.kind, lib.verbatim)
2471 NativeLibKind::Static {
2472 bundle: Some(false),
2473 whole_archive: Some(true),
2475 cmd.link_whole_staticlib(
2477 lib.verbatim.unwrap_or(false),
2478 search_path.get_or_init(|| archive_search_paths(sess)),
2481 NativeLibKind::Static {
2482 bundle: Some(false),
2483 whole_archive: Some(false) | None,
2485 // HACK/FIXME: Fixup a circular dependency between libgcc and libc
2486 // with glibc. This logic should be moved to the libc crate.
2487 if sess.target.os == "linux"
2488 && sess.target.env == "gnu"
2491 cmd.link_staticlib("gcc", false);
2493 cmd.link_staticlib(name, lib.verbatim.unwrap_or(false));
2495 NativeLibKind::LinkArg => {
2498 NativeLibKind::Dylib { .. }
2499 | NativeLibKind::Framework { .. }
2500 | NativeLibKind::Unspecified
2501 | NativeLibKind::RawDylib => {}
2502 NativeLibKind::Static { bundle: Some(true) | None, whole_archive } => {
2503 if sess.opts.unstable_opts.packed_bundled_libs {
2504 // If rlib contains native libs as archives, they are unpacked to tmpdir.
2505 let path = tmpdir.join(lib.filename.unwrap().as_str());
2506 if whole_archive == Some(true) {
2507 cmd.link_whole_rlib(&path);
2509 cmd.link_rlib(&path);
2517 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
2521 // compiler-builtins are always placed last to ensure that they're
2522 // linked correctly.
2523 // We must always link the `compiler_builtins` crate statically. Even if it
2524 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
2526 if let Some(cnum) = compiler_builtins {
2530 archive_builder_builder,
2534 &Default::default(),
2538 // Converts a library file-stem into a cc -l argument
2539 fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
2540 if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
2543 // Adds the static "rlib" versions of all crates to the command line.
2544 // There's a bit of magic which happens here specifically related to LTO,
2545 // namely that we remove upstream object files.
2547 // When performing LTO, almost(*) all of the bytecode from the upstream
2548 // libraries has already been included in our object file output. As a
2549 // result we need to remove the object files in the upstream libraries so
2550 // the linker doesn't try to include them twice (or whine about duplicate
2551 // symbols). We must continue to include the rest of the rlib, however, as
2552 // it may contain static native libraries which must be linked in.
2554 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
2555 // their bytecode wasn't included. The object files in those libraries must
2556 // still be passed to the linker.
2558 // Note, however, that if we're not doing LTO we can just pass the rlib
2559 // blindly to the linker (fast) because it's fine if it's not actually
2560 // included as we're at the end of the dependency chain.
2561 fn add_static_crate<'a>(
2562 cmd: &mut dyn Linker,
2564 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2565 codegen_results: &CodegenResults,
2568 bundled_lib_file_names: &FxHashSet<Symbol>,
2570 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2571 let cratepath = &src.rlib.as_ref().unwrap().0;
2573 let mut link_upstream = |path: &Path| {
2574 cmd.link_rlib(&fix_windows_verbatim_for_gcc(path));
2577 // See the comment above in `link_staticlib` and `link_rlib` for why if
2578 // there's a static library that's not relevant we skip all object
2580 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
2581 let skip_native = native_libs.iter().any(|lib| {
2582 matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
2583 && !relevant_lib(sess, lib)
2586 if (!are_upstream_rust_objects_already_included(sess)
2587 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
2590 link_upstream(cratepath);
2594 let dst = tmpdir.join(cratepath.file_name().unwrap());
2595 let name = cratepath.file_name().unwrap().to_str().unwrap();
2596 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2597 let bundled_lib_file_names = bundled_lib_file_names.clone();
2599 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2600 let canonical_name = name.replace('-', "_");
2601 let upstream_rust_objects_already_included =
2602 are_upstream_rust_objects_already_included(sess);
2603 let is_builtins = sess.target.no_builtins
2604 || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2606 let mut archive = archive_builder_builder.new_archive_builder(sess);
2607 if let Err(error) = archive.add_archive(
2610 if f == METADATA_FILENAME {
2614 let canonical = f.replace('-', "_");
2616 let is_rust_object =
2617 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2619 // If we've been requested to skip all native object files
2620 // (those not generated by the rust compiler) then we can skip
2621 // this file. See above for why we may want to do this.
2622 let skip_because_cfg_say_so = skip_native && !is_rust_object;
2624 // If we're performing LTO and this is a rust-generated object
2625 // file, then we don't need the object file as it's part of the
2626 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2627 // though, so we let that object file slide.
2628 let skip_because_lto =
2629 upstream_rust_objects_already_included && is_rust_object && is_builtins;
2631 // We skip native libraries because:
2632 // 1. This native libraries won't be used from the generated rlib,
2633 // so we can throw them away to avoid the copying work.
2634 // 2. We can't allow it to be a single remaining entry in archive
2635 // as some linkers may complain on that.
2636 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
2640 if skip_because_cfg_say_so || skip_because_lto {
2647 sess.emit_fatal(errors::RlibArchiveBuildFailure { error });
2649 if archive.build(&dst) {
2650 link_upstream(&dst);
2655 // Same thing as above, but for dynamic crates instead of static crates.
2656 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2657 // Just need to tell the linker about where the library lives and
2659 let parent = cratepath.parent();
2660 if let Some(dir) = parent {
2661 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2663 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2664 cmd.link_rust_dylib(
2665 &unlib(&sess.target, filestem),
2666 parent.unwrap_or_else(|| Path::new("")),
2671 /// Link in all of our upstream crates' native dependencies. Remember that all of these upstream
2672 /// native dependencies are all non-static dependencies. We've got two cases then:
2674 /// 1. The upstream crate is an rlib. In this case we *must* link in the native dependency because
2675 /// the rlib is just an archive.
2677 /// 2. The upstream crate is a dylib. In order to use the dylib, we have to have the dependency
2678 /// present on the system somewhere. Thus, we don't gain a whole lot from not linking in the
2679 /// dynamic dependency to this crate as well.
2681 /// The use case for this is a little subtle. In theory the native dependencies of a crate are
2682 /// purely an implementation detail of the crate itself, but the problem arises with generic and
2683 /// inlined functions. If a generic function calls a native function, then the generic function
2684 /// must be instantiated in the target crate, meaning that the native symbol must also be resolved
2685 /// in the target crate.
2686 fn add_upstream_native_libraries(
2687 cmd: &mut dyn Linker,
2689 codegen_results: &CodegenResults,
2691 let mut last = (None, NativeLibKind::Unspecified, None);
2692 for &cnum in &codegen_results.crate_info.used_crates {
2693 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2694 let Some(name) = lib.name else {
2697 let name = name.as_str();
2698 if !relevant_lib(sess, &lib) {
2702 // Skip if this library is the same as the last.
2703 last = if (lib.name, lib.kind, lib.verbatim) == last {
2706 (lib.name, lib.kind, lib.verbatim)
2709 let verbatim = lib.verbatim.unwrap_or(false);
2711 NativeLibKind::Dylib { as_needed } => {
2712 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2714 NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
2715 NativeLibKind::Framework { as_needed } => {
2716 cmd.link_framework(name, as_needed.unwrap_or(true))
2718 // ignore static native libraries here as we've
2719 // already included them in add_local_native_libraries and
2720 // add_upstream_rust_crates
2721 NativeLibKind::Static { .. } => {}
2722 NativeLibKind::RawDylib | NativeLibKind::LinkArg => {}
2728 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2730 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, CRATE_NODE_ID, None),
2735 pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2737 config::Lto::Fat => true,
2738 config::Lto::Thin => {
2739 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2740 // any upstream object files have not been copied yet.
2741 !sess.opts.cg.linker_plugin_lto.enabled()
2743 config::Lto::No | config::Lto::ThinLocal => false,
2747 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2748 let arch = &sess.target.arch;
2749 let os = &sess.target.os;
2750 let llvm_target = &sess.target.llvm_target;
2751 if sess.target.vendor != "apple"
2752 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "macos")
2753 || !matches!(flavor, LinkerFlavor::Darwin(..))
2758 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
2762 let sdk_name = match (arch.as_ref(), os.as_ref()) {
2763 ("aarch64", "tvos") => "appletvos",
2764 ("x86_64", "tvos") => "appletvsimulator",
2765 ("arm", "ios") => "iphoneos",
2766 ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2767 ("aarch64", "ios") if llvm_target.ends_with("-simulator") => "iphonesimulator",
2768 ("aarch64", "ios") => "iphoneos",
2769 ("x86", "ios") => "iphonesimulator",
2770 ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2771 ("x86_64", "ios") => "iphonesimulator",
2772 ("x86_64", "watchos") => "watchsimulator",
2773 ("arm64_32", "watchos") => "watchos",
2774 ("aarch64", "watchos") if llvm_target.ends_with("-simulator") => "watchsimulator",
2775 ("aarch64", "watchos") => "watchos",
2776 ("arm", "watchos") => "watchos",
2777 (_, "macos") => "macosx",
2779 sess.emit_err(errors::UnsupportedArch { arch, os });
2783 let sdk_root = match get_apple_sdk_root(sdk_name) {
2792 LinkerFlavor::Darwin(Cc::Yes, _) => {
2793 cmd.args(&["-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2795 LinkerFlavor::Darwin(Cc::No, _) => {
2796 cmd.args(&["-syslibroot", &sdk_root]);
2798 _ => unreachable!(),
2802 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, errors::AppleSdkRootError<'_>> {
2803 // Following what clang does
2804 // (https://github.com/llvm/llvm-project/blob/
2805 // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2806 // to allow the SDK path to be set. (For clang, xcrun sets
2807 // SDKROOT; for rustc, the user or build system can set it, or we
2808 // can fall back to checking for xcrun on PATH.)
2809 if let Ok(sdkroot) = env::var("SDKROOT") {
2810 let p = Path::new(&sdkroot);
2812 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2814 if sdkroot.contains("TVSimulator.platform")
2815 || sdkroot.contains("MacOSX.platform") => {}
2817 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2819 if sdkroot.contains("iPhoneSimulator.platform")
2820 || sdkroot.contains("MacOSX.platform") => {}
2822 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2825 if sdkroot.contains("iPhoneOS.platform")
2826 || sdkroot.contains("iPhoneSimulator.platform") => {}
2828 if sdkroot.contains("WatchSimulator.platform")
2829 || sdkroot.contains("MacOSX.platform") => {}
2831 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2832 // Ignore `SDKROOT` if it's not a valid path.
2833 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2834 _ => return Ok(sdkroot),
2838 Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2840 if output.status.success() {
2841 Ok(String::from_utf8(output.stdout).unwrap())
2843 let error = String::from_utf8(output.stderr);
2844 let error = format!("process exit with error: {}", error.unwrap());
2845 Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2851 Ok(output) => Ok(output.trim().to_string()),
2852 Err(error) => Err(errors::AppleSdkRootError::SdkPath { sdk_name, error }),
2856 fn add_gcc_ld_path(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2857 if let Some(ld_impl) = sess.opts.unstable_opts.gcc_ld {
2858 if let LinkerFlavor::Gnu(Cc::Yes, _)
2859 | LinkerFlavor::Darwin(Cc::Yes, _)
2860 | LinkerFlavor::WasmLld(Cc::Yes) = flavor
2864 // Implement the "self-contained" part of -Zgcc-ld
2865 // by adding rustc distribution directories to the tool search path.
2866 for path in sess.get_tools_search_paths(false) {
2868 let mut arg = OsString::from("-B");
2869 arg.push(path.join("gcc-ld"));
2873 // Implement the "linker flavor" part of -Zgcc-ld
2874 // by asking cc to use some kind of lld.
2875 cmd.arg("-fuse-ld=lld");
2876 if !flavor.is_gnu() {
2877 // Tell clang to use a non-default LLD flavor.
2878 // Gcc doesn't understand the target option, but we currently assume
2879 // that gcc is not used for Apple and Wasm targets (#97402).
2880 cmd.arg(format!("--target={}", sess.target.llvm_target));
2885 sess.emit_fatal(errors::OptionGccOnly);