rustc_codegen_ssa/back/
link.rs

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