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