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