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