]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/link.rs
use <[u8]>::escape_ascii instead of core::ascii::escape_default
[rust.git] / compiler / rustc_codegen_ssa / src / back / link.rs
1 use rustc_arena::TypedArena;
2 use rustc_ast::CRATE_NODE_ID;
3 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
4 use rustc_data_structures::memmap::Mmap;
5 use rustc_data_structures::temp_dir::MaybeTempDir;
6 use rustc_errors::{ErrorGuaranteed, Handler};
7 use rustc_fs_util::fix_windows_verbatim_for_gcc;
8 use rustc_hir::def_id::CrateNum;
9 use rustc_metadata::fs::{emit_metadata, METADATA_FILENAME};
10 use rustc_middle::middle::dependency_format::Linkage;
11 use rustc_middle::middle::exported_symbols::SymbolExportKind;
12 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, LdImpl, Strip};
13 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SplitDwarfKind};
14 use rustc_session::cstore::DllImport;
15 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
16 use rustc_session::search_paths::PathKind;
17 use rustc_session::utils::NativeLibKind;
18 /// For all the linkers we support, and information they might
19 /// need out of the shared crate context before we get rid of it.
20 use rustc_session::{filesearch, Session};
21 use rustc_span::symbol::Symbol;
22 use rustc_span::DebuggerVisualizerFile;
23 use rustc_target::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
24 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor, SplitDebuginfo};
25 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, SanitizerSet, Target};
26
27 use super::archive::{find_library, ArchiveBuilder, ArchiveBuilderBuilder};
28 use super::command::Command;
29 use super::linker::{self, Linker};
30 use super::metadata::{create_rmeta_file, MetadataPosition};
31 use super::rpath::{self, RPathConfig};
32 use crate::{looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib};
33
34 use cc::windows_registry;
35 use regex::Regex;
36 use tempfile::Builder as TempFileBuilder;
37
38 use std::borrow::Borrow;
39 use std::cell::OnceCell;
40 use std::collections::BTreeSet;
41 use std::ffi::OsString;
42 use std::fs::{File, OpenOptions};
43 use std::io::{BufWriter, Write};
44 use std::ops::Deref;
45 use std::path::{Path, PathBuf};
46 use std::process::{ExitStatus, Output, Stdio};
47 use std::{env, fmt, fs, io, mem, str};
48
49 pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
50     if let Err(e) = fs::remove_file(path) {
51         if e.kind() != io::ErrorKind::NotFound {
52             diag_handler.err(&format!("failed to remove {}: {}", path.display(), e));
53         }
54     }
55 }
56
57 /// Performs the linkage portion of the compilation phase. This will generate all
58 /// of the requested outputs for this compilation session.
59 pub fn link_binary<'a>(
60     sess: &'a Session,
61     archive_builder_builder: &dyn ArchiveBuilderBuilder,
62     codegen_results: &CodegenResults,
63     outputs: &OutputFilenames,
64 ) -> Result<(), ErrorGuaranteed> {
65     let _timer = sess.timer("link_binary");
66     let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
67     for &crate_type in sess.crate_types().iter() {
68         // Ignore executable crates if we have -Z no-codegen, as they will error.
69         if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
70             && !output_metadata
71             && crate_type == CrateType::Executable
72         {
73             continue;
74         }
75
76         if invalid_output_for_target(sess, crate_type) {
77             bug!(
78                 "invalid output type `{:?}` for target os `{}`",
79                 crate_type,
80                 sess.opts.target_triple
81             );
82         }
83
84         sess.time("link_binary_check_files_are_writeable", || {
85             for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
86                 check_file_is_writeable(obj, sess);
87             }
88         });
89
90         if outputs.outputs.should_link() {
91             let tmpdir = TempFileBuilder::new()
92                 .prefix("rustc")
93                 .tempdir()
94                 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
95             let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
96             let out_filename = out_filename(
97                 sess,
98                 crate_type,
99                 outputs,
100                 codegen_results.crate_info.local_crate_name.as_str(),
101             );
102             match crate_type {
103                 CrateType::Rlib => {
104                     let _timer = sess.timer("link_rlib");
105                     info!("preparing rlib to {:?}", out_filename);
106                     link_rlib(
107                         sess,
108                         archive_builder_builder,
109                         codegen_results,
110                         RlibFlavor::Normal,
111                         &path,
112                     )?
113                     .build(&out_filename);
114                 }
115                 CrateType::Staticlib => {
116                     link_staticlib(
117                         sess,
118                         archive_builder_builder,
119                         codegen_results,
120                         &out_filename,
121                         &path,
122                     )?;
123                 }
124                 _ => {
125                     link_natively(
126                         sess,
127                         archive_builder_builder,
128                         crate_type,
129                         &out_filename,
130                         codegen_results,
131                         path.as_ref(),
132                     )?;
133                 }
134             }
135             if sess.opts.json_artifact_notifications {
136                 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
137             }
138
139             if sess.prof.enabled() {
140                 if let Some(artifact_name) = out_filename.file_name() {
141                     // Record size for self-profiling
142                     let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
143
144                     sess.prof.artifact_size(
145                         "linked_artifact",
146                         artifact_name.to_string_lossy(),
147                         file_size,
148                     );
149                 }
150             }
151         }
152     }
153
154     // Remove the temporary object file and metadata if we aren't saving temps.
155     sess.time("link_binary_remove_temps", || {
156         // If the user requests that temporaries are saved, don't delete any.
157         if sess.opts.cg.save_temps {
158             return;
159         }
160
161         let maybe_remove_temps_from_module =
162             |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
163                 if !preserve_objects {
164                     if let Some(ref obj) = module.object {
165                         ensure_removed(sess.diagnostic(), obj);
166                     }
167                 }
168
169                 if !preserve_dwarf_objects {
170                     if let Some(ref dwo_obj) = module.dwarf_object {
171                         ensure_removed(sess.diagnostic(), dwo_obj);
172                     }
173                 }
174             };
175
176         let remove_temps_from_module =
177             |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
178
179         // Otherwise, always remove the metadata and allocator module temporaries.
180         if let Some(ref metadata_module) = codegen_results.metadata_module {
181             remove_temps_from_module(metadata_module);
182         }
183
184         if let Some(ref allocator_module) = codegen_results.allocator_module {
185             remove_temps_from_module(allocator_module);
186         }
187
188         // If no requested outputs require linking, then the object temporaries should
189         // be kept.
190         if !sess.opts.output_types.should_link() {
191             return;
192         }
193
194         // Potentially keep objects for their debuginfo.
195         let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
196         debug!(?preserve_objects, ?preserve_dwarf_objects);
197
198         for module in &codegen_results.modules {
199             maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
200         }
201     });
202
203     Ok(())
204 }
205
206 pub fn each_linked_rlib(
207     info: &CrateInfo,
208     f: &mut dyn FnMut(CrateNum, &Path),
209 ) -> Result<(), String> {
210     let crates = info.used_crates.iter();
211     let mut fmts = None;
212     for (ty, list) in info.dependency_formats.iter() {
213         match ty {
214             CrateType::Executable
215             | CrateType::Staticlib
216             | CrateType::Cdylib
217             | CrateType::ProcMacro => {
218                 fmts = Some(list);
219                 break;
220             }
221             _ => {}
222         }
223     }
224     let Some(fmts) = fmts else {
225         return Err("could not find formats for rlibs".to_string());
226     };
227     for &cnum in crates {
228         match fmts.get(cnum.as_usize() - 1) {
229             Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
230             Some(_) => {}
231             None => return Err("could not find formats for rlibs".to_string()),
232         }
233         let name = info.crate_name[&cnum];
234         let used_crate_source = &info.used_crate_source[&cnum];
235         if let Some((path, _)) = &used_crate_source.rlib {
236             f(cnum, &path);
237         } else {
238             if used_crate_source.rmeta.is_some() {
239                 return Err(format!(
240                     "could not find rlib for: `{}`, found rmeta (metadata) file",
241                     name
242                 ));
243             } else {
244                 return Err(format!("could not find rlib for: `{}`", name));
245             }
246         }
247     }
248     Ok(())
249 }
250
251 /// Create an 'rlib'.
252 ///
253 /// An rlib in its current incarnation is essentially a renamed .a file. The rlib primarily contains
254 /// the object file of the crate, but it also contains all of the object files from native
255 /// libraries. This is done by unzipping native libraries and inserting all of the contents into
256 /// this archive.
257 fn link_rlib<'a>(
258     sess: &'a Session,
259     archive_builder_builder: &dyn ArchiveBuilderBuilder,
260     codegen_results: &CodegenResults,
261     flavor: RlibFlavor,
262     tmpdir: &MaybeTempDir,
263 ) -> Result<Box<dyn ArchiveBuilder<'a> + 'a>, ErrorGuaranteed> {
264     let lib_search_paths = archive_search_paths(sess);
265
266     let mut ab = archive_builder_builder.new_archive_builder(sess);
267
268     let trailing_metadata = match flavor {
269         RlibFlavor::Normal => {
270             let (metadata, metadata_position) =
271                 create_rmeta_file(sess, codegen_results.metadata.raw_data());
272             let metadata = emit_metadata(sess, &metadata, tmpdir);
273             match metadata_position {
274                 MetadataPosition::First => {
275                     // Most of the time metadata in rlib files is wrapped in a "dummy" object
276                     // file for the target platform so the rlib can be processed entirely by
277                     // normal linkers for the platform. Sometimes this is not possible however.
278                     // If it is possible however, placing the metadata object first improves
279                     // performance of getting metadata from rlibs.
280                     ab.add_file(&metadata);
281                     None
282                 }
283                 MetadataPosition::Last => Some(metadata),
284             }
285         }
286
287         RlibFlavor::StaticlibBase => None,
288     };
289
290     for m in &codegen_results.modules {
291         if let Some(obj) = m.object.as_ref() {
292             ab.add_file(obj);
293         }
294
295         if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
296             ab.add_file(dwarf_obj);
297         }
298     }
299
300     match flavor {
301         RlibFlavor::Normal => {}
302         RlibFlavor::StaticlibBase => {
303             let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
304             if let Some(obj) = obj {
305                 ab.add_file(obj);
306             }
307         }
308     }
309
310     // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
311     // we may not be configured to actually include a static library if we're
312     // adding it here. That's because later when we consume this rlib we'll
313     // decide whether we actually needed the static library or not.
314     //
315     // To do this "correctly" we'd need to keep track of which libraries added
316     // which object files to the archive. We don't do that here, however. The
317     // #[link(cfg(..))] feature is unstable, though, and only intended to get
318     // liblibc working. In that sense the check below just indicates that if
319     // there are any libraries we want to omit object files for at link time we
320     // just exclude all custom object files.
321     //
322     // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
323     // feature then we'll need to figure out how to record what objects were
324     // loaded from the libraries found here and then encode that into the
325     // metadata of the rlib we're generating somehow.
326     for lib in codegen_results.crate_info.used_libraries.iter() {
327         match lib.kind {
328             NativeLibKind::Static { bundle: None | Some(true), whole_archive: Some(true) }
329                 if flavor == RlibFlavor::Normal =>
330             {
331                 // Don't allow mixing +bundle with +whole_archive since an rlib may contain
332                 // multiple native libs, some of which are +whole-archive and some of which are
333                 // -whole-archive and it isn't clear how we can currently handle such a
334                 // situation correctly.
335                 // See https://github.com/rust-lang/rust/issues/88085#issuecomment-901050897
336                 sess.err(
337                     "the linking modifiers `+bundle` and `+whole-archive` are not compatible \
338                         with each other when generating rlibs",
339                 );
340             }
341             NativeLibKind::Static { bundle: None | Some(true), .. } => {}
342             NativeLibKind::Static { bundle: Some(false), .. }
343             | NativeLibKind::Dylib { .. }
344             | NativeLibKind::Framework { .. }
345             | NativeLibKind::RawDylib
346             | NativeLibKind::LinkArg
347             | NativeLibKind::Unspecified => continue,
348         }
349         if let Some(name) = lib.name {
350             let location =
351                 find_library(name.as_str(), lib.verbatim.unwrap_or(false), &lib_search_paths, sess);
352             ab.add_archive(&location, Box::new(|_| false)).unwrap_or_else(|e| {
353                 sess.fatal(&format!(
354                     "failed to add native library {}: {}",
355                     location.to_string_lossy(),
356                     e
357                 ));
358             });
359         }
360     }
361
362     for (raw_dylib_name, raw_dylib_imports) in
363         collate_raw_dylibs(sess, &codegen_results.crate_info.used_libraries)?
364     {
365         let output_path = archive_builder_builder.create_dll_import_lib(
366             sess,
367             &raw_dylib_name,
368             &raw_dylib_imports,
369             tmpdir.as_ref(),
370         );
371
372         ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|e| {
373             sess.fatal(&format!("failed to add native library {}: {}", output_path.display(), e));
374         });
375     }
376
377     if let Some(trailing_metadata) = trailing_metadata {
378         // Note that it is important that we add all of our non-object "magical
379         // files" *after* all of the object files in the archive. The reason for
380         // this is as follows:
381         //
382         // * When performing LTO, this archive will be modified to remove
383         //   objects from above. The reason for this is described below.
384         //
385         // * When the system linker looks at an archive, it will attempt to
386         //   determine the architecture of the archive in order to see whether its
387         //   linkable.
388         //
389         //   The algorithm for this detection is: iterate over the files in the
390         //   archive. Skip magical SYMDEF names. Interpret the first file as an
391         //   object file. Read architecture from the object file.
392         //
393         // * As one can probably see, if "metadata" and "foo.bc" were placed
394         //   before all of the objects, then the architecture of this archive would
395         //   not be correctly inferred once 'foo.o' is removed.
396         //
397         // * Most of the time metadata in rlib files is wrapped in a "dummy" object
398         //   file for the target platform so the rlib can be processed entirely by
399         //   normal linkers for the platform. Sometimes this is not possible however.
400         //
401         // Basically, all this means is that this code should not move above the
402         // code above.
403         ab.add_file(&trailing_metadata);
404     }
405
406     return Ok(ab);
407 }
408
409 /// Extract all symbols defined in raw-dylib libraries, collated by library name.
410 ///
411 /// If we have multiple extern blocks that specify symbols defined in the same raw-dylib library,
412 /// then the CodegenResults value contains one NativeLib instance for each block.  However, the
413 /// linker appears to expect only a single import library for each library used, so we need to
414 /// collate the symbols together by library name before generating the import libraries.
415 fn collate_raw_dylibs(
416     sess: &Session,
417     used_libraries: &[NativeLib],
418 ) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed> {
419     // Use index maps to preserve original order of imports and libraries.
420     let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
421
422     for lib in used_libraries {
423         if lib.kind == NativeLibKind::RawDylib {
424             let ext = if matches!(lib.verbatim, Some(true)) { "" } else { ".dll" };
425             let name = format!("{}{}", lib.name.expect("unnamed raw-dylib library"), ext);
426             let imports = dylib_table.entry(name.clone()).or_default();
427             for import in &lib.dll_imports {
428                 if let Some(old_import) = imports.insert(import.name, import) {
429                     // FIXME: when we add support for ordinals, figure out if we need to do anything
430                     // if we have two DllImport values with the same name but different ordinals.
431                     if import.calling_convention != old_import.calling_convention {
432                         sess.span_err(
433                             import.span,
434                             &format!(
435                                 "multiple declarations of external function `{}` from \
436                                  library `{}` have different calling conventions",
437                                 import.name, name,
438                             ),
439                         );
440                     }
441                 }
442             }
443         }
444     }
445     sess.compile_status()?;
446     Ok(dylib_table
447         .into_iter()
448         .map(|(name, imports)| {
449             (name, imports.into_iter().map(|(_, import)| import.clone()).collect())
450         })
451         .collect())
452 }
453
454 /// Create a static archive.
455 ///
456 /// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
457 /// crates' objects into the archive. This will slurp in all of the native libraries of upstream
458 /// dependencies as well.
459 ///
460 /// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
461 /// library dependencies that they're not linked in.
462 ///
463 /// There's no need to include metadata in a static archive, so ensure to not link in the metadata
464 /// object file (and also don't prepare the archive with a metadata file).
465 fn link_staticlib<'a>(
466     sess: &'a Session,
467     archive_builder_builder: &dyn ArchiveBuilderBuilder,
468     codegen_results: &CodegenResults,
469     out_filename: &Path,
470     tempdir: &MaybeTempDir,
471 ) -> Result<(), ErrorGuaranteed> {
472     info!("preparing staticlib to {:?}", out_filename);
473     let mut ab = link_rlib(
474         sess,
475         archive_builder_builder,
476         codegen_results,
477         RlibFlavor::StaticlibBase,
478         tempdir,
479     )?;
480     let mut all_native_libs = vec![];
481
482     let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
483         let name = codegen_results.crate_info.crate_name[&cnum];
484         let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
485
486         // Here when we include the rlib into our staticlib we need to make a
487         // decision whether to include the extra object files along the way.
488         // These extra object files come from statically included native
489         // libraries, but they may be cfg'd away with #[link(cfg(..))].
490         //
491         // This unstable feature, though, only needs liblibc to work. The only
492         // use case there is where musl is statically included in liblibc.rlib,
493         // so if we don't want the included version we just need to skip it. As
494         // a result the logic here is that if *any* linked library is cfg'd away
495         // we just skip all object files.
496         //
497         // Clearly this is not sufficient for a general purpose feature, and
498         // we'd want to read from the library's metadata to determine which
499         // object files come from where and selectively skip them.
500         let skip_object_files = native_libs.iter().any(|lib| {
501             matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
502                 && !relevant_lib(sess, lib)
503         });
504
505         let lto = are_upstream_rust_objects_already_included(sess)
506             && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
507
508         // Ignoring obj file starting with the crate name
509         // as simple comparison is not enough - there
510         // might be also an extra name suffix
511         let obj_start = name.as_str().to_owned();
512
513         ab.add_archive(
514             path,
515             Box::new(move |fname: &str| {
516                 // Ignore metadata files, no matter the name.
517                 if fname == METADATA_FILENAME {
518                     return true;
519                 }
520
521                 // Don't include Rust objects if LTO is enabled
522                 if lto && looks_like_rust_object_file(fname) {
523                     return true;
524                 }
525
526                 // Otherwise if this is *not* a rust object and we're skipping
527                 // objects then skip this file
528                 if skip_object_files && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
529                     return true;
530                 }
531
532                 // ok, don't skip this
533                 false
534             }),
535         )
536         .unwrap();
537
538         all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
539     });
540     if let Err(e) = res {
541         sess.fatal(&e);
542     }
543
544     ab.build(out_filename);
545
546     if !all_native_libs.is_empty() {
547         if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
548             print_native_static_libs(sess, &all_native_libs);
549         }
550     }
551
552     Ok(())
553 }
554
555 /// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
556 /// DWARF package.
557 fn link_dwarf_object<'a>(
558     sess: &'a Session,
559     cg_results: &CodegenResults,
560     executable_out_filename: &Path,
561 ) {
562     let dwp_out_filename = executable_out_filename.with_extension("dwp");
563     debug!(?dwp_out_filename, ?executable_out_filename);
564
565     #[derive(Default)]
566     struct ThorinSession<Relocations> {
567         arena_data: TypedArena<Vec<u8>>,
568         arena_mmap: TypedArena<Mmap>,
569         arena_relocations: TypedArena<Relocations>,
570     }
571
572     impl<Relocations> ThorinSession<Relocations> {
573         fn alloc_mmap<'arena>(&'arena self, data: Mmap) -> &'arena Mmap {
574             (*self.arena_mmap.alloc(data)).borrow()
575         }
576     }
577
578     impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
579         fn alloc_data<'arena>(&'arena self, data: Vec<u8>) -> &'arena [u8] {
580             (*self.arena_data.alloc(data)).borrow()
581         }
582
583         fn alloc_relocation<'arena>(&'arena self, data: Relocations) -> &'arena Relocations {
584             (*self.arena_relocations.alloc(data)).borrow()
585         }
586
587         fn read_input<'arena>(&'arena self, path: &Path) -> std::io::Result<&'arena [u8]> {
588             let file = File::open(&path)?;
589             let mmap = (unsafe { Mmap::map(file) })?;
590             Ok(self.alloc_mmap(mmap))
591         }
592     }
593
594     match sess.time("run_thorin", || -> Result<(), thorin::Error> {
595         let thorin_sess = ThorinSession::default();
596         let mut package = thorin::DwarfPackage::new(&thorin_sess);
597
598         // Input objs contain .o/.dwo files from the current crate.
599         match sess.opts.unstable_opts.split_dwarf_kind {
600             SplitDwarfKind::Single => {
601                 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
602                     package.add_input_object(input_obj)?;
603                 }
604             }
605             SplitDwarfKind::Split => {
606                 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
607                     package.add_input_object(input_obj)?;
608                 }
609             }
610         }
611
612         // Input rlibs contain .o/.dwo files from dependencies.
613         let input_rlibs = cg_results
614             .crate_info
615             .used_crate_source
616             .values()
617             .filter_map(|csource| csource.rlib.as_ref())
618             .map(|(path, _)| path);
619         for input_rlib in input_rlibs {
620             debug!(?input_rlib);
621             package.add_input_object(input_rlib)?;
622         }
623
624         // Failing to read the referenced objects is expected for dependencies where the path in the
625         // executable will have been cleaned by Cargo, but the referenced objects will be contained
626         // within rlibs provided as inputs.
627         //
628         // If paths have been remapped, then .o/.dwo files from the current crate also won't be
629         // found, but are provided explicitly above.
630         //
631         // Adding an executable is primarily done to make `thorin` check that all the referenced
632         // dwarf objects are found in the end.
633         package.add_executable(
634             &executable_out_filename,
635             thorin::MissingReferencedObjectBehaviour::Skip,
636         )?;
637
638         let output = package.finish()?.write()?;
639         let mut output_stream = BufWriter::new(
640             OpenOptions::new()
641                 .read(true)
642                 .write(true)
643                 .create(true)
644                 .truncate(true)
645                 .open(dwp_out_filename)?,
646         );
647         output_stream.write_all(&output)?;
648         output_stream.flush()?;
649
650         Ok(())
651     }) {
652         Ok(()) => {}
653         Err(e) => {
654             sess.struct_err("linking dwarf objects with thorin failed")
655                 .note(&format!("{:?}", e))
656                 .emit();
657             sess.abort_if_errors();
658         }
659     }
660 }
661
662 /// Create a dynamic library or executable.
663 ///
664 /// This will invoke the system linker/cc to create the resulting file. This links to all upstream
665 /// files as well.
666 fn link_natively<'a>(
667     sess: &'a Session,
668     archive_builder_builder: &dyn ArchiveBuilderBuilder,
669     crate_type: CrateType,
670     out_filename: &Path,
671     codegen_results: &CodegenResults,
672     tmpdir: &Path,
673 ) -> Result<(), ErrorGuaranteed> {
674     info!("preparing {:?} to {:?}", crate_type, out_filename);
675     let (linker_path, flavor) = linker_and_flavor(sess);
676     let mut cmd = linker_with_args(
677         &linker_path,
678         flavor,
679         sess,
680         archive_builder_builder,
681         crate_type,
682         tmpdir,
683         out_filename,
684         codegen_results,
685     )?;
686
687     linker::disable_localization(&mut cmd);
688
689     for &(ref k, ref v) in sess.target.link_env.as_ref() {
690         cmd.env(k.as_ref(), v.as_ref());
691     }
692     for k in sess.target.link_env_remove.as_ref() {
693         cmd.env_remove(k.as_ref());
694     }
695
696     if sess.opts.prints.contains(&PrintRequest::LinkArgs) {
697         println!("{:?}", &cmd);
698     }
699
700     // May have not found libraries in the right formats.
701     sess.abort_if_errors();
702
703     // Invoke the system linker
704     info!("{:?}", &cmd);
705     let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
706     let unknown_arg_regex =
707         Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
708     let mut prog;
709     let mut i = 0;
710     loop {
711         i += 1;
712         prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
713         let Ok(ref output) = prog else {
714             break;
715         };
716         if output.status.success() {
717             break;
718         }
719         let mut out = output.stderr.clone();
720         out.extend(&output.stdout);
721         let out = String::from_utf8_lossy(&out);
722
723         // Check to see if the link failed with an error message that indicates it
724         // doesn't recognize the -no-pie option. If so, re-perform the link step
725         // without it. This is safe because if the linker doesn't support -no-pie
726         // then it should not default to linking executables as pie. Different
727         // versions of gcc seem to use different quotes in the error message so
728         // don't check for them.
729         if sess.target.linker_is_gnu
730             && flavor != LinkerFlavor::Ld
731             && unknown_arg_regex.is_match(&out)
732             && out.contains("-no-pie")
733             && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
734         {
735             info!("linker output: {:?}", out);
736             warn!("Linker does not support -no-pie command line option. Retrying without.");
737             for arg in cmd.take_args() {
738                 if arg.to_string_lossy() != "-no-pie" {
739                     cmd.arg(arg);
740                 }
741             }
742             info!("{:?}", &cmd);
743             continue;
744         }
745
746         // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
747         // Fallback from '-static-pie' to '-static' in that case.
748         if sess.target.linker_is_gnu
749             && flavor != LinkerFlavor::Ld
750             && unknown_arg_regex.is_match(&out)
751             && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
752             && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
753         {
754             info!("linker output: {:?}", out);
755             warn!(
756                 "Linker does not support -static-pie command line option. Retrying with -static instead."
757             );
758             // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
759             let self_contained = self_contained(sess, crate_type);
760             let opts = &sess.target;
761             let pre_objects = if self_contained {
762                 &opts.pre_link_objects_self_contained
763             } else {
764                 &opts.pre_link_objects
765             };
766             let post_objects = if self_contained {
767                 &opts.post_link_objects_self_contained
768             } else {
769                 &opts.post_link_objects
770             };
771             let get_objects = |objects: &CrtObjects, kind| {
772                 objects
773                     .get(&kind)
774                     .iter()
775                     .copied()
776                     .flatten()
777                     .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
778                     .collect::<Vec<_>>()
779             };
780             let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
781             let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
782             let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
783             let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
784             // Assume that we know insertion positions for the replacement arguments from replaced
785             // arguments, which is true for all supported targets.
786             assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
787             assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
788             for arg in cmd.take_args() {
789                 if arg.to_string_lossy() == "-static-pie" {
790                     // Replace the output kind.
791                     cmd.arg("-static");
792                 } else if pre_objects_static_pie.contains(&arg) {
793                     // Replace the pre-link objects (replace the first and remove the rest).
794                     cmd.args(mem::take(&mut pre_objects_static));
795                 } else if post_objects_static_pie.contains(&arg) {
796                     // Replace the post-link objects (replace the first and remove the rest).
797                     cmd.args(mem::take(&mut post_objects_static));
798                 } else {
799                     cmd.arg(arg);
800                 }
801             }
802             info!("{:?}", &cmd);
803             continue;
804         }
805
806         // Here's a terribly awful hack that really shouldn't be present in any
807         // compiler. Here an environment variable is supported to automatically
808         // retry the linker invocation if the linker looks like it segfaulted.
809         //
810         // Gee that seems odd, normally segfaults are things we want to know
811         // about!  Unfortunately though in rust-lang/rust#38878 we're
812         // experiencing the linker segfaulting on Travis quite a bit which is
813         // causing quite a bit of pain to land PRs when they spuriously fail
814         // due to a segfault.
815         //
816         // The issue #38878 has some more debugging information on it as well,
817         // but this unfortunately looks like it's just a race condition in
818         // macOS's linker with some thread pool working in the background. It
819         // seems that no one currently knows a fix for this so in the meantime
820         // we're left with this...
821         if !retry_on_segfault || i > 3 {
822             break;
823         }
824         let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
825         let msg_bus = "clang: error: unable to execute command: Bus error: 10";
826         if out.contains(msg_segv) || out.contains(msg_bus) {
827             warn!(
828                 ?cmd, %out,
829                 "looks like the linker segfaulted when we tried to call it, \
830                  automatically retrying again",
831             );
832             continue;
833         }
834
835         if is_illegal_instruction(&output.status) {
836             warn!(
837                 ?cmd, %out, status = %output.status,
838                 "looks like the linker hit an illegal instruction when we \
839                  tried to call it, automatically retrying again.",
840             );
841             continue;
842         }
843
844         #[cfg(unix)]
845         fn is_illegal_instruction(status: &ExitStatus) -> bool {
846             use std::os::unix::prelude::*;
847             status.signal() == Some(libc::SIGILL)
848         }
849
850         #[cfg(not(unix))]
851         fn is_illegal_instruction(_status: &ExitStatus) -> bool {
852             false
853         }
854     }
855
856     match prog {
857         Ok(prog) => {
858             if !prog.status.success() {
859                 let mut output = prog.stderr.clone();
860                 output.extend_from_slice(&prog.stdout);
861                 let escaped_output = escape_string(&output);
862                 let mut err = sess.struct_err(&format!(
863                     "linking with `{}` failed: {}",
864                     linker_path.display(),
865                     prog.status
866                 ));
867                 err.note(&format!("{:?}", &cmd)).note(&escaped_output);
868                 if escaped_output.contains("undefined reference to") {
869                     err.help(
870                         "some `extern` functions couldn't be found; some native libraries may \
871                          need to be installed or have their path specified",
872                     );
873                     err.note("use the `-l` flag to specify native libraries to link");
874                     err.note("use the `cargo:rustc-link-lib` directive to specify the native \
875                               libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)");
876                 }
877                 err.emit();
878
879                 // If MSVC's `link.exe` was expected but the return code
880                 // is not a Microsoft LNK error then suggest a way to fix or
881                 // install the Visual Studio build tools.
882                 if let Some(code) = prog.status.code() {
883                     if sess.target.is_like_msvc
884                         && flavor == LinkerFlavor::Msvc
885                         // Respect the command line override
886                         && sess.opts.cg.linker.is_none()
887                         // Match exactly "link.exe"
888                         && linker_path.to_str() == Some("link.exe")
889                         // All Microsoft `link.exe` linking error codes are
890                         // four digit numbers in the range 1000 to 9999 inclusive
891                         && (code < 1000 || code > 9999)
892                     {
893                         let is_vs_installed = windows_registry::find_vs_version().is_ok();
894                         let has_linker = windows_registry::find_tool(
895                             &sess.opts.target_triple.triple(),
896                             "link.exe",
897                         )
898                         .is_some();
899
900                         sess.note_without_error("`link.exe` returned an unexpected error");
901                         if is_vs_installed && has_linker {
902                             // the linker is broken
903                             sess.note_without_error(
904                                 "the Visual Studio build tools may need to be repaired \
905                                 using the Visual Studio installer",
906                             );
907                             sess.note_without_error(
908                                 "or a necessary component may be missing from the \
909                                 \"C++ build tools\" workload",
910                             );
911                         } else if is_vs_installed {
912                             // the linker is not installed
913                             sess.note_without_error(
914                                 "in the Visual Studio installer, ensure the \
915                                 \"C++ build tools\" workload is selected",
916                             );
917                         } else {
918                             // visual studio is not installed
919                             sess.note_without_error(
920                                 "you may need to install Visual Studio build tools with the \
921                                 \"C++ build tools\" workload",
922                             );
923                         }
924                     }
925                 }
926
927                 sess.abort_if_errors();
928             }
929             info!("linker stderr:\n{}", escape_string(&prog.stderr));
930             info!("linker stdout:\n{}", escape_string(&prog.stdout));
931         }
932         Err(e) => {
933             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
934
935             let mut linker_error = {
936                 if linker_not_found {
937                     sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
938                 } else {
939                     sess.struct_err(&format!(
940                         "could not exec the linker `{}`",
941                         linker_path.display()
942                     ))
943                 }
944             };
945
946             linker_error.note(&e.to_string());
947
948             if !linker_not_found {
949                 linker_error.note(&format!("{:?}", &cmd));
950             }
951
952             linker_error.emit();
953
954             if sess.target.is_like_msvc && linker_not_found {
955                 sess.note_without_error(
956                     "the msvc targets depend on the msvc linker \
957                      but `link.exe` was not found",
958                 );
959                 sess.note_without_error(
960                     "please ensure that VS 2013, VS 2015, VS 2017, VS 2019 or VS 2022 \
961                      was installed with the Visual C++ option",
962                 );
963             }
964             sess.abort_if_errors();
965         }
966     }
967
968     match sess.split_debuginfo() {
969         // If split debug information is disabled or located in individual files
970         // there's nothing to do here.
971         SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
972
973         // If packed split-debuginfo is requested, but the final compilation
974         // doesn't actually have any debug information, then we skip this step.
975         SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
976
977         // On macOS the external `dsymutil` tool is used to create the packed
978         // debug information. Note that this will read debug information from
979         // the objects on the filesystem which we'll clean up later.
980         SplitDebuginfo::Packed if sess.target.is_like_osx => {
981             let prog = Command::new("dsymutil").arg(out_filename).output();
982             match prog {
983                 Ok(prog) => {
984                     if !prog.status.success() {
985                         let mut output = prog.stderr.clone();
986                         output.extend_from_slice(&prog.stdout);
987                         sess.struct_warn(&format!(
988                             "processing debug info with `dsymutil` failed: {}",
989                             prog.status
990                         ))
991                         .note(&escape_string(&output))
992                         .emit();
993                     }
994                 }
995                 Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
996             }
997         }
998
999         // On MSVC packed debug information is produced by the linker itself so
1000         // there's no need to do anything else here.
1001         SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1002
1003         // ... and otherwise we're processing a `*.dwp` packed dwarf file.
1004         //
1005         // We cannot rely on the .o paths in the executable because they may have been
1006         // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1007         // the .o/.dwo paths explicitly.
1008         SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1009     }
1010
1011     let strip = strip_value(sess);
1012
1013     if sess.target.is_like_osx {
1014         match (strip, crate_type) {
1015             (Strip::Debuginfo, _) => strip_symbols_in_osx(sess, &out_filename, Some("-S")),
1016             // Per the manpage, `-x` is the maximum safe strip level for dynamic libraries. (#93988)
1017             (Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro) => {
1018                 strip_symbols_in_osx(sess, &out_filename, Some("-x"))
1019             }
1020             (Strip::Symbols, _) => strip_symbols_in_osx(sess, &out_filename, None),
1021             (Strip::None, _) => {}
1022         }
1023     }
1024
1025     Ok(())
1026 }
1027
1028 // Temporarily support both -Z strip and -C strip
1029 fn strip_value(sess: &Session) -> Strip {
1030     match (sess.opts.unstable_opts.strip, sess.opts.cg.strip) {
1031         (s, Strip::None) => s,
1032         (_, s) => s,
1033     }
1034 }
1035
1036 fn strip_symbols_in_osx<'a>(sess: &'a Session, out_filename: &Path, option: Option<&str>) {
1037     let mut cmd = Command::new("strip");
1038     if let Some(option) = option {
1039         cmd.arg(option);
1040     }
1041     let prog = cmd.arg(out_filename).output();
1042     match prog {
1043         Ok(prog) => {
1044             if !prog.status.success() {
1045                 let mut output = prog.stderr.clone();
1046                 output.extend_from_slice(&prog.stdout);
1047                 sess.struct_warn(&format!(
1048                     "stripping debug info with `strip` failed: {}",
1049                     prog.status
1050                 ))
1051                 .note(&escape_string(&output))
1052                 .emit();
1053             }
1054         }
1055         Err(e) => sess.fatal(&format!("unable to run `strip`: {}", e)),
1056     }
1057 }
1058
1059 fn escape_string(s: &[u8]) -> String {
1060     match str::from_utf8(s) {
1061         Ok(s) => s.to_owned(),
1062         Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1063     }
1064 }
1065
1066 fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
1067     // On macOS the runtimes are distributed as dylibs which should be linked to
1068     // both executables and dynamic shared objects. Everywhere else the runtimes
1069     // are currently distributed as static libraries which should be linked to
1070     // executables only.
1071     let needs_runtime = match crate_type {
1072         CrateType::Executable => true,
1073         CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
1074         CrateType::Rlib | CrateType::Staticlib => false,
1075     };
1076
1077     if !needs_runtime {
1078         return;
1079     }
1080
1081     let sanitizer = sess.opts.unstable_opts.sanitizer;
1082     if sanitizer.contains(SanitizerSet::ADDRESS) {
1083         link_sanitizer_runtime(sess, linker, "asan");
1084     }
1085     if sanitizer.contains(SanitizerSet::LEAK) {
1086         link_sanitizer_runtime(sess, linker, "lsan");
1087     }
1088     if sanitizer.contains(SanitizerSet::MEMORY) {
1089         link_sanitizer_runtime(sess, linker, "msan");
1090     }
1091     if sanitizer.contains(SanitizerSet::THREAD) {
1092         link_sanitizer_runtime(sess, linker, "tsan");
1093     }
1094     if sanitizer.contains(SanitizerSet::HWADDRESS) {
1095         link_sanitizer_runtime(sess, linker, "hwasan");
1096     }
1097 }
1098
1099 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
1100     fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1101         let session_tlib =
1102             filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
1103         let path = session_tlib.join(filename);
1104         if path.exists() {
1105             return session_tlib;
1106         } else {
1107             let default_sysroot = filesearch::get_or_default_sysroot();
1108             let default_tlib = filesearch::make_target_lib_path(
1109                 &default_sysroot,
1110                 sess.opts.target_triple.triple(),
1111             );
1112             return default_tlib;
1113         }
1114     }
1115
1116     let channel = option_env!("CFG_RELEASE_CHANNEL")
1117         .map(|channel| format!("-{}", channel))
1118         .unwrap_or_default();
1119
1120     if sess.target.is_like_osx {
1121         // On Apple platforms, the sanitizer is always built as a dylib, and
1122         // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1123         // rpath to the library as well (the rpath should be absolute, see
1124         // PR #41352 for details).
1125         let filename = format!("rustc{}_rt.{}", channel, name);
1126         let path = find_sanitizer_runtime(&sess, &filename);
1127         let rpath = path.to_str().expect("non-utf8 component in path");
1128         linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
1129         linker.link_dylib(&filename, false, true);
1130     } else {
1131         let filename = format!("librustc{}_rt.{}.a", channel, name);
1132         let path = find_sanitizer_runtime(&sess, &filename).join(&filename);
1133         linker.link_whole_rlib(&path);
1134     }
1135 }
1136
1137 /// Returns a boolean indicating whether the specified crate should be ignored
1138 /// during LTO.
1139 ///
1140 /// Crates ignored during LTO are not lumped together in the "massive object
1141 /// file" that we create and are linked in their normal rlib states. See
1142 /// comments below for what crates do not participate in LTO.
1143 ///
1144 /// It's unusual for a crate to not participate in LTO. Typically only
1145 /// compiler-specific and unstable crates have a reason to not participate in
1146 /// LTO.
1147 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1148     // If our target enables builtin function lowering in LLVM then the
1149     // crates providing these functions don't participate in LTO (e.g.
1150     // no_builtins or compiler builtins crates).
1151     !sess.target.no_builtins
1152         && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1153 }
1154
1155 // This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1156 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1157     fn infer_from(
1158         sess: &Session,
1159         linker: Option<PathBuf>,
1160         flavor: Option<LinkerFlavor>,
1161     ) -> Option<(PathBuf, LinkerFlavor)> {
1162         match (linker, flavor) {
1163             (Some(linker), Some(flavor)) => Some((linker, flavor)),
1164             // only the linker flavor is known; use the default linker for the selected flavor
1165             (None, Some(flavor)) => Some((
1166                 PathBuf::from(match flavor {
1167                     LinkerFlavor::Em => {
1168                         if cfg!(windows) {
1169                             "emcc.bat"
1170                         } else {
1171                             "emcc"
1172                         }
1173                     }
1174                     LinkerFlavor::Gcc => {
1175                         if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1176                             // On historical Solaris systems, "cc" may have
1177                             // been Sun Studio, which is not flag-compatible
1178                             // with "gcc".  This history casts a long shadow,
1179                             // and many modern illumos distributions today
1180                             // ship GCC as "gcc" without also making it
1181                             // available as "cc".
1182                             "gcc"
1183                         } else {
1184                             "cc"
1185                         }
1186                     }
1187                     LinkerFlavor::Ld => "ld",
1188                     LinkerFlavor::Msvc => "link.exe",
1189                     LinkerFlavor::Lld(_) => "lld",
1190                     LinkerFlavor::PtxLinker => "rust-ptx-linker",
1191                     LinkerFlavor::BpfLinker => "bpf-linker",
1192                     LinkerFlavor::L4Bender => "l4-bender",
1193                 }),
1194                 flavor,
1195             )),
1196             (Some(linker), None) => {
1197                 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1198                     sess.fatal("couldn't extract file stem from specified linker")
1199                 });
1200
1201                 let flavor = if stem == "emcc" {
1202                     LinkerFlavor::Em
1203                 } else if stem == "gcc"
1204                     || stem.ends_with("-gcc")
1205                     || stem == "clang"
1206                     || stem.ends_with("-clang")
1207                 {
1208                     LinkerFlavor::Gcc
1209                 } else if stem == "wasm-ld" || stem.ends_with("-wasm-ld") {
1210                     LinkerFlavor::Lld(LldFlavor::Wasm)
1211                 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
1212                     LinkerFlavor::Ld
1213                 } else if stem == "link" || stem == "lld-link" {
1214                     LinkerFlavor::Msvc
1215                 } else if stem == "lld" || stem == "rust-lld" {
1216                     LinkerFlavor::Lld(sess.target.lld_flavor)
1217                 } else {
1218                     // fall back to the value in the target spec
1219                     sess.target.linker_flavor
1220                 };
1221
1222                 Some((linker, flavor))
1223             }
1224             (None, None) => None,
1225         }
1226     }
1227
1228     // linker and linker flavor specified via command line have precedence over what the target
1229     // specification specifies
1230     if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
1231         return ret;
1232     }
1233
1234     if let Some(ret) = infer_from(
1235         sess,
1236         sess.target.linker.as_deref().map(PathBuf::from),
1237         Some(sess.target.linker_flavor),
1238     ) {
1239         return ret;
1240     }
1241
1242     bug!("Not enough information provided to determine how to invoke the linker");
1243 }
1244
1245 /// Returns a pair of boolean indicating whether we should preserve the object and
1246 /// dwarf object files on the filesystem for their debug information. This is often
1247 /// useful with split-dwarf like schemes.
1248 fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1249     // If the objects don't have debuginfo there's nothing to preserve.
1250     if sess.opts.debuginfo == config::DebugInfo::None {
1251         return (false, false);
1252     }
1253
1254     // If we're only producing artifacts that are archives, no need to preserve
1255     // the objects as they're losslessly contained inside the archives.
1256     if sess.crate_types().iter().all(|&x| x.is_archive()) {
1257         return (false, false);
1258     }
1259
1260     match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1261         // If there is no split debuginfo then do not preserve objects.
1262         (SplitDebuginfo::Off, _) => (false, false),
1263         // If there is packed split debuginfo, then the debuginfo in the objects
1264         // has been packaged and the objects can be deleted.
1265         (SplitDebuginfo::Packed, _) => (false, false),
1266         // If there is unpacked split debuginfo and the current target can not use
1267         // split dwarf, then keep objects.
1268         (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1269         // If there is unpacked split debuginfo and the target can use split dwarf, then
1270         // keep the object containing that debuginfo (whether that is an object file or
1271         // dwarf object file depends on the split dwarf kind).
1272         (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1273         (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1274     }
1275 }
1276
1277 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
1278     sess.target_filesearch(PathKind::Native).search_path_dirs()
1279 }
1280
1281 #[derive(PartialEq)]
1282 enum RlibFlavor {
1283     Normal,
1284     StaticlibBase,
1285 }
1286
1287 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
1288     let lib_args: Vec<_> = all_native_libs
1289         .iter()
1290         .filter(|l| relevant_lib(sess, l))
1291         .filter_map(|lib| {
1292             let name = lib.name?;
1293             match lib.kind {
1294                 NativeLibKind::Static { bundle: Some(false), .. }
1295                 | NativeLibKind::Dylib { .. }
1296                 | NativeLibKind::Unspecified => {
1297                     let verbatim = lib.verbatim.unwrap_or(false);
1298                     if sess.target.is_like_msvc {
1299                         Some(format!("{}{}", name, if verbatim { "" } else { ".lib" }))
1300                     } else if sess.target.linker_is_gnu {
1301                         Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1302                     } else {
1303                         Some(format!("-l{}", name))
1304                     }
1305                 }
1306                 NativeLibKind::Framework { .. } => {
1307                     // ld-only syntax, since there are no frameworks in MSVC
1308                     Some(format!("-framework {}", name))
1309                 }
1310                 // These are included, no need to print them
1311                 NativeLibKind::Static { bundle: None | Some(true), .. }
1312                 | NativeLibKind::LinkArg
1313                 | NativeLibKind::RawDylib => None,
1314             }
1315         })
1316         .collect();
1317     if !lib_args.is_empty() {
1318         sess.note_without_error(
1319             "Link against the following native artifacts when linking \
1320                                  against this static library. The order and any duplication \
1321                                  can be significant on some platforms.",
1322         );
1323         // Prefix for greppability
1324         sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1325     }
1326 }
1327
1328 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1329     let fs = sess.target_filesearch(PathKind::Native);
1330     let file_path = fs.get_lib_path().join(name);
1331     if file_path.exists() {
1332         return file_path;
1333     }
1334     // Special directory with objects used only in self-contained linkage mode
1335     if self_contained {
1336         let file_path = fs.get_self_contained_lib_path().join(name);
1337         if file_path.exists() {
1338             return file_path;
1339         }
1340     }
1341     for search_path in fs.search_paths() {
1342         let file_path = search_path.dir.join(name);
1343         if file_path.exists() {
1344             return file_path;
1345         }
1346     }
1347     PathBuf::from(name)
1348 }
1349
1350 fn exec_linker(
1351     sess: &Session,
1352     cmd: &Command,
1353     out_filename: &Path,
1354     tmpdir: &Path,
1355 ) -> io::Result<Output> {
1356     // When attempting to spawn the linker we run a risk of blowing out the
1357     // size limits for spawning a new process with respect to the arguments
1358     // we pass on the command line.
1359     //
1360     // Here we attempt to handle errors from the OS saying "your list of
1361     // arguments is too big" by reinvoking the linker again with an `@`-file
1362     // that contains all the arguments. The theory is that this is then
1363     // accepted on all linkers and the linker will read all its options out of
1364     // there instead of looking at the command line.
1365     if !cmd.very_likely_to_exceed_some_spawn_limit() {
1366         match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1367             Ok(child) => {
1368                 let output = child.wait_with_output();
1369                 flush_linked_file(&output, out_filename)?;
1370                 return output;
1371             }
1372             Err(ref e) if command_line_too_big(e) => {
1373                 info!("command line to linker was too big: {}", e);
1374             }
1375             Err(e) => return Err(e),
1376         }
1377     }
1378
1379     info!("falling back to passing arguments to linker via an @-file");
1380     let mut cmd2 = cmd.clone();
1381     let mut args = String::new();
1382     for arg in cmd2.take_args() {
1383         args.push_str(
1384             &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1385                 .to_string(),
1386         );
1387         args.push('\n');
1388     }
1389     let file = tmpdir.join("linker-arguments");
1390     let bytes = if sess.target.is_like_msvc {
1391         let mut out = Vec::with_capacity((1 + args.len()) * 2);
1392         // start the stream with a UTF-16 BOM
1393         for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1394             // encode in little endian
1395             out.push(c as u8);
1396             out.push((c >> 8) as u8);
1397         }
1398         out
1399     } else {
1400         args.into_bytes()
1401     };
1402     fs::write(&file, &bytes)?;
1403     cmd2.arg(format!("@{}", file.display()));
1404     info!("invoking linker {:?}", cmd2);
1405     let output = cmd2.output();
1406     flush_linked_file(&output, out_filename)?;
1407     return output;
1408
1409     #[cfg(not(windows))]
1410     fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1411         Ok(())
1412     }
1413
1414     #[cfg(windows)]
1415     fn flush_linked_file(
1416         command_output: &io::Result<Output>,
1417         out_filename: &Path,
1418     ) -> io::Result<()> {
1419         // On Windows, under high I/O load, output buffers are sometimes not flushed,
1420         // even long after process exit, causing nasty, non-reproducible output bugs.
1421         //
1422         // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1423         //
1424         // А full writeup of the original Chrome bug can be found at
1425         // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1426
1427         if let &Ok(ref out) = command_output {
1428             if out.status.success() {
1429                 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1430                     of.sync_all()?;
1431                 }
1432             }
1433         }
1434
1435         Ok(())
1436     }
1437
1438     #[cfg(unix)]
1439     fn command_line_too_big(err: &io::Error) -> bool {
1440         err.raw_os_error() == Some(::libc::E2BIG)
1441     }
1442
1443     #[cfg(windows)]
1444     fn command_line_too_big(err: &io::Error) -> bool {
1445         const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1446         err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1447     }
1448
1449     #[cfg(not(any(unix, windows)))]
1450     fn command_line_too_big(_: &io::Error) -> bool {
1451         false
1452     }
1453
1454     struct Escape<'a> {
1455         arg: &'a str,
1456         is_like_msvc: bool,
1457     }
1458
1459     impl<'a> fmt::Display for Escape<'a> {
1460         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461             if self.is_like_msvc {
1462                 // This is "documented" at
1463                 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1464                 //
1465                 // Unfortunately there's not a great specification of the
1466                 // syntax I could find online (at least) but some local
1467                 // testing showed that this seemed sufficient-ish to catch
1468                 // at least a few edge cases.
1469                 write!(f, "\"")?;
1470                 for c in self.arg.chars() {
1471                     match c {
1472                         '"' => write!(f, "\\{}", c)?,
1473                         c => write!(f, "{}", c)?,
1474                     }
1475                 }
1476                 write!(f, "\"")?;
1477             } else {
1478                 // This is documented at https://linux.die.net/man/1/ld, namely:
1479                 //
1480                 // > Options in file are separated by whitespace. A whitespace
1481                 // > character may be included in an option by surrounding the
1482                 // > entire option in either single or double quotes. Any
1483                 // > character (including a backslash) may be included by
1484                 // > prefixing the character to be included with a backslash.
1485                 //
1486                 // We put an argument on each line, so all we need to do is
1487                 // ensure the line is interpreted as one whole argument.
1488                 for c in self.arg.chars() {
1489                     match c {
1490                         '\\' | ' ' => write!(f, "\\{}", c)?,
1491                         c => write!(f, "{}", c)?,
1492                     }
1493                 }
1494             }
1495             Ok(())
1496         }
1497     }
1498 }
1499
1500 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1501     let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1502         (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1503         (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1504             LinkOutputKind::DynamicPicExe
1505         }
1506         (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1507         (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1508             LinkOutputKind::StaticPicExe
1509         }
1510         (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1511         (_, true, _) => LinkOutputKind::StaticDylib,
1512         (_, false, _) => LinkOutputKind::DynamicDylib,
1513     };
1514
1515     // Adjust the output kind to target capabilities.
1516     let opts = &sess.target;
1517     let pic_exe_supported = opts.position_independent_executables;
1518     let static_pic_exe_supported = opts.static_position_independent_executables;
1519     let static_dylib_supported = opts.crt_static_allows_dylibs;
1520     match kind {
1521         LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1522         LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1523         LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1524         _ => kind,
1525     }
1526 }
1527
1528 // Returns true if linker is located within sysroot
1529 fn detect_self_contained_mingw(sess: &Session) -> bool {
1530     let (linker, _) = linker_and_flavor(&sess);
1531     // Assume `-C linker=rust-lld` as self-contained mode
1532     if linker == Path::new("rust-lld") {
1533         return true;
1534     }
1535     let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1536         linker.with_extension("exe")
1537     } else {
1538         linker
1539     };
1540     for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1541         let full_path = dir.join(&linker_with_extension);
1542         // If linker comes from sysroot assume self-contained mode
1543         if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1544             return false;
1545         }
1546     }
1547     true
1548 }
1549
1550 /// Various toolchain components used during linking are used from rustc distribution
1551 /// instead of being found somewhere on the host system.
1552 /// We only provide such support for a very limited number of targets.
1553 fn self_contained(sess: &Session, crate_type: CrateType) -> bool {
1554     if let Some(self_contained) = sess.opts.cg.link_self_contained {
1555         return self_contained;
1556     }
1557
1558     match sess.target.link_self_contained {
1559         LinkSelfContainedDefault::False => false,
1560         LinkSelfContainedDefault::True => true,
1561         // FIXME: Find a better heuristic for "native musl toolchain is available",
1562         // based on host and linker path, for example.
1563         // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1564         LinkSelfContainedDefault::Musl => sess.crt_static(Some(crate_type)),
1565         LinkSelfContainedDefault::Mingw => {
1566             sess.host == sess.target
1567                 && sess.target.vendor != "uwp"
1568                 && detect_self_contained_mingw(&sess)
1569         }
1570     }
1571 }
1572
1573 /// Add pre-link object files defined by the target spec.
1574 fn add_pre_link_objects(
1575     cmd: &mut dyn Linker,
1576     sess: &Session,
1577     flavor: LinkerFlavor,
1578     link_output_kind: LinkOutputKind,
1579     self_contained: bool,
1580 ) {
1581     // FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1582     // so Fuchsia has to be special-cased.
1583     let opts = &sess.target;
1584     let empty = Default::default();
1585     let objects = if self_contained {
1586         &opts.pre_link_objects_self_contained
1587     } else if !(sess.target.os == "fuchsia" && flavor == LinkerFlavor::Gcc) {
1588         &opts.pre_link_objects
1589     } else {
1590         &empty
1591     };
1592     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1593         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1594     }
1595 }
1596
1597 /// Add post-link object files defined by the target spec.
1598 fn add_post_link_objects(
1599     cmd: &mut dyn Linker,
1600     sess: &Session,
1601     link_output_kind: LinkOutputKind,
1602     self_contained: bool,
1603 ) {
1604     let objects = if self_contained {
1605         &sess.target.post_link_objects_self_contained
1606     } else {
1607         &sess.target.post_link_objects
1608     };
1609     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1610         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1611     }
1612 }
1613
1614 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1615 /// FIXME: Determine where exactly these args need to be inserted.
1616 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1617     if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1618         cmd.args(args.iter().map(Deref::deref));
1619     }
1620     cmd.args(&sess.opts.unstable_opts.pre_link_args);
1621 }
1622
1623 /// Add a link script embedded in the target, if applicable.
1624 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1625     match (crate_type, &sess.target.link_script) {
1626         (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1627             if !sess.target.linker_is_gnu {
1628                 sess.fatal("can only use link script when linking with GNU-like linker");
1629             }
1630
1631             let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1632
1633             let path = tmpdir.join(file_name);
1634             if let Err(e) = fs::write(&path, script.as_ref()) {
1635                 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1636             }
1637
1638             cmd.arg("--script");
1639             cmd.arg(path);
1640         }
1641         _ => {}
1642     }
1643 }
1644
1645 /// Add arbitrary "user defined" args defined from command line.
1646 /// FIXME: Determine where exactly these args need to be inserted.
1647 fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1648     cmd.args(&sess.opts.cg.link_args);
1649 }
1650
1651 /// Add arbitrary "late link" args defined by the target spec.
1652 /// FIXME: Determine where exactly these args need to be inserted.
1653 fn add_late_link_args(
1654     cmd: &mut dyn Linker,
1655     sess: &Session,
1656     flavor: LinkerFlavor,
1657     crate_type: CrateType,
1658     codegen_results: &CodegenResults,
1659 ) {
1660     let any_dynamic_crate = crate_type == CrateType::Dylib
1661         || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1662             *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1663         });
1664     if any_dynamic_crate {
1665         if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1666             cmd.args(args.iter().map(Deref::deref));
1667         }
1668     } else {
1669         if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1670             cmd.args(args.iter().map(Deref::deref));
1671         }
1672     }
1673     if let Some(args) = sess.target.late_link_args.get(&flavor) {
1674         cmd.args(args.iter().map(Deref::deref));
1675     }
1676 }
1677
1678 /// Add arbitrary "post-link" args defined by the target spec.
1679 /// FIXME: Determine where exactly these args need to be inserted.
1680 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1681     if let Some(args) = sess.target.post_link_args.get(&flavor) {
1682         cmd.args(args.iter().map(Deref::deref));
1683     }
1684 }
1685
1686 /// Add a synthetic object file that contains reference to all symbols that we want to expose to
1687 /// the linker.
1688 ///
1689 /// Background: we implement rlibs as static library (archives). Linkers treat archives
1690 /// differently from object files: all object files participate in linking, while archives will
1691 /// only participate in linking if they can satisfy at least one undefined reference (version
1692 /// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1693 /// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1694 /// can't keep them either. This causes #47384.
1695 ///
1696 /// To keep them around, we could use `--whole-archive` and equivalents to force rlib to
1697 /// participate in linking like object files, but this proves to be expensive (#93791). Therefore
1698 /// we instead just introduce an undefined reference to them. This could be done by `-u` command
1699 /// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1700 /// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1701 /// from removing them, and this is especially problematic for embedded programming where every
1702 /// byte counts.
1703 ///
1704 /// This method creates a synthetic object file, which contains undefined references to all symbols
1705 /// that are necessary for the linking. They are only present in symbol table but not actually
1706 /// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1707 /// unused `#[no_mangle]` or `#[used]` can still be discard by GC sections.
1708 fn add_linked_symbol_object(
1709     cmd: &mut dyn Linker,
1710     sess: &Session,
1711     tmpdir: &Path,
1712     symbols: &[(String, SymbolExportKind)],
1713 ) {
1714     if symbols.is_empty() {
1715         return;
1716     }
1717
1718     let Some(mut file) = super::metadata::create_object_file(sess) else {
1719         return;
1720     };
1721
1722     // NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1723     // so add an empty section.
1724     if file.format() == object::BinaryFormat::Coff {
1725         file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1726
1727         // We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1728         // default mangler in `object` crate.
1729         file.set_mangling(object::write::Mangling::None);
1730
1731         // Add feature flags to the object file. On MSVC this is optional but LLD will complain if
1732         // not present.
1733         let mut feature = 0;
1734
1735         if file.architecture() == object::Architecture::I386 {
1736             // Indicate that all SEH handlers are registered in .sxdata section.
1737             // We don't have generate any code, so we don't need .sxdata section but LLD still
1738             // expects us to set this bit (see #96498).
1739             // Reference: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
1740             feature |= 1;
1741         }
1742
1743         file.add_symbol(object::write::Symbol {
1744             name: "@feat.00".into(),
1745             value: feature,
1746             size: 0,
1747             kind: object::SymbolKind::Data,
1748             scope: object::SymbolScope::Compilation,
1749             weak: false,
1750             section: object::write::SymbolSection::Absolute,
1751             flags: object::SymbolFlags::None,
1752         });
1753     }
1754
1755     for (sym, kind) in symbols.iter() {
1756         file.add_symbol(object::write::Symbol {
1757             name: sym.clone().into(),
1758             value: 0,
1759             size: 0,
1760             kind: match kind {
1761                 SymbolExportKind::Text => object::SymbolKind::Text,
1762                 SymbolExportKind::Data => object::SymbolKind::Data,
1763                 SymbolExportKind::Tls => object::SymbolKind::Tls,
1764             },
1765             scope: object::SymbolScope::Unknown,
1766             weak: false,
1767             section: object::write::SymbolSection::Undefined,
1768             flags: object::SymbolFlags::None,
1769         });
1770     }
1771
1772     let path = tmpdir.join("symbols.o");
1773     let result = std::fs::write(&path, file.write().unwrap());
1774     if let Err(e) = result {
1775         sess.fatal(&format!("failed to write {}: {}", path.display(), e));
1776     }
1777     cmd.add_object(&path);
1778 }
1779
1780 /// Add object files containing code from the current crate.
1781 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1782     for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1783         cmd.add_object(obj);
1784     }
1785 }
1786
1787 /// Add object files for allocator code linked once for the whole crate tree.
1788 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1789     if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1790         cmd.add_object(obj);
1791     }
1792 }
1793
1794 /// Add object files containing metadata for the current crate.
1795 fn add_local_crate_metadata_objects(
1796     cmd: &mut dyn Linker,
1797     crate_type: CrateType,
1798     codegen_results: &CodegenResults,
1799 ) {
1800     // When linking a dynamic library, we put the metadata into a section of the
1801     // executable. This metadata is in a separate object file from the main
1802     // object file, so we link that in here.
1803     if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1804         if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1805         {
1806             cmd.add_object(obj);
1807         }
1808     }
1809 }
1810
1811 /// Add sysroot and other globally set directories to the directory search list.
1812 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1813     // The default library location, we need this to find the runtime.
1814     // The location of crates will be determined as needed.
1815     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1816     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1817
1818     // Special directory with libraries used only in self-contained linkage mode
1819     if self_contained {
1820         let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1821         cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1822     }
1823 }
1824
1825 /// Add options making relocation sections in the produced ELF files read-only
1826 /// and suppressing lazy binding.
1827 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1828     match sess.opts.unstable_opts.relro_level.unwrap_or(sess.target.relro_level) {
1829         RelroLevel::Full => cmd.full_relro(),
1830         RelroLevel::Partial => cmd.partial_relro(),
1831         RelroLevel::Off => cmd.no_relro(),
1832         RelroLevel::None => {}
1833     }
1834 }
1835
1836 /// Add library search paths used at runtime by dynamic linkers.
1837 fn add_rpath_args(
1838     cmd: &mut dyn Linker,
1839     sess: &Session,
1840     codegen_results: &CodegenResults,
1841     out_filename: &Path,
1842 ) {
1843     // FIXME (#2397): At some point we want to rpath our guesses as to
1844     // where extern libraries might live, based on the
1845     // add_lib_search_paths
1846     if sess.opts.cg.rpath {
1847         let libs = codegen_results
1848             .crate_info
1849             .used_crates
1850             .iter()
1851             .filter_map(|cnum| {
1852                 codegen_results.crate_info.used_crate_source[cnum]
1853                     .dylib
1854                     .as_ref()
1855                     .map(|(path, _)| &**path)
1856             })
1857             .collect::<Vec<_>>();
1858         let mut rpath_config = RPathConfig {
1859             libs: &*libs,
1860             out_filename: out_filename.to_path_buf(),
1861             has_rpath: sess.target.has_rpath,
1862             is_like_osx: sess.target.is_like_osx,
1863             linker_is_gnu: sess.target.linker_is_gnu,
1864         };
1865         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1866     }
1867 }
1868
1869 /// Produce the linker command line containing linker path and arguments.
1870 ///
1871 /// When comments in the function say "order-(in)dependent" they mean order-dependence between
1872 /// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
1873 /// to specific libraries passed after it, and `-o` (output file, order-independent) applies
1874 /// to the linking process as a whole.
1875 /// Order-independent options may still override each other in order-dependent fashion,
1876 /// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
1877 fn linker_with_args<'a>(
1878     path: &Path,
1879     flavor: LinkerFlavor,
1880     sess: &'a Session,
1881     archive_builder_builder: &dyn ArchiveBuilderBuilder,
1882     crate_type: CrateType,
1883     tmpdir: &Path,
1884     out_filename: &Path,
1885     codegen_results: &CodegenResults,
1886 ) -> Result<Command, ErrorGuaranteed> {
1887     let self_contained = self_contained(sess, crate_type);
1888     let cmd = &mut *super::linker::get_linker(
1889         sess,
1890         path,
1891         flavor,
1892         self_contained,
1893         &codegen_results.crate_info.target_cpu,
1894     );
1895     let link_output_kind = link_output_kind(sess, crate_type);
1896
1897     // ------------ Early order-dependent options ------------
1898
1899     // If we're building something like a dynamic library then some platforms
1900     // need to make sure that all symbols are exported correctly from the
1901     // dynamic library.
1902     // Must be passed before any libraries to prevent the symbols to export from being thrown away,
1903     // at least on some platforms (e.g. windows-gnu).
1904     cmd.export_symbols(
1905         tmpdir,
1906         crate_type,
1907         &codegen_results.crate_info.exported_symbols[&crate_type],
1908     );
1909
1910     // Can be used for adding custom CRT objects or overriding order-dependent options above.
1911     // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
1912     // introduce a target spec option for order-independent linker options and migrate built-in
1913     // specs to it.
1914     add_pre_link_args(cmd, sess, flavor);
1915
1916     // ------------ Object code and libraries, order-dependent ------------
1917
1918     // Pre-link CRT objects.
1919     add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained);
1920
1921     add_linked_symbol_object(
1922         cmd,
1923         sess,
1924         tmpdir,
1925         &codegen_results.crate_info.linked_symbols[&crate_type],
1926     );
1927
1928     // Sanitizer libraries.
1929     add_sanitizer_libraries(sess, crate_type, cmd);
1930
1931     // Object code from the current crate.
1932     // Take careful note of the ordering of the arguments we pass to the linker
1933     // here. Linkers will assume that things on the left depend on things to the
1934     // right. Things on the right cannot depend on things on the left. This is
1935     // all formally implemented in terms of resolving symbols (libs on the right
1936     // resolve unknown symbols of libs on the left, but not vice versa).
1937     //
1938     // For this reason, we have organized the arguments we pass to the linker as
1939     // such:
1940     //
1941     // 1. The local object that LLVM just generated
1942     // 2. Local native libraries
1943     // 3. Upstream rust libraries
1944     // 4. Upstream native libraries
1945     //
1946     // The rationale behind this ordering is that those items lower down in the
1947     // list can't depend on items higher up in the list. For example nothing can
1948     // depend on what we just generated (e.g., that'd be a circular dependency).
1949     // Upstream rust libraries are not supposed to depend on our local native
1950     // libraries as that would violate the structure of the DAG, in that
1951     // scenario they are required to link to them as well in a shared fashion.
1952     // (The current implementation still doesn't prevent it though, see the FIXME below.)
1953     //
1954     // Note that upstream rust libraries may contain native dependencies as
1955     // well, but they also can't depend on what we just started to add to the
1956     // link line. And finally upstream native libraries can't depend on anything
1957     // in this DAG so far because they can only depend on other native libraries
1958     // and such dependencies are also required to be specified.
1959     add_local_crate_regular_objects(cmd, codegen_results);
1960     add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1961     add_local_crate_allocator_objects(cmd, codegen_results);
1962
1963     // Avoid linking to dynamic libraries unless they satisfy some undefined symbols
1964     // at the point at which they are specified on the command line.
1965     // Must be passed before any (dynamic) libraries to have effect on them.
1966     // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
1967     // so it will ignore unreferenced ELF sections from relocatable objects.
1968     // For that reason, we put this flag after metadata objects as they would otherwise be removed.
1969     // FIXME: Support more fine-grained dead code removal on Solaris/illumos
1970     // and move this option back to the top.
1971     cmd.add_as_needed();
1972
1973     // FIXME: Move this below to other native libraries
1974     // (or alternatively link all native libraries after their respective crates).
1975     // This change is somewhat breaking in practice due to local static libraries being linked
1976     // as whole-archive (#85144), so removing whole-archive may be a pre-requisite.
1977     if sess.opts.unstable_opts.link_native_libraries {
1978         add_local_native_libraries(cmd, sess, codegen_results);
1979     }
1980
1981     // Upstream rust libraries and their non-bundled static libraries
1982     add_upstream_rust_crates(
1983         cmd,
1984         sess,
1985         archive_builder_builder,
1986         codegen_results,
1987         crate_type,
1988         tmpdir,
1989     );
1990
1991     // Upstream dynamic native libraries linked with `#[link]` attributes at and `-l`
1992     // command line options.
1993     // If -Zlink-native-libraries=false is set, then the assumption is that an
1994     // external build system already has the native dependencies defined, and it
1995     // will provide them to the linker itself.
1996     if sess.opts.unstable_opts.link_native_libraries {
1997         add_upstream_native_libraries(cmd, sess, codegen_results);
1998     }
1999
2000     // Link with the import library generated for any raw-dylib functions.
2001     for (raw_dylib_name, raw_dylib_imports) in
2002         collate_raw_dylibs(sess, &codegen_results.crate_info.used_libraries)?
2003     {
2004         cmd.add_object(&archive_builder_builder.create_dll_import_lib(
2005             sess,
2006             &raw_dylib_name,
2007             &raw_dylib_imports,
2008             tmpdir,
2009         ));
2010     }
2011
2012     // Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2013     // command line shorter, reset it to default here before adding more libraries.
2014     cmd.reset_per_library_state();
2015
2016     // FIXME: Built-in target specs occasionally use this for linking system libraries,
2017     // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2018     // and remove the option.
2019     add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2020
2021     // ------------ Arbitrary order-independent options ------------
2022
2023     // Add order-independent options determined by rustc from its compiler options,
2024     // target properties and source code.
2025     add_order_independent_options(
2026         cmd,
2027         sess,
2028         link_output_kind,
2029         self_contained,
2030         flavor,
2031         crate_type,
2032         codegen_results,
2033         out_filename,
2034         tmpdir,
2035     );
2036
2037     // Can be used for arbitrary order-independent options.
2038     // In practice may also be occasionally used for linking native libraries.
2039     // Passed after compiler-generated options to support manual overriding when necessary.
2040     add_user_defined_link_args(cmd, sess);
2041
2042     // ------------ Object code and libraries, order-dependent ------------
2043
2044     // Post-link CRT objects.
2045     add_post_link_objects(cmd, sess, link_output_kind, self_contained);
2046
2047     // ------------ Late order-dependent options ------------
2048
2049     // Doesn't really make sense.
2050     // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2051     // introduce a target spec option for order-independent linker options, migrate built-in specs
2052     // to it and remove the option.
2053     add_post_link_args(cmd, sess, flavor);
2054
2055     Ok(cmd.take_cmd())
2056 }
2057
2058 fn add_order_independent_options(
2059     cmd: &mut dyn Linker,
2060     sess: &Session,
2061     link_output_kind: LinkOutputKind,
2062     self_contained: bool,
2063     flavor: LinkerFlavor,
2064     crate_type: CrateType,
2065     codegen_results: &CodegenResults,
2066     out_filename: &Path,
2067     tmpdir: &Path,
2068 ) {
2069     add_gcc_ld_path(cmd, sess, flavor);
2070
2071     add_apple_sdk(cmd, sess, flavor);
2072
2073     add_link_script(cmd, sess, tmpdir, crate_type);
2074
2075     if sess.target.os == "fuchsia"
2076         && crate_type == CrateType::Executable
2077         && flavor != LinkerFlavor::Gcc
2078     {
2079         let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2080             "asan/"
2081         } else {
2082             ""
2083         };
2084         cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
2085     }
2086
2087     if sess.target.eh_frame_header {
2088         cmd.add_eh_frame_header();
2089     }
2090
2091     // Make the binary compatible with data execution prevention schemes.
2092     cmd.add_no_exec();
2093
2094     if self_contained {
2095         cmd.no_crt_objects();
2096     }
2097
2098     if sess.target.os == "emscripten" {
2099         cmd.arg("-s");
2100         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
2101             "DISABLE_EXCEPTION_CATCHING=1"
2102         } else {
2103             "DISABLE_EXCEPTION_CATCHING=0"
2104         });
2105     }
2106
2107     if flavor == LinkerFlavor::PtxLinker {
2108         // Provide the linker with fallback to internal `target-cpu`.
2109         cmd.arg("--fallback-arch");
2110         cmd.arg(&codegen_results.crate_info.target_cpu);
2111     } else if flavor == LinkerFlavor::BpfLinker {
2112         cmd.arg("--cpu");
2113         cmd.arg(&codegen_results.crate_info.target_cpu);
2114         cmd.arg("--cpu-features");
2115         cmd.arg(match &sess.opts.cg.target_feature {
2116             feat if !feat.is_empty() => feat.as_ref(),
2117             _ => sess.target.options.features.as_ref(),
2118         });
2119     }
2120
2121     cmd.linker_plugin_lto();
2122
2123     add_library_search_dirs(cmd, sess, self_contained);
2124
2125     cmd.output_filename(out_filename);
2126
2127     if crate_type == CrateType::Executable && sess.target.is_like_windows {
2128         if let Some(ref s) = codegen_results.crate_info.windows_subsystem {
2129             cmd.subsystem(s);
2130         }
2131     }
2132
2133     // Try to strip as much out of the generated object by removing unused
2134     // sections if possible. See more comments in linker.rs
2135     if !sess.link_dead_code() {
2136         // If PGO is enabled sometimes gc_sections will remove the profile data section
2137         // as it appears to be unused. This can then cause the PGO profile file to lose
2138         // some functions. If we are generating a profile we shouldn't strip those metadata
2139         // sections to ensure we have all the data for PGO.
2140         let keep_metadata =
2141             crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2142         if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2143         {
2144             cmd.gc_sections(keep_metadata);
2145         } else {
2146             cmd.no_gc_sections();
2147         }
2148     }
2149
2150     cmd.set_output_kind(link_output_kind, out_filename);
2151
2152     add_relro_args(cmd, sess);
2153
2154     // Pass optimization flags down to the linker.
2155     cmd.optimize();
2156
2157     // Gather the set of NatVis files, if any, and write them out to a temp directory.
2158     let natvis_visualizers = collect_natvis_visualizers(
2159         tmpdir,
2160         sess,
2161         &codegen_results.crate_info.local_crate_name,
2162         &codegen_results.crate_info.natvis_debugger_visualizers,
2163     );
2164
2165     // Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2166     cmd.debuginfo(strip_value(sess), &natvis_visualizers);
2167
2168     // We want to prevent the compiler from accidentally leaking in any system libraries,
2169     // so by default we tell linkers not to link to any default libraries.
2170     if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2171         cmd.no_default_libraries();
2172     }
2173
2174     if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2175         cmd.pgo_gen();
2176     }
2177
2178     if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2179         cmd.control_flow_guard();
2180     }
2181
2182     add_rpath_args(cmd, sess, codegen_results, out_filename);
2183 }
2184
2185 // Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2186 fn collect_natvis_visualizers(
2187     tmpdir: &Path,
2188     sess: &Session,
2189     crate_name: &Symbol,
2190     natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2191 ) -> Vec<PathBuf> {
2192     let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2193
2194     for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2195         let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2196
2197         match fs::write(&visualizer_out_file, &visualizer.src) {
2198             Ok(()) => {
2199                 visualizer_paths.push(visualizer_out_file);
2200             }
2201             Err(error) => {
2202                 sess.warn(
2203                     format!(
2204                         "Unable to write debugger visualizer file `{}`: {} ",
2205                         visualizer_out_file.display(),
2206                         error
2207                     )
2208                     .as_str(),
2209                 );
2210             }
2211         };
2212     }
2213     visualizer_paths
2214 }
2215
2216 /// # Native library linking
2217 ///
2218 /// User-supplied library search paths (-L on the command line). These are the same paths used to
2219 /// find Rust crates, so some of them may have been added already by the previous crate linking
2220 /// code. This only allows them to be found at compile time so it is still entirely up to outside
2221 /// forces to make sure that library can be found at runtime.
2222 ///
2223 /// Also note that the native libraries linked here are only the ones located in the current crate.
2224 /// Upstream crates with native library dependencies may have their native library pulled in above.
2225 fn add_local_native_libraries(
2226     cmd: &mut dyn Linker,
2227     sess: &Session,
2228     codegen_results: &CodegenResults,
2229 ) {
2230     let filesearch = sess.target_filesearch(PathKind::All);
2231     for search_path in filesearch.search_paths() {
2232         match search_path.kind {
2233             PathKind::Framework => {
2234                 cmd.framework_path(&search_path.dir);
2235             }
2236             _ => {
2237                 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
2238             }
2239         }
2240     }
2241
2242     let relevant_libs =
2243         codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
2244
2245     let search_path = OnceCell::new();
2246     let mut last = (None, NativeLibKind::Unspecified, None);
2247     for lib in relevant_libs {
2248         let Some(name) = lib.name else {
2249             continue;
2250         };
2251         let name = name.as_str();
2252
2253         // Skip if this library is the same as the last.
2254         last = if (lib.name, lib.kind, lib.verbatim) == last {
2255             continue;
2256         } else {
2257             (lib.name, lib.kind, lib.verbatim)
2258         };
2259
2260         let verbatim = lib.verbatim.unwrap_or(false);
2261         match lib.kind {
2262             NativeLibKind::Dylib { as_needed } => {
2263                 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2264             }
2265             NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
2266             NativeLibKind::Framework { as_needed } => {
2267                 cmd.link_framework(name, as_needed.unwrap_or(true))
2268             }
2269             NativeLibKind::Static { whole_archive, bundle, .. } => {
2270                 if whole_archive == Some(true)
2271                     // Backward compatibility case: this can be a rlib (so `+whole-archive` cannot
2272                     // be added explicitly if necessary, see the error in `fn link_rlib`) compiled
2273                     // as an executable due to `--test`. Use whole-archive implicitly, like before
2274                     // the introduction of native lib modifiers.
2275                     || (whole_archive == None && bundle != Some(false) && sess.opts.test)
2276                 {
2277                     cmd.link_whole_staticlib(
2278                         name,
2279                         verbatim,
2280                         &search_path.get_or_init(|| archive_search_paths(sess)),
2281                     );
2282                 } else {
2283                     cmd.link_staticlib(name, verbatim)
2284                 }
2285             }
2286             NativeLibKind::RawDylib => {
2287                 // Ignore RawDylib here, they are handled separately in linker_with_args().
2288             }
2289             NativeLibKind::LinkArg => {
2290                 cmd.arg(name);
2291             }
2292         }
2293     }
2294 }
2295
2296 /// # Linking Rust crates and their non-bundled static libraries
2297 ///
2298 /// Rust crates are not considered at all when creating an rlib output. All dependencies will be
2299 /// linked when producing the final output (instead of the intermediate rlib version).
2300 fn add_upstream_rust_crates<'a>(
2301     cmd: &mut dyn Linker,
2302     sess: &'a Session,
2303     archive_builder_builder: &dyn ArchiveBuilderBuilder,
2304     codegen_results: &CodegenResults,
2305     crate_type: CrateType,
2306     tmpdir: &Path,
2307 ) {
2308     // All of the heavy lifting has previously been accomplished by the
2309     // dependency_format module of the compiler. This is just crawling the
2310     // output of that module, adding crates as necessary.
2311     //
2312     // Linking to a rlib involves just passing it to the linker (the linker
2313     // will slurp up the object files inside), and linking to a dynamic library
2314     // involves just passing the right -l flag.
2315
2316     let (_, data) = codegen_results
2317         .crate_info
2318         .dependency_formats
2319         .iter()
2320         .find(|(ty, _)| *ty == crate_type)
2321         .expect("failed to find crate type in dependency format list");
2322
2323     // Invoke get_used_crates to ensure that we get a topological sorting of
2324     // crates.
2325     let deps = &codegen_results.crate_info.used_crates;
2326
2327     // There's a few internal crates in the standard library (aka libcore and
2328     // libstd) which actually have a circular dependence upon one another. This
2329     // currently arises through "weak lang items" where libcore requires things
2330     // like `rust_begin_unwind` but libstd ends up defining it. To get this
2331     // circular dependence to work correctly in all situations we'll need to be
2332     // sure to correctly apply the `--start-group` and `--end-group` options to
2333     // GNU linkers, otherwise if we don't use any other symbol from the standard
2334     // library it'll get discarded and the whole application won't link.
2335     //
2336     // In this loop we're calculating the `group_end`, after which crate to
2337     // pass `--end-group` and `group_start`, before which crate to pass
2338     // `--start-group`. We currently do this by passing `--end-group` after
2339     // the first crate (when iterating backwards) that requires a lang item
2340     // defined somewhere else. Once that's set then when we've defined all the
2341     // necessary lang items we'll pass `--start-group`.
2342     //
2343     // Note that this isn't amazing logic for now but it should do the trick
2344     // for the current implementation of the standard library.
2345     let mut group_end = None;
2346     let mut group_start = None;
2347     // Crates available for linking thus far.
2348     let mut available = FxHashSet::default();
2349     // Crates required to satisfy dependencies discovered so far.
2350     let mut required = FxHashSet::default();
2351
2352     let info = &codegen_results.crate_info;
2353     for &cnum in deps.iter().rev() {
2354         if let Some(missing) = info.missing_lang_items.get(&cnum) {
2355             let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
2356             required.extend(missing_crates);
2357         }
2358
2359         required.insert(Some(cnum));
2360         available.insert(Some(cnum));
2361
2362         if required.len() > available.len() && group_end.is_none() {
2363             group_end = Some(cnum);
2364         }
2365         if required.len() == available.len() && group_end.is_some() {
2366             group_start = Some(cnum);
2367             break;
2368         }
2369     }
2370
2371     // If we didn't end up filling in all lang items from upstream crates then
2372     // we'll be filling it in with our crate. This probably means we're the
2373     // standard library itself, so skip this for now.
2374     if group_end.is_some() && group_start.is_none() {
2375         group_end = None;
2376     }
2377
2378     let mut compiler_builtins = None;
2379     let search_path = OnceCell::new();
2380
2381     for &cnum in deps.iter() {
2382         if group_start == Some(cnum) {
2383             cmd.group_start();
2384         }
2385
2386         // We may not pass all crates through to the linker. Some crates may
2387         // appear statically in an existing dylib, meaning we'll pick up all the
2388         // symbols from the dylib.
2389         let src = &codegen_results.crate_info.used_crate_source[&cnum];
2390         match data[cnum.as_usize() - 1] {
2391             _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
2392                 add_static_crate(cmd, sess, archive_builder_builder, codegen_results, tmpdir, cnum);
2393             }
2394             // compiler-builtins are always placed last to ensure that they're
2395             // linked correctly.
2396             _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
2397                 assert!(compiler_builtins.is_none());
2398                 compiler_builtins = Some(cnum);
2399             }
2400             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
2401             Linkage::Static => {
2402                 add_static_crate(cmd, sess, archive_builder_builder, codegen_results, tmpdir, cnum);
2403
2404                 // Link static native libs with "-bundle" modifier only if the crate they originate from
2405                 // is being linked statically to the current crate.  If it's linked dynamically
2406                 // or is an rlib already included via some other dylib crate, the symbols from
2407                 // native libs will have already been included in that dylib.
2408                 //
2409                 // If -Zlink-native-libraries=false is set, then the assumption is that an
2410                 // external build system already has the native dependencies defined, and it
2411                 // will provide them to the linker itself.
2412                 if sess.opts.unstable_opts.link_native_libraries {
2413                     let mut last = (None, NativeLibKind::Unspecified, None);
2414                     for lib in &codegen_results.crate_info.native_libraries[&cnum] {
2415                         let Some(name) = lib.name else {
2416                             continue;
2417                         };
2418                         let name = name.as_str();
2419                         if !relevant_lib(sess, lib) {
2420                             continue;
2421                         }
2422
2423                         // Skip if this library is the same as the last.
2424                         last = if (lib.name, lib.kind, lib.verbatim) == last {
2425                             continue;
2426                         } else {
2427                             (lib.name, lib.kind, lib.verbatim)
2428                         };
2429
2430                         match lib.kind {
2431                             NativeLibKind::Static {
2432                                 bundle: Some(false),
2433                                 whole_archive: Some(true),
2434                             } => {
2435                                 cmd.link_whole_staticlib(
2436                                     name,
2437                                     lib.verbatim.unwrap_or(false),
2438                                     search_path.get_or_init(|| archive_search_paths(sess)),
2439                                 );
2440                             }
2441                             NativeLibKind::Static {
2442                                 bundle: Some(false),
2443                                 whole_archive: Some(false) | None,
2444                             } => {
2445                                 cmd.link_staticlib(name, lib.verbatim.unwrap_or(false));
2446                             }
2447                             NativeLibKind::LinkArg => {
2448                                 cmd.arg(name);
2449                             }
2450                             NativeLibKind::Dylib { .. }
2451                             | NativeLibKind::Framework { .. }
2452                             | NativeLibKind::Unspecified
2453                             | NativeLibKind::RawDylib => {}
2454                             NativeLibKind::Static {
2455                                 bundle: Some(true) | None,
2456                                 whole_archive: _,
2457                             } => {}
2458                         }
2459                     }
2460                 }
2461             }
2462             Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
2463         }
2464
2465         if group_end == Some(cnum) {
2466             cmd.group_end();
2467         }
2468     }
2469
2470     // compiler-builtins are always placed last to ensure that they're
2471     // linked correctly.
2472     // We must always link the `compiler_builtins` crate statically. Even if it
2473     // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
2474     // is used)
2475     if let Some(cnum) = compiler_builtins {
2476         add_static_crate(cmd, sess, archive_builder_builder, codegen_results, tmpdir, cnum);
2477     }
2478
2479     // Converts a library file-stem into a cc -l argument
2480     fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
2481         if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
2482     }
2483
2484     // Adds the static "rlib" versions of all crates to the command line.
2485     // There's a bit of magic which happens here specifically related to LTO,
2486     // namely that we remove upstream object files.
2487     //
2488     // When performing LTO, almost(*) all of the bytecode from the upstream
2489     // libraries has already been included in our object file output. As a
2490     // result we need to remove the object files in the upstream libraries so
2491     // the linker doesn't try to include them twice (or whine about duplicate
2492     // symbols). We must continue to include the rest of the rlib, however, as
2493     // it may contain static native libraries which must be linked in.
2494     //
2495     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
2496     // their bytecode wasn't included. The object files in those libraries must
2497     // still be passed to the linker.
2498     //
2499     // Note, however, that if we're not doing LTO we can just pass the rlib
2500     // blindly to the linker (fast) because it's fine if it's not actually
2501     // included as we're at the end of the dependency chain.
2502     fn add_static_crate<'a>(
2503         cmd: &mut dyn Linker,
2504         sess: &'a Session,
2505         archive_builder_builder: &dyn ArchiveBuilderBuilder,
2506         codegen_results: &CodegenResults,
2507         tmpdir: &Path,
2508         cnum: CrateNum,
2509     ) {
2510         let src = &codegen_results.crate_info.used_crate_source[&cnum];
2511         let cratepath = &src.rlib.as_ref().unwrap().0;
2512
2513         let mut link_upstream = |path: &Path| {
2514             cmd.link_rlib(&fix_windows_verbatim_for_gcc(path));
2515         };
2516
2517         // See the comment above in `link_staticlib` and `link_rlib` for why if
2518         // there's a static library that's not relevant we skip all object
2519         // files.
2520         let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
2521         let skip_native = native_libs.iter().any(|lib| {
2522             matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
2523                 && !relevant_lib(sess, lib)
2524         });
2525
2526         if (!are_upstream_rust_objects_already_included(sess)
2527             || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
2528             && !skip_native
2529         {
2530             link_upstream(cratepath);
2531             return;
2532         }
2533
2534         let dst = tmpdir.join(cratepath.file_name().unwrap());
2535         let name = cratepath.file_name().unwrap().to_str().unwrap();
2536         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2537
2538         sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2539             let canonical_name = name.replace('-', "_");
2540             let upstream_rust_objects_already_included =
2541                 are_upstream_rust_objects_already_included(sess);
2542             let is_builtins = sess.target.no_builtins
2543                 || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2544
2545             let mut archive = archive_builder_builder.new_archive_builder(sess);
2546             if let Err(e) = archive.add_archive(
2547                 cratepath,
2548                 Box::new(move |f| {
2549                     if f == METADATA_FILENAME {
2550                         return true;
2551                     }
2552
2553                     let canonical = f.replace('-', "_");
2554
2555                     let is_rust_object =
2556                         canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2557
2558                     // If we've been requested to skip all native object files
2559                     // (those not generated by the rust compiler) then we can skip
2560                     // this file. See above for why we may want to do this.
2561                     let skip_because_cfg_say_so = skip_native && !is_rust_object;
2562
2563                     // If we're performing LTO and this is a rust-generated object
2564                     // file, then we don't need the object file as it's part of the
2565                     // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2566                     // though, so we let that object file slide.
2567                     let skip_because_lto =
2568                         upstream_rust_objects_already_included && is_rust_object && is_builtins;
2569
2570                     if skip_because_cfg_say_so || skip_because_lto {
2571                         return true;
2572                     }
2573
2574                     false
2575                 }),
2576             ) {
2577                 sess.fatal(&format!("failed to build archive from rlib: {}", e));
2578             }
2579             if archive.build(&dst) {
2580                 link_upstream(&dst);
2581             }
2582         });
2583     }
2584
2585     // Same thing as above, but for dynamic crates instead of static crates.
2586     fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2587         // Just need to tell the linker about where the library lives and
2588         // what its name is
2589         let parent = cratepath.parent();
2590         if let Some(dir) = parent {
2591             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2592         }
2593         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2594         cmd.link_rust_dylib(
2595             &unlib(&sess.target, filestem),
2596             parent.unwrap_or_else(|| Path::new("")),
2597         );
2598     }
2599 }
2600
2601 /// Link in all of our upstream crates' native dependencies. Remember that all of these upstream
2602 /// native dependencies are all non-static dependencies. We've got two cases then:
2603 ///
2604 /// 1. The upstream crate is an rlib. In this case we *must* link in the native dependency because
2605 /// the rlib is just an archive.
2606 ///
2607 /// 2. The upstream crate is a dylib. In order to use the dylib, we have to have the dependency
2608 /// present on the system somewhere. Thus, we don't gain a whole lot from not linking in the
2609 /// dynamic dependency to this crate as well.
2610 ///
2611 /// The use case for this is a little subtle. In theory the native dependencies of a crate are
2612 /// purely an implementation detail of the crate itself, but the problem arises with generic and
2613 /// inlined functions. If a generic function calls a native function, then the generic function
2614 /// must be instantiated in the target crate, meaning that the native symbol must also be resolved
2615 /// in the target crate.
2616 fn add_upstream_native_libraries(
2617     cmd: &mut dyn Linker,
2618     sess: &Session,
2619     codegen_results: &CodegenResults,
2620 ) {
2621     let mut last = (None, NativeLibKind::Unspecified, None);
2622     for &cnum in &codegen_results.crate_info.used_crates {
2623         for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2624             let Some(name) = lib.name else {
2625                 continue;
2626             };
2627             let name = name.as_str();
2628             if !relevant_lib(sess, &lib) {
2629                 continue;
2630             }
2631
2632             // Skip if this library is the same as the last.
2633             last = if (lib.name, lib.kind, lib.verbatim) == last {
2634                 continue;
2635             } else {
2636                 (lib.name, lib.kind, lib.verbatim)
2637             };
2638
2639             let verbatim = lib.verbatim.unwrap_or(false);
2640             match lib.kind {
2641                 NativeLibKind::Dylib { as_needed } => {
2642                     cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2643                 }
2644                 NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
2645                 NativeLibKind::Framework { as_needed } => {
2646                     cmd.link_framework(name, as_needed.unwrap_or(true))
2647                 }
2648                 // ignore static native libraries here as we've
2649                 // already included them in add_local_native_libraries and
2650                 // add_upstream_rust_crates
2651                 NativeLibKind::Static { .. } => {}
2652                 NativeLibKind::RawDylib | NativeLibKind::LinkArg => {}
2653             }
2654         }
2655     }
2656 }
2657
2658 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2659     match lib.cfg {
2660         Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, CRATE_NODE_ID, None),
2661         None => true,
2662     }
2663 }
2664
2665 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2666     match sess.lto() {
2667         config::Lto::Fat => true,
2668         config::Lto::Thin => {
2669             // If we defer LTO to the linker, we haven't run LTO ourselves, so
2670             // any upstream object files have not been copied yet.
2671             !sess.opts.cg.linker_plugin_lto.enabled()
2672         }
2673         config::Lto::No | config::Lto::ThinLocal => false,
2674     }
2675 }
2676
2677 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2678     let arch = &sess.target.arch;
2679     let os = &sess.target.os;
2680     let llvm_target = &sess.target.llvm_target;
2681     if sess.target.vendor != "apple"
2682         || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "macos")
2683         || (flavor != LinkerFlavor::Gcc && flavor != LinkerFlavor::Lld(LldFlavor::Ld64))
2684     {
2685         return;
2686     }
2687
2688     if os == "macos" && flavor != LinkerFlavor::Lld(LldFlavor::Ld64) {
2689         return;
2690     }
2691
2692     let sdk_name = match (arch.as_ref(), os.as_ref()) {
2693         ("aarch64", "tvos") => "appletvos",
2694         ("x86_64", "tvos") => "appletvsimulator",
2695         ("arm", "ios") => "iphoneos",
2696         ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2697         ("aarch64", "ios") if llvm_target.ends_with("-simulator") => "iphonesimulator",
2698         ("aarch64", "ios") => "iphoneos",
2699         ("x86", "ios") => "iphonesimulator",
2700         ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2701         ("x86_64", "ios") => "iphonesimulator",
2702         ("x86_64", "watchos") => "watchsimulator",
2703         ("arm64_32", "watchos") => "watchos",
2704         ("aarch64", "watchos") if llvm_target.ends_with("-simulator") => "watchsimulator",
2705         ("aarch64", "watchos") => "watchos",
2706         ("arm", "watchos") => "watchos",
2707         (_, "macos") => "macosx",
2708         _ => {
2709             sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2710             return;
2711         }
2712     };
2713     let sdk_root = match get_apple_sdk_root(sdk_name) {
2714         Ok(s) => s,
2715         Err(e) => {
2716             sess.err(&e);
2717             return;
2718         }
2719     };
2720
2721     match flavor {
2722         LinkerFlavor::Gcc => {
2723             cmd.args(&["-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2724         }
2725         LinkerFlavor::Lld(LldFlavor::Ld64) => {
2726             cmd.args(&["-syslibroot", &sdk_root]);
2727         }
2728         _ => unreachable!(),
2729     }
2730 }
2731
2732 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2733     // Following what clang does
2734     // (https://github.com/llvm/llvm-project/blob/
2735     // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2736     // to allow the SDK path to be set. (For clang, xcrun sets
2737     // SDKROOT; for rustc, the user or build system can set it, or we
2738     // can fall back to checking for xcrun on PATH.)
2739     if let Ok(sdkroot) = env::var("SDKROOT") {
2740         let p = Path::new(&sdkroot);
2741         match sdk_name {
2742             // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2743             "appletvos"
2744                 if sdkroot.contains("TVSimulator.platform")
2745                     || sdkroot.contains("MacOSX.platform") => {}
2746             "appletvsimulator"
2747                 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2748             "iphoneos"
2749                 if sdkroot.contains("iPhoneSimulator.platform")
2750                     || sdkroot.contains("MacOSX.platform") => {}
2751             "iphonesimulator"
2752                 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2753             }
2754             "macosx10.15"
2755                 if sdkroot.contains("iPhoneOS.platform")
2756                     || sdkroot.contains("iPhoneSimulator.platform") => {}
2757             "watchos"
2758                 if sdkroot.contains("WatchSimulator.platform")
2759                     || sdkroot.contains("MacOSX.platform") => {}
2760             "watchsimulator"
2761                 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2762             // Ignore `SDKROOT` if it's not a valid path.
2763             _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2764             _ => return Ok(sdkroot),
2765         }
2766     }
2767     let res =
2768         Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2769             |output| {
2770                 if output.status.success() {
2771                     Ok(String::from_utf8(output.stdout).unwrap())
2772                 } else {
2773                     let error = String::from_utf8(output.stderr);
2774                     let error = format!("process exit with error: {}", error.unwrap());
2775                     Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2776                 }
2777             },
2778         );
2779
2780     match res {
2781         Ok(output) => Ok(output.trim().to_string()),
2782         Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),
2783     }
2784 }
2785
2786 fn add_gcc_ld_path(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2787     if let Some(ld_impl) = sess.opts.unstable_opts.gcc_ld {
2788         if let LinkerFlavor::Gcc = flavor {
2789             match ld_impl {
2790                 LdImpl::Lld => {
2791                     let tools_path = sess.get_tools_search_paths(false);
2792                     let gcc_ld_dir = tools_path
2793                         .into_iter()
2794                         .map(|p| p.join("gcc-ld"))
2795                         .find(|p| {
2796                             p.join(if sess.host.is_like_windows { "ld.exe" } else { "ld" }).exists()
2797                         })
2798                         .unwrap_or_else(|| sess.fatal("rust-lld (as ld) not found"));
2799                     cmd.arg({
2800                         let mut arg = OsString::from("-B");
2801                         arg.push(gcc_ld_dir);
2802                         arg
2803                     });
2804                     cmd.arg(format!("-Wl,-rustc-lld-flavor={}", sess.target.lld_flavor.as_str()));
2805                 }
2806             }
2807         } else {
2808             sess.fatal("option `-Z gcc-ld` is used even though linker flavor is not gcc");
2809         }
2810     }
2811 }