rustc_codegen_ssa/back/
link.rs

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