rustc_codegen_ssa/back/
link.rs

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