rustc_codegen_ssa/back/
link.rs

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