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