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