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