]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/link.rs
Rollup merge of #80040 - tmiasko:always-lower-intrinsics, r=Dylan-DPC
[rust.git] / compiler / rustc_codegen_ssa / src / back / link.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::temp_dir::MaybeTempDir;
3 use rustc_fs_util::fix_windows_verbatim_for_gcc;
4 use rustc_hir::def_id::CrateNum;
5 use rustc_middle::middle::cstore::{EncodedMetadata, LibSource, NativeLib};
6 use rustc_middle::middle::dependency_format::Linkage;
7 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo};
8 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SanitizerSet};
9 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
10 use rustc_session::search_paths::PathKind;
11 use rustc_session::utils::NativeLibKind;
12 /// For all the linkers we support, and information they might
13 /// need out of the shared crate context before we get rid of it.
14 use rustc_session::{filesearch, Session};
15 use rustc_span::symbol::Symbol;
16 use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
17 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
18 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target};
19
20 use super::archive::ArchiveBuilder;
21 use super::command::Command;
22 use super::linker::{self, Linker};
23 use super::rpath::{self, RPathConfig};
24 use crate::{
25     looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, METADATA_FILENAME,
26 };
27
28 use cc::windows_registry;
29 use tempfile::Builder as TempFileBuilder;
30
31 use std::ffi::OsString;
32 use std::path::{Path, PathBuf};
33 use std::process::{ExitStatus, Output, Stdio};
34 use std::{ascii, char, env, fmt, fs, io, mem, str};
35
36 pub fn remove(sess: &Session, path: &Path) {
37     if let Err(e) = fs::remove_file(path) {
38         sess.err(&format!("failed to remove {}: {}", path.display(), e));
39     }
40 }
41
42 /// Performs the linkage portion of the compilation phase. This will generate all
43 /// of the requested outputs for this compilation session.
44 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
45     sess: &'a Session,
46     codegen_results: &CodegenResults,
47     outputs: &OutputFilenames,
48     crate_name: &str,
49     target_cpu: &str,
50 ) {
51     let _timer = sess.timer("link_binary");
52     let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
53     for &crate_type in sess.crate_types().iter() {
54         // Ignore executable crates if we have -Z no-codegen, as they will error.
55         if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
56             && !output_metadata
57             && crate_type == CrateType::Executable
58         {
59             continue;
60         }
61
62         if invalid_output_for_target(sess, crate_type) {
63             bug!(
64                 "invalid output type `{:?}` for target os `{}`",
65                 crate_type,
66                 sess.opts.target_triple
67             );
68         }
69
70         sess.time("link_binary_check_files_are_writeable", || {
71             for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
72                 check_file_is_writeable(obj, sess);
73             }
74         });
75
76         if outputs.outputs.should_codegen() {
77             let tmpdir = TempFileBuilder::new()
78                 .prefix("rustc")
79                 .tempdir()
80                 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
81             let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
82             let out_filename = out_filename(sess, crate_type, outputs, crate_name);
83             match crate_type {
84                 CrateType::Rlib => {
85                     let _timer = sess.timer("link_rlib");
86                     link_rlib::<B>(sess, codegen_results, RlibFlavor::Normal, &out_filename, &path)
87                         .build();
88                 }
89                 CrateType::Staticlib => {
90                     link_staticlib::<B>(sess, codegen_results, &out_filename, &path);
91                 }
92                 _ => {
93                     link_natively::<B>(
94                         sess,
95                         crate_type,
96                         &out_filename,
97                         codegen_results,
98                         path.as_ref(),
99                         target_cpu,
100                     );
101                     if sess.opts.debugging_opts.split_dwarf == config::SplitDwarfKind::Split {
102                         link_dwarf_object(sess, &out_filename);
103                     }
104                 }
105             }
106             if sess.opts.json_artifact_notifications {
107                 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
108             }
109         }
110     }
111
112     // Remove the temporary object file and metadata if we aren't saving temps
113     sess.time("link_binary_remove_temps", || {
114         if !sess.opts.cg.save_temps {
115             let remove_temps_from_module = |module: &CompiledModule| {
116                 if let Some(ref obj) = module.object {
117                     remove(sess, obj);
118                 }
119
120                 if let Some(ref obj) = module.dwarf_object {
121                     remove(sess, obj);
122                 }
123             };
124
125             if sess.opts.output_types.should_codegen()
126                 && !preserve_objects_for_their_debuginfo(sess)
127             {
128                 for module in &codegen_results.modules {
129                     remove_temps_from_module(module);
130                 }
131             }
132
133             if let Some(ref metadata_module) = codegen_results.metadata_module {
134                 remove_temps_from_module(metadata_module);
135             }
136
137             if let Some(ref allocator_module) = codegen_results.allocator_module {
138                 remove_temps_from_module(allocator_module);
139             }
140         }
141     });
142 }
143
144 // The third parameter is for env vars, used on windows to set up the
145 // path for MSVC to find its DLLs, and gcc to find its bundled
146 // toolchain
147 fn get_linker(
148     sess: &Session,
149     linker: &Path,
150     flavor: LinkerFlavor,
151     self_contained: bool,
152 ) -> Command {
153     let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
154
155     // If our linker looks like a batch script on Windows then to execute this
156     // we'll need to spawn `cmd` explicitly. This is primarily done to handle
157     // emscripten where the linker is `emcc.bat` and needs to be spawned as
158     // `cmd /c emcc.bat ...`.
159     //
160     // This worked historically but is needed manually since #42436 (regression
161     // was tagged as #42791) and some more info can be found on #44443 for
162     // emscripten itself.
163     let mut cmd = match linker.to_str() {
164         Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
165         _ => match flavor {
166             LinkerFlavor::Lld(f) => Command::lld(linker, f),
167             LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
168                 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
169             }
170             _ => Command::new(linker),
171         },
172     };
173
174     // UWP apps have API restrictions enforced during Store submissions.
175     // To comply with the Windows App Certification Kit,
176     // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
177     let t = &sess.target;
178     if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
179         && t.vendor == "uwp"
180     {
181         if let Some(ref tool) = msvc_tool {
182             let original_path = tool.path();
183             if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
184                 let arch = match t.arch.as_str() {
185                     "x86_64" => Some("x64".to_string()),
186                     "x86" => Some("x86".to_string()),
187                     "aarch64" => Some("arm64".to_string()),
188                     "arm" => Some("arm".to_string()),
189                     _ => None,
190                 };
191                 if let Some(ref a) = arch {
192                     // FIXME: Move this to `fn linker_with_args`.
193                     let mut arg = OsString::from("/LIBPATH:");
194                     arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
195                     cmd.arg(&arg);
196                 } else {
197                     warn!("arch is not supported");
198                 }
199             } else {
200                 warn!("MSVC root path lib location not found");
201             }
202         } else {
203             warn!("link.exe not found");
204         }
205     }
206
207     // The compiler's sysroot often has some bundled tools, so add it to the
208     // PATH for the child.
209     let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(self_contained);
210     let mut msvc_changed_path = false;
211     if sess.target.is_like_msvc {
212         if let Some(ref tool) = msvc_tool {
213             cmd.args(tool.args());
214             for &(ref k, ref v) in tool.env() {
215                 if k == "PATH" {
216                     new_path.extend(env::split_paths(v));
217                     msvc_changed_path = true;
218                 } else {
219                     cmd.env(k, v);
220                 }
221             }
222         }
223     }
224
225     if !msvc_changed_path {
226         if let Some(path) = env::var_os("PATH") {
227             new_path.extend(env::split_paths(&path));
228         }
229     }
230     cmd.env("PATH", env::join_paths(new_path).unwrap());
231
232     cmd
233 }
234
235 pub fn each_linked_rlib(
236     info: &CrateInfo,
237     f: &mut dyn FnMut(CrateNum, &Path),
238 ) -> Result<(), String> {
239     let crates = info.used_crates_static.iter();
240     let mut fmts = None;
241     for (ty, list) in info.dependency_formats.iter() {
242         match ty {
243             CrateType::Executable
244             | CrateType::Staticlib
245             | CrateType::Cdylib
246             | CrateType::ProcMacro => {
247                 fmts = Some(list);
248                 break;
249             }
250             _ => {}
251         }
252     }
253     let fmts = match fmts {
254         Some(f) => f,
255         None => return Err("could not find formats for rlibs".to_string()),
256     };
257     for &(cnum, ref path) in crates {
258         match fmts.get(cnum.as_usize() - 1) {
259             Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
260             Some(_) => {}
261             None => return Err("could not find formats for rlibs".to_string()),
262         }
263         let name = &info.crate_name[&cnum];
264         let path = match *path {
265             LibSource::Some(ref p) => p,
266             LibSource::MetadataOnly => {
267                 return Err(format!(
268                     "could not find rlib for: `{}`, found rmeta (metadata) file",
269                     name
270                 ));
271             }
272             LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
273         };
274         f(cnum, &path);
275     }
276     Ok(())
277 }
278
279 /// We use a temp directory here to avoid races between concurrent rustc processes,
280 /// such as builds in the same directory using the same filename for metadata while
281 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
282 /// directory being searched for `extern crate` (observing an incomplete file).
283 /// The returned path is the temporary file containing the complete metadata.
284 pub fn emit_metadata(sess: &Session, metadata: &EncodedMetadata, tmpdir: &MaybeTempDir) -> PathBuf {
285     let out_filename = tmpdir.as_ref().join(METADATA_FILENAME);
286     let result = fs::write(&out_filename, &metadata.raw_data);
287
288     if let Err(e) = result {
289         sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
290     }
291
292     out_filename
293 }
294
295 /// Create an 'rlib'.
296 ///
297 /// An rlib in its current incarnation is essentially a renamed .a file. The rlib primarily contains
298 /// the object file of the crate, but it also contains all of the object files from native
299 /// libraries. This is done by unzipping native libraries and inserting all of the contents into
300 /// this archive.
301 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
302     sess: &'a Session,
303     codegen_results: &CodegenResults,
304     flavor: RlibFlavor,
305     out_filename: &Path,
306     tmpdir: &MaybeTempDir,
307 ) -> B {
308     info!("preparing rlib to {:?}", out_filename);
309     let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
310
311     for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
312         ab.add_file(obj);
313     }
314
315     // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
316     // we may not be configured to actually include a static library if we're
317     // adding it here. That's because later when we consume this rlib we'll
318     // decide whether we actually needed the static library or not.
319     //
320     // To do this "correctly" we'd need to keep track of which libraries added
321     // which object files to the archive. We don't do that here, however. The
322     // #[link(cfg(..))] feature is unstable, though, and only intended to get
323     // liblibc working. In that sense the check below just indicates that if
324     // there are any libraries we want to omit object files for at link time we
325     // just exclude all custom object files.
326     //
327     // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
328     // feature then we'll need to figure out how to record what objects were
329     // loaded from the libraries found here and then encode that into the
330     // metadata of the rlib we're generating somehow.
331     for lib in codegen_results.crate_info.used_libraries.iter() {
332         match lib.kind {
333             NativeLibKind::StaticBundle => {}
334             NativeLibKind::StaticNoBundle
335             | NativeLibKind::Dylib
336             | NativeLibKind::Framework
337             | NativeLibKind::RawDylib
338             | NativeLibKind::Unspecified => continue,
339         }
340         if let Some(name) = lib.name {
341             ab.add_native_library(name);
342         }
343     }
344
345     // After adding all files to the archive, we need to update the
346     // symbol table of the archive.
347     ab.update_symbols();
348
349     // Note that it is important that we add all of our non-object "magical
350     // files" *after* all of the object files in the archive. The reason for
351     // this is as follows:
352     //
353     // * When performing LTO, this archive will be modified to remove
354     //   objects from above. The reason for this is described below.
355     //
356     // * When the system linker looks at an archive, it will attempt to
357     //   determine the architecture of the archive in order to see whether its
358     //   linkable.
359     //
360     //   The algorithm for this detection is: iterate over the files in the
361     //   archive. Skip magical SYMDEF names. Interpret the first file as an
362     //   object file. Read architecture from the object file.
363     //
364     // * As one can probably see, if "metadata" and "foo.bc" were placed
365     //   before all of the objects, then the architecture of this archive would
366     //   not be correctly inferred once 'foo.o' is removed.
367     //
368     // Basically, all this means is that this code should not move above the
369     // code above.
370     match flavor {
371         RlibFlavor::Normal => {
372             // Instead of putting the metadata in an object file section, rlibs
373             // contain the metadata in a separate file.
374             ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
375
376             // After adding all files to the archive, we need to update the
377             // symbol table of the archive. This currently dies on macOS (see
378             // #11162), and isn't necessary there anyway
379             if !sess.target.is_like_osx {
380                 ab.update_symbols();
381             }
382         }
383
384         RlibFlavor::StaticlibBase => {
385             let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
386             if let Some(obj) = obj {
387                 ab.add_file(obj);
388             }
389         }
390     }
391
392     ab
393 }
394
395 /// Create a static archive.
396 ///
397 /// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
398 /// crates' objects into the archive. This will slurp in all of the native libraries of upstream
399 /// dependencies as well.
400 ///
401 /// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
402 /// library dependencies that they're not linked in.
403 ///
404 /// There's no need to include metadata in a static archive, so ensure to not link in the metadata
405 /// object file (and also don't prepare the archive with a metadata file).
406 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
407     sess: &'a Session,
408     codegen_results: &CodegenResults,
409     out_filename: &Path,
410     tempdir: &MaybeTempDir,
411 ) {
412     let mut ab =
413         link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
414     let mut all_native_libs = vec![];
415
416     let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
417         let name = &codegen_results.crate_info.crate_name[&cnum];
418         let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
419
420         // Here when we include the rlib into our staticlib we need to make a
421         // decision whether to include the extra object files along the way.
422         // These extra object files come from statically included native
423         // libraries, but they may be cfg'd away with #[link(cfg(..))].
424         //
425         // This unstable feature, though, only needs liblibc to work. The only
426         // use case there is where musl is statically included in liblibc.rlib,
427         // so if we don't want the included version we just need to skip it. As
428         // a result the logic here is that if *any* linked library is cfg'd away
429         // we just skip all object files.
430         //
431         // Clearly this is not sufficient for a general purpose feature, and
432         // we'd want to read from the library's metadata to determine which
433         // object files come from where and selectively skip them.
434         let skip_object_files = native_libs
435             .iter()
436             .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
437         ab.add_rlib(
438             path,
439             &name.as_str(),
440             are_upstream_rust_objects_already_included(sess)
441                 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
442             skip_object_files,
443         )
444         .unwrap();
445
446         all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
447     });
448     if let Err(e) = res {
449         sess.fatal(&e);
450     }
451
452     ab.update_symbols();
453     ab.build();
454
455     if !all_native_libs.is_empty() {
456         if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
457             print_native_static_libs(sess, &all_native_libs);
458         }
459     }
460 }
461
462 fn escape_stdout_stderr_string(s: &[u8]) -> String {
463     str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
464         let mut x = "Non-UTF-8 output: ".to_string();
465         x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
466         x
467     })
468 }
469
470 const LLVM_DWP_EXECUTABLE: &'static str = "rust-llvm-dwp";
471
472 /// Invoke `llvm-dwp` (shipped alongside rustc) to link `dwo` files from Split DWARF into a `dwp`
473 /// file.
474 fn link_dwarf_object<'a>(sess: &'a Session, executable_out_filename: &Path) {
475     info!("preparing dwp to {}.dwp", executable_out_filename.to_str().unwrap());
476
477     let dwp_out_filename = executable_out_filename.with_extension("dwp");
478     let mut cmd = Command::new(LLVM_DWP_EXECUTABLE);
479     cmd.arg("-e");
480     cmd.arg(executable_out_filename);
481     cmd.arg("-o");
482     cmd.arg(&dwp_out_filename);
483
484     let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false);
485     if let Some(path) = env::var_os("PATH") {
486         new_path.extend(env::split_paths(&path));
487     }
488     let new_path = env::join_paths(new_path).unwrap();
489     cmd.env("PATH", new_path);
490
491     info!("{:?}", &cmd);
492     match sess.time("run_dwp", || cmd.output()) {
493         Ok(prog) if !prog.status.success() => {
494             sess.struct_err(&format!(
495                 "linking dwarf objects with `{}` failed: {}",
496                 LLVM_DWP_EXECUTABLE, prog.status
497             ))
498             .note(&format!("{:?}", &cmd))
499             .note(&escape_stdout_stderr_string(&prog.stdout))
500             .note(&escape_stdout_stderr_string(&prog.stderr))
501             .emit();
502             info!("linker stderr:\n{}", escape_stdout_stderr_string(&prog.stderr));
503             info!("linker stdout:\n{}", escape_stdout_stderr_string(&prog.stdout));
504         }
505         Ok(_) => {}
506         Err(e) => {
507             let dwp_not_found = e.kind() == io::ErrorKind::NotFound;
508             let mut err = if dwp_not_found {
509                 sess.struct_err(&format!("linker `{}` not found", LLVM_DWP_EXECUTABLE))
510             } else {
511                 sess.struct_err(&format!("could not exec the linker `{}`", LLVM_DWP_EXECUTABLE))
512             };
513
514             err.note(&e.to_string());
515
516             if !dwp_not_found {
517                 err.note(&format!("{:?}", &cmd));
518             }
519
520             err.emit();
521         }
522     }
523 }
524
525 /// Create a dynamic library or executable.
526 ///
527 /// This will invoke the system linker/cc to create the resulting file. This links to all upstream
528 /// files as well.
529 fn link_natively<'a, B: ArchiveBuilder<'a>>(
530     sess: &'a Session,
531     crate_type: CrateType,
532     out_filename: &Path,
533     codegen_results: &CodegenResults,
534     tmpdir: &Path,
535     target_cpu: &str,
536 ) {
537     info!("preparing {:?} to {:?}", crate_type, out_filename);
538     let (linker_path, flavor) = linker_and_flavor(sess);
539     let mut cmd = linker_with_args::<B>(
540         &linker_path,
541         flavor,
542         sess,
543         crate_type,
544         tmpdir,
545         out_filename,
546         codegen_results,
547         target_cpu,
548     );
549
550     linker::disable_localization(&mut cmd);
551
552     for &(ref k, ref v) in &sess.target.link_env {
553         cmd.env(k, v);
554     }
555     for k in &sess.target.link_env_remove {
556         cmd.env_remove(k);
557     }
558
559     if sess.opts.debugging_opts.print_link_args {
560         println!("{:?}", &cmd);
561     }
562
563     // May have not found libraries in the right formats.
564     sess.abort_if_errors();
565
566     // Invoke the system linker
567     info!("{:?}", &cmd);
568     let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
569     let mut prog;
570     let mut i = 0;
571     loop {
572         i += 1;
573         prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
574         let output = match prog {
575             Ok(ref output) => output,
576             Err(_) => break,
577         };
578         if output.status.success() {
579             break;
580         }
581         let mut out = output.stderr.clone();
582         out.extend(&output.stdout);
583         let out = String::from_utf8_lossy(&out);
584
585         // Check to see if the link failed with "unrecognized command line option:
586         // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
587         // reperform the link step without the -no-pie option. This is safe because
588         // if the linker doesn't support -no-pie then it should not default to
589         // linking executables as pie. Different versions of gcc seem to use
590         // different quotes in the error message so don't check for them.
591         if sess.target.linker_is_gnu
592             && flavor != LinkerFlavor::Ld
593             && (out.contains("unrecognized command line option")
594                 || out.contains("unknown argument"))
595             && out.contains("-no-pie")
596             && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
597         {
598             info!("linker output: {:?}", out);
599             warn!("Linker does not support -no-pie command line option. Retrying without.");
600             for arg in cmd.take_args() {
601                 if arg.to_string_lossy() != "-no-pie" {
602                     cmd.arg(arg);
603                 }
604             }
605             info!("{:?}", &cmd);
606             continue;
607         }
608
609         // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
610         // Fallback from '-static-pie' to '-static' in that case.
611         if sess.target.linker_is_gnu
612             && flavor != LinkerFlavor::Ld
613             && (out.contains("unrecognized command line option")
614                 || out.contains("unknown argument"))
615             && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
616             && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
617         {
618             info!("linker output: {:?}", out);
619             warn!(
620                 "Linker does not support -static-pie command line option. Retrying with -static instead."
621             );
622             // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
623             let self_contained = crt_objects_fallback(sess, crate_type);
624             let opts = &sess.target;
625             let pre_objects = if self_contained {
626                 &opts.pre_link_objects_fallback
627             } else {
628                 &opts.pre_link_objects
629             };
630             let post_objects = if self_contained {
631                 &opts.post_link_objects_fallback
632             } else {
633                 &opts.post_link_objects
634             };
635             let get_objects = |objects: &CrtObjects, kind| {
636                 objects
637                     .get(&kind)
638                     .iter()
639                     .copied()
640                     .flatten()
641                     .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
642                     .collect::<Vec<_>>()
643             };
644             let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
645             let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
646             let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
647             let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
648             // Assume that we know insertion positions for the replacement arguments from replaced
649             // arguments, which is true for all supported targets.
650             assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
651             assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
652             for arg in cmd.take_args() {
653                 if arg.to_string_lossy() == "-static-pie" {
654                     // Replace the output kind.
655                     cmd.arg("-static");
656                 } else if pre_objects_static_pie.contains(&arg) {
657                     // Replace the pre-link objects (replace the first and remove the rest).
658                     cmd.args(mem::take(&mut pre_objects_static));
659                 } else if post_objects_static_pie.contains(&arg) {
660                     // Replace the post-link objects (replace the first and remove the rest).
661                     cmd.args(mem::take(&mut post_objects_static));
662                 } else {
663                     cmd.arg(arg);
664                 }
665             }
666             info!("{:?}", &cmd);
667             continue;
668         }
669
670         // Here's a terribly awful hack that really shouldn't be present in any
671         // compiler. Here an environment variable is supported to automatically
672         // retry the linker invocation if the linker looks like it segfaulted.
673         //
674         // Gee that seems odd, normally segfaults are things we want to know
675         // about!  Unfortunately though in rust-lang/rust#38878 we're
676         // experiencing the linker segfaulting on Travis quite a bit which is
677         // causing quite a bit of pain to land PRs when they spuriously fail
678         // due to a segfault.
679         //
680         // The issue #38878 has some more debugging information on it as well,
681         // but this unfortunately looks like it's just a race condition in
682         // macOS's linker with some thread pool working in the background. It
683         // seems that no one currently knows a fix for this so in the meantime
684         // we're left with this...
685         if !retry_on_segfault || i > 3 {
686             break;
687         }
688         let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
689         let msg_bus = "clang: error: unable to execute command: Bus error: 10";
690         if out.contains(msg_segv) || out.contains(msg_bus) {
691             warn!(
692                 "looks like the linker segfaulted when we tried to call it, \
693                  automatically retrying again. cmd = {:?}, out = {}.",
694                 cmd, out,
695             );
696             continue;
697         }
698
699         if is_illegal_instruction(&output.status) {
700             warn!(
701                 "looks like the linker hit an illegal instruction when we \
702                  tried to call it, automatically retrying again. cmd = {:?}, ]\
703                  out = {}, status = {}.",
704                 cmd, out, output.status,
705             );
706             continue;
707         }
708
709         #[cfg(unix)]
710         fn is_illegal_instruction(status: &ExitStatus) -> bool {
711             use std::os::unix::prelude::*;
712             status.signal() == Some(libc::SIGILL)
713         }
714
715         #[cfg(windows)]
716         fn is_illegal_instruction(_status: &ExitStatus) -> bool {
717             false
718         }
719     }
720
721     fn escape_string(s: &[u8]) -> String {
722         str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
723             let mut x = "Non-UTF-8 output: ".to_string();
724             x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
725             x
726         })
727     }
728
729     match prog {
730         Ok(prog) => {
731             if !prog.status.success() {
732                 let mut output = prog.stderr.clone();
733                 output.extend_from_slice(&prog.stdout);
734                 sess.struct_err(&format!(
735                     "linking with `{}` failed: {}",
736                     linker_path.display(),
737                     prog.status
738                 ))
739                 .note(&format!("{:?}", &cmd))
740                 .note(&escape_stdout_stderr_string(&output))
741                 .emit();
742
743                 // If MSVC's `link.exe` was expected but the return code
744                 // is not a Microsoft LNK error then suggest a way to fix or
745                 // install the Visual Studio build tools.
746                 if let Some(code) = prog.status.code() {
747                     if sess.target.is_like_msvc
748                         && flavor == LinkerFlavor::Msvc
749                         // Respect the command line override
750                         && sess.opts.cg.linker.is_none()
751                         // Match exactly "link.exe"
752                         && linker_path.to_str() == Some("link.exe")
753                         // All Microsoft `link.exe` linking error codes are
754                         // four digit numbers in the range 1000 to 9999 inclusive
755                         && (code < 1000 || code > 9999)
756                     {
757                         let is_vs_installed = windows_registry::find_vs_version().is_ok();
758                         let has_linker = windows_registry::find_tool(
759                             &sess.opts.target_triple.triple(),
760                             "link.exe",
761                         )
762                         .is_some();
763
764                         sess.note_without_error("`link.exe` returned an unexpected error");
765                         if is_vs_installed && has_linker {
766                             // the linker is broken
767                             sess.note_without_error(
768                                 "the Visual Studio build tools may need to be repaired \
769                                 using the Visual Studio installer",
770                             );
771                             sess.note_without_error(
772                                 "or a necessary component may be missing from the \
773                                 \"C++ build tools\" workload",
774                             );
775                         } else if is_vs_installed {
776                             // the linker is not installed
777                             sess.note_without_error(
778                                 "in the Visual Studio installer, ensure the \
779                                 \"C++ build tools\" workload is selected",
780                             );
781                         } else {
782                             // visual studio is not installed
783                             sess.note_without_error(
784                                 "you may need to install Visual Studio build tools with the \
785                                 \"C++ build tools\" workload",
786                             );
787                         }
788                     }
789                 }
790
791                 sess.abort_if_errors();
792             }
793             info!("linker stderr:\n{}", escape_stdout_stderr_string(&prog.stderr));
794             info!("linker stdout:\n{}", escape_stdout_stderr_string(&prog.stdout));
795         }
796         Err(e) => {
797             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
798
799             let mut linker_error = {
800                 if linker_not_found {
801                     sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
802                 } else {
803                     sess.struct_err(&format!(
804                         "could not exec the linker `{}`",
805                         linker_path.display()
806                     ))
807                 }
808             };
809
810             linker_error.note(&e.to_string());
811
812             if !linker_not_found {
813                 linker_error.note(&format!("{:?}", &cmd));
814             }
815
816             linker_error.emit();
817
818             if sess.target.is_like_msvc && linker_not_found {
819                 sess.note_without_error(
820                     "the msvc targets depend on the msvc linker \
821                      but `link.exe` was not found",
822                 );
823                 sess.note_without_error(
824                     "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
825                      was installed with the Visual C++ option",
826                 );
827             }
828             sess.abort_if_errors();
829         }
830     }
831
832     // On macOS, debuggers need this utility to get run to do some munging of
833     // the symbols. Note, though, that if the object files are being preserved
834     // for their debug information there's no need for us to run dsymutil.
835     if sess.target.is_like_osx
836         && sess.opts.debuginfo != DebugInfo::None
837         && !preserve_objects_for_their_debuginfo(sess)
838     {
839         let prog = Command::new("dsymutil").arg(out_filename).output();
840         match prog {
841             Ok(prog) => {
842                 if !prog.status.success() {
843                     let mut output = prog.stderr.clone();
844                     output.extend_from_slice(&prog.stdout);
845                     sess.struct_warn(&format!(
846                         "processing debug info with `dsymutil` failed: {}",
847                         prog.status
848                     ))
849                     .note(&escape_string(&output))
850                     .emit();
851                 }
852             }
853             Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
854         }
855     }
856 }
857
858 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
859     // On macOS the runtimes are distributed as dylibs which should be linked to
860     // both executables and dynamic shared objects. Everywhere else the runtimes
861     // are currently distributed as static liraries which should be linked to
862     // executables only.
863     let needs_runtime = match crate_type {
864         CrateType::Executable => true,
865         CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
866         CrateType::Rlib | CrateType::Staticlib => false,
867     };
868
869     if !needs_runtime {
870         return;
871     }
872
873     let sanitizer = sess.opts.debugging_opts.sanitizer;
874     if sanitizer.contains(SanitizerSet::ADDRESS) {
875         link_sanitizer_runtime(sess, linker, "asan");
876     }
877     if sanitizer.contains(SanitizerSet::LEAK) {
878         link_sanitizer_runtime(sess, linker, "lsan");
879     }
880     if sanitizer.contains(SanitizerSet::MEMORY) {
881         link_sanitizer_runtime(sess, linker, "msan");
882     }
883     if sanitizer.contains(SanitizerSet::THREAD) {
884         link_sanitizer_runtime(sess, linker, "tsan");
885     }
886 }
887
888 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
889     let default_sysroot = filesearch::get_or_default_sysroot();
890     let default_tlib =
891         filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
892     let channel = option_env!("CFG_RELEASE_CHANNEL")
893         .map(|channel| format!("-{}", channel))
894         .unwrap_or_default();
895
896     match sess.opts.target_triple.triple() {
897         "x86_64-apple-darwin" => {
898             // On Apple platforms, the sanitizer is always built as a dylib, and
899             // LLVM will link to `@rpath/*.dylib`, so we need to specify an
900             // rpath to the library as well (the rpath should be absolute, see
901             // PR #41352 for details).
902             let libname = format!("rustc{}_rt.{}", channel, name);
903             let rpath = default_tlib.to_str().expect("non-utf8 component in path");
904             linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
905             linker.link_dylib(Symbol::intern(&libname));
906         }
907         "aarch64-fuchsia"
908         | "aarch64-unknown-linux-gnu"
909         | "x86_64-fuchsia"
910         | "x86_64-unknown-freebsd"
911         | "x86_64-unknown-linux-gnu" => {
912             let filename = format!("librustc{}_rt.{}.a", channel, name);
913             let path = default_tlib.join(&filename);
914             linker.link_whole_rlib(&path);
915         }
916         _ => {}
917     }
918 }
919
920 /// Returns a boolean indicating whether the specified crate should be ignored
921 /// during LTO.
922 ///
923 /// Crates ignored during LTO are not lumped together in the "massive object
924 /// file" that we create and are linked in their normal rlib states. See
925 /// comments below for what crates do not participate in LTO.
926 ///
927 /// It's unusual for a crate to not participate in LTO. Typically only
928 /// compiler-specific and unstable crates have a reason to not participate in
929 /// LTO.
930 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
931     // If our target enables builtin function lowering in LLVM then the
932     // crates providing these functions don't participate in LTO (e.g.
933     // no_builtins or compiler builtins crates).
934     !sess.target.no_builtins
935         && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
936 }
937
938 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
939     fn infer_from(
940         sess: &Session,
941         linker: Option<PathBuf>,
942         flavor: Option<LinkerFlavor>,
943     ) -> Option<(PathBuf, LinkerFlavor)> {
944         match (linker, flavor) {
945             (Some(linker), Some(flavor)) => Some((linker, flavor)),
946             // only the linker flavor is known; use the default linker for the selected flavor
947             (None, Some(flavor)) => Some((
948                 PathBuf::from(match flavor {
949                     LinkerFlavor::Em => {
950                         if cfg!(windows) {
951                             "emcc.bat"
952                         } else {
953                             "emcc"
954                         }
955                     }
956                     LinkerFlavor::Gcc => {
957                         if cfg!(any(target_os = "solaris", target_os = "illumos")) {
958                             // On historical Solaris systems, "cc" may have
959                             // been Sun Studio, which is not flag-compatible
960                             // with "gcc".  This history casts a long shadow,
961                             // and many modern illumos distributions today
962                             // ship GCC as "gcc" without also making it
963                             // available as "cc".
964                             "gcc"
965                         } else {
966                             "cc"
967                         }
968                     }
969                     LinkerFlavor::Ld => "ld",
970                     LinkerFlavor::Msvc => "link.exe",
971                     LinkerFlavor::Lld(_) => "lld",
972                     LinkerFlavor::PtxLinker => "rust-ptx-linker",
973                 }),
974                 flavor,
975             )),
976             (Some(linker), None) => {
977                 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
978                     sess.fatal("couldn't extract file stem from specified linker")
979                 });
980
981                 let flavor = if stem == "emcc" {
982                     LinkerFlavor::Em
983                 } else if stem == "gcc"
984                     || stem.ends_with("-gcc")
985                     || stem == "clang"
986                     || stem.ends_with("-clang")
987                 {
988                     LinkerFlavor::Gcc
989                 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
990                     LinkerFlavor::Ld
991                 } else if stem == "link" || stem == "lld-link" {
992                     LinkerFlavor::Msvc
993                 } else if stem == "lld" || stem == "rust-lld" {
994                     LinkerFlavor::Lld(sess.target.lld_flavor)
995                 } else {
996                     // fall back to the value in the target spec
997                     sess.target.linker_flavor
998                 };
999
1000                 Some((linker, flavor))
1001             }
1002             (None, None) => None,
1003         }
1004     }
1005
1006     // linker and linker flavor specified via command line have precedence over what the target
1007     // specification specifies
1008     if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
1009         return ret;
1010     }
1011
1012     if let Some(ret) = infer_from(
1013         sess,
1014         sess.target.linker.clone().map(PathBuf::from),
1015         Some(sess.target.linker_flavor),
1016     ) {
1017         return ret;
1018     }
1019
1020     bug!("Not enough information provided to determine how to invoke the linker");
1021 }
1022
1023 /// Returns a boolean indicating whether we should preserve the object files on
1024 /// the filesystem for their debug information. This is often useful with
1025 /// split-dwarf like schemes.
1026 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
1027     // If the objects don't have debuginfo there's nothing to preserve.
1028     if sess.opts.debuginfo == config::DebugInfo::None {
1029         return false;
1030     }
1031
1032     // If we're only producing artifacts that are archives, no need to preserve
1033     // the objects as they're losslessly contained inside the archives.
1034     let output_linked =
1035         sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
1036     if !output_linked {
1037         return false;
1038     }
1039
1040     // Single mode keeps debuginfo in the same object file, but in such a way that it it skipped
1041     // by the linker - so it's expected that when codegen units are linked together that this
1042     // debuginfo would be lost without keeping around the temps.
1043     if sess.opts.debugging_opts.split_dwarf == config::SplitDwarfKind::Single {
1044         return true;
1045     }
1046
1047     // If we're on OSX then the equivalent of split dwarf is turned on by
1048     // default. The final executable won't actually have any debug information
1049     // except it'll have pointers to elsewhere. Historically we've always run
1050     // `dsymutil` to "link all the dwarf together" but this is actually sort of
1051     // a bummer for incremental compilation! (the whole point of split dwarf is
1052     // that you don't do this sort of dwarf link).
1053     //
1054     // Basically as a result this just means that if we're on OSX and we're
1055     // *not* running dsymutil then the object files are the only source of truth
1056     // for debug information, so we must preserve them.
1057     if sess.target.is_like_osx {
1058         return !sess.opts.debugging_opts.run_dsymutil;
1059     }
1060
1061     false
1062 }
1063
1064 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
1065     sess.target_filesearch(PathKind::Native).search_path_dirs()
1066 }
1067
1068 enum RlibFlavor {
1069     Normal,
1070     StaticlibBase,
1071 }
1072
1073 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
1074     let lib_args: Vec<_> = all_native_libs
1075         .iter()
1076         .filter(|l| relevant_lib(sess, l))
1077         .filter_map(|lib| {
1078             let name = lib.name?;
1079             match lib.kind {
1080                 NativeLibKind::StaticNoBundle
1081                 | NativeLibKind::Dylib
1082                 | NativeLibKind::Unspecified => {
1083                     if sess.target.is_like_msvc {
1084                         Some(format!("{}.lib", name))
1085                     } else {
1086                         Some(format!("-l{}", name))
1087                     }
1088                 }
1089                 NativeLibKind::Framework => {
1090                     // ld-only syntax, since there are no frameworks in MSVC
1091                     Some(format!("-framework {}", name))
1092                 }
1093                 // These are included, no need to print them
1094                 NativeLibKind::StaticBundle | NativeLibKind::RawDylib => None,
1095             }
1096         })
1097         .collect();
1098     if !lib_args.is_empty() {
1099         sess.note_without_error(
1100             "Link against the following native artifacts when linking \
1101                                  against this static library. The order and any duplication \
1102                                  can be significant on some platforms.",
1103         );
1104         // Prefix for greppability
1105         sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1106     }
1107 }
1108
1109 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1110     let fs = sess.target_filesearch(PathKind::Native);
1111     let file_path = fs.get_lib_path().join(name);
1112     if file_path.exists() {
1113         return file_path;
1114     }
1115     // Special directory with objects used only in self-contained linkage mode
1116     if self_contained {
1117         let file_path = fs.get_self_contained_lib_path().join(name);
1118         if file_path.exists() {
1119             return file_path;
1120         }
1121     }
1122     for search_path in fs.search_paths() {
1123         let file_path = search_path.dir.join(name);
1124         if file_path.exists() {
1125             return file_path;
1126         }
1127     }
1128     PathBuf::from(name)
1129 }
1130
1131 fn exec_linker(
1132     sess: &Session,
1133     cmd: &Command,
1134     out_filename: &Path,
1135     tmpdir: &Path,
1136 ) -> io::Result<Output> {
1137     // When attempting to spawn the linker we run a risk of blowing out the
1138     // size limits for spawning a new process with respect to the arguments
1139     // we pass on the command line.
1140     //
1141     // Here we attempt to handle errors from the OS saying "your list of
1142     // arguments is too big" by reinvoking the linker again with an `@`-file
1143     // that contains all the arguments. The theory is that this is then
1144     // accepted on all linkers and the linker will read all its options out of
1145     // there instead of looking at the command line.
1146     if !cmd.very_likely_to_exceed_some_spawn_limit() {
1147         match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1148             Ok(child) => {
1149                 let output = child.wait_with_output();
1150                 flush_linked_file(&output, out_filename)?;
1151                 return output;
1152             }
1153             Err(ref e) if command_line_too_big(e) => {
1154                 info!("command line to linker was too big: {}", e);
1155             }
1156             Err(e) => return Err(e),
1157         }
1158     }
1159
1160     info!("falling back to passing arguments to linker via an @-file");
1161     let mut cmd2 = cmd.clone();
1162     let mut args = String::new();
1163     for arg in cmd2.take_args() {
1164         args.push_str(
1165             &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1166                 .to_string(),
1167         );
1168         args.push('\n');
1169     }
1170     let file = tmpdir.join("linker-arguments");
1171     let bytes = if sess.target.is_like_msvc {
1172         let mut out = Vec::with_capacity((1 + args.len()) * 2);
1173         // start the stream with a UTF-16 BOM
1174         for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1175             // encode in little endian
1176             out.push(c as u8);
1177             out.push((c >> 8) as u8);
1178         }
1179         out
1180     } else {
1181         args.into_bytes()
1182     };
1183     fs::write(&file, &bytes)?;
1184     cmd2.arg(format!("@{}", file.display()));
1185     info!("invoking linker {:?}", cmd2);
1186     let output = cmd2.output();
1187     flush_linked_file(&output, out_filename)?;
1188     return output;
1189
1190     #[cfg(unix)]
1191     fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1192         Ok(())
1193     }
1194
1195     #[cfg(windows)]
1196     fn flush_linked_file(
1197         command_output: &io::Result<Output>,
1198         out_filename: &Path,
1199     ) -> io::Result<()> {
1200         // On Windows, under high I/O load, output buffers are sometimes not flushed,
1201         // even long after process exit, causing nasty, non-reproducible output bugs.
1202         //
1203         // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1204         //
1205         // А full writeup of the original Chrome bug can be found at
1206         // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1207
1208         if let &Ok(ref out) = command_output {
1209             if out.status.success() {
1210                 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1211                     of.sync_all()?;
1212                 }
1213             }
1214         }
1215
1216         Ok(())
1217     }
1218
1219     #[cfg(unix)]
1220     fn command_line_too_big(err: &io::Error) -> bool {
1221         err.raw_os_error() == Some(::libc::E2BIG)
1222     }
1223
1224     #[cfg(windows)]
1225     fn command_line_too_big(err: &io::Error) -> bool {
1226         const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1227         err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1228     }
1229
1230     struct Escape<'a> {
1231         arg: &'a str,
1232         is_like_msvc: bool,
1233     }
1234
1235     impl<'a> fmt::Display for Escape<'a> {
1236         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237             if self.is_like_msvc {
1238                 // This is "documented" at
1239                 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1240                 //
1241                 // Unfortunately there's not a great specification of the
1242                 // syntax I could find online (at least) but some local
1243                 // testing showed that this seemed sufficient-ish to catch
1244                 // at least a few edge cases.
1245                 write!(f, "\"")?;
1246                 for c in self.arg.chars() {
1247                     match c {
1248                         '"' => write!(f, "\\{}", c)?,
1249                         c => write!(f, "{}", c)?,
1250                     }
1251                 }
1252                 write!(f, "\"")?;
1253             } else {
1254                 // This is documented at https://linux.die.net/man/1/ld, namely:
1255                 //
1256                 // > Options in file are separated by whitespace. A whitespace
1257                 // > character may be included in an option by surrounding the
1258                 // > entire option in either single or double quotes. Any
1259                 // > character (including a backslash) may be included by
1260                 // > prefixing the character to be included with a backslash.
1261                 //
1262                 // We put an argument on each line, so all we need to do is
1263                 // ensure the line is interpreted as one whole argument.
1264                 for c in self.arg.chars() {
1265                     match c {
1266                         '\\' | ' ' => write!(f, "\\{}", c)?,
1267                         c => write!(f, "{}", c)?,
1268                     }
1269                 }
1270             }
1271             Ok(())
1272         }
1273     }
1274 }
1275
1276 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1277     let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1278         (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1279         (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1280         (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1281         (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1282         (_, true, _) => LinkOutputKind::StaticDylib,
1283         (_, false, _) => LinkOutputKind::DynamicDylib,
1284     };
1285
1286     // Adjust the output kind to target capabilities.
1287     let opts = &sess.target;
1288     let pic_exe_supported = opts.position_independent_executables;
1289     let static_pic_exe_supported = opts.static_position_independent_executables;
1290     let static_dylib_supported = opts.crt_static_allows_dylibs;
1291     match kind {
1292         LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1293         LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1294         LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1295         _ => kind,
1296     }
1297 }
1298
1299 // Returns true if linker is located within sysroot
1300 fn detect_self_contained_mingw(sess: &Session) -> bool {
1301     let (linker, _) = linker_and_flavor(&sess);
1302     // Assume `-C linker=rust-lld` as self-contained mode
1303     if linker == Path::new("rust-lld") {
1304         return true;
1305     }
1306     let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1307         linker.with_extension("exe")
1308     } else {
1309         linker
1310     };
1311     for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1312         let full_path = dir.join(&linker_with_extension);
1313         // If linker comes from sysroot assume self-contained mode
1314         if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1315             return false;
1316         }
1317     }
1318     true
1319 }
1320
1321 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1322 /// We only provide such support for a very limited number of targets.
1323 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1324     if let Some(self_contained) = sess.opts.cg.link_self_contained {
1325         return self_contained;
1326     }
1327
1328     match sess.target.crt_objects_fallback {
1329         // FIXME: Find a better heuristic for "native musl toolchain is available",
1330         // based on host and linker path, for example.
1331         // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1332         Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1333         Some(CrtObjectsFallback::Mingw) => {
1334             sess.host == sess.target
1335                 && sess.target.vendor != "uwp"
1336                 && detect_self_contained_mingw(&sess)
1337         }
1338         // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1339         Some(CrtObjectsFallback::Wasm) => true,
1340         None => false,
1341     }
1342 }
1343
1344 /// Add pre-link object files defined by the target spec.
1345 fn add_pre_link_objects(
1346     cmd: &mut dyn Linker,
1347     sess: &Session,
1348     link_output_kind: LinkOutputKind,
1349     self_contained: bool,
1350 ) {
1351     let opts = &sess.target;
1352     let objects =
1353         if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1354     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1355         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1356     }
1357 }
1358
1359 /// Add post-link object files defined by the target spec.
1360 fn add_post_link_objects(
1361     cmd: &mut dyn Linker,
1362     sess: &Session,
1363     link_output_kind: LinkOutputKind,
1364     self_contained: bool,
1365 ) {
1366     let opts = &sess.target;
1367     let objects =
1368         if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1369     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1370         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1371     }
1372 }
1373
1374 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1375 /// FIXME: Determine where exactly these args need to be inserted.
1376 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1377     if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1378         cmd.args(args);
1379     }
1380     cmd.args(&sess.opts.debugging_opts.pre_link_args);
1381 }
1382
1383 /// Add a link script embedded in the target, if applicable.
1384 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1385     match (crate_type, &sess.target.link_script) {
1386         (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1387             if !sess.target.linker_is_gnu {
1388                 sess.fatal("can only use link script when linking with GNU-like linker");
1389             }
1390
1391             let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1392
1393             let path = tmpdir.join(file_name);
1394             if let Err(e) = fs::write(&path, script) {
1395                 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1396             }
1397
1398             cmd.arg("--script");
1399             cmd.arg(path);
1400         }
1401         _ => {}
1402     }
1403 }
1404
1405 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1406 /// FIXME: Determine where exactly these args need to be inserted.
1407 fn add_user_defined_link_args(
1408     cmd: &mut dyn Linker,
1409     sess: &Session,
1410     codegen_results: &CodegenResults,
1411 ) {
1412     cmd.args(&sess.opts.cg.link_args);
1413     cmd.args(&*codegen_results.crate_info.link_args);
1414 }
1415
1416 /// Add arbitrary "late link" args defined by the target spec.
1417 /// FIXME: Determine where exactly these args need to be inserted.
1418 fn add_late_link_args(
1419     cmd: &mut dyn Linker,
1420     sess: &Session,
1421     flavor: LinkerFlavor,
1422     crate_type: CrateType,
1423     codegen_results: &CodegenResults,
1424 ) {
1425     let any_dynamic_crate = crate_type == CrateType::Dylib
1426         || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1427             *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1428         });
1429     if any_dynamic_crate {
1430         if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1431             cmd.args(args);
1432         }
1433     } else {
1434         if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1435             cmd.args(args);
1436         }
1437     }
1438     if let Some(args) = sess.target.late_link_args.get(&flavor) {
1439         cmd.args(args);
1440     }
1441 }
1442
1443 /// Add arbitrary "post-link" args defined by the target spec.
1444 /// FIXME: Determine where exactly these args need to be inserted.
1445 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1446     if let Some(args) = sess.target.post_link_args.get(&flavor) {
1447         cmd.args(args);
1448     }
1449 }
1450
1451 /// Add object files containing code from the current crate.
1452 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1453     for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1454         cmd.add_object(obj);
1455     }
1456 }
1457
1458 /// Add object files for allocator code linked once for the whole crate tree.
1459 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1460     if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1461         cmd.add_object(obj);
1462     }
1463 }
1464
1465 /// Add object files containing metadata for the current crate.
1466 fn add_local_crate_metadata_objects(
1467     cmd: &mut dyn Linker,
1468     crate_type: CrateType,
1469     codegen_results: &CodegenResults,
1470 ) {
1471     // When linking a dynamic library, we put the metadata into a section of the
1472     // executable. This metadata is in a separate object file from the main
1473     // object file, so we link that in here.
1474     if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1475         if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1476         {
1477             cmd.add_object(obj);
1478         }
1479     }
1480 }
1481
1482 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1483 /// all its dependency crates.
1484 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1485 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1486     cmd: &mut dyn Linker,
1487     sess: &'a Session,
1488     crate_type: CrateType,
1489     codegen_results: &CodegenResults,
1490     tmpdir: &Path,
1491 ) {
1492     // Take careful note of the ordering of the arguments we pass to the linker
1493     // here. Linkers will assume that things on the left depend on things to the
1494     // right. Things on the right cannot depend on things on the left. This is
1495     // all formally implemented in terms of resolving symbols (libs on the right
1496     // resolve unknown symbols of libs on the left, but not vice versa).
1497     //
1498     // For this reason, we have organized the arguments we pass to the linker as
1499     // such:
1500     //
1501     // 1. The local object that LLVM just generated
1502     // 2. Local native libraries
1503     // 3. Upstream rust libraries
1504     // 4. Upstream native libraries
1505     //
1506     // The rationale behind this ordering is that those items lower down in the
1507     // list can't depend on items higher up in the list. For example nothing can
1508     // depend on what we just generated (e.g., that'd be a circular dependency).
1509     // Upstream rust libraries are not allowed to depend on our local native
1510     // libraries as that would violate the structure of the DAG, in that
1511     // scenario they are required to link to them as well in a shared fashion.
1512     //
1513     // Note that upstream rust libraries may contain native dependencies as
1514     // well, but they also can't depend on what we just started to add to the
1515     // link line. And finally upstream native libraries can't depend on anything
1516     // in this DAG so far because they're only dylibs and dylibs can only depend
1517     // on other dylibs (e.g., other native deps).
1518     //
1519     // If -Zlink-native-libraries=false is set, then the assumption is that an
1520     // external build system already has the native dependencies defined, and it
1521     // will provide them to the linker itself.
1522     if sess.opts.debugging_opts.link_native_libraries {
1523         add_local_native_libraries(cmd, sess, codegen_results);
1524     }
1525     add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1526     if sess.opts.debugging_opts.link_native_libraries {
1527         add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1528     }
1529 }
1530
1531 /// Add sysroot and other globally set directories to the directory search list.
1532 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1533     // The default library location, we need this to find the runtime.
1534     // The location of crates will be determined as needed.
1535     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1536     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1537
1538     // Special directory with libraries used only in self-contained linkage mode
1539     if self_contained {
1540         let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1541         cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1542     }
1543 }
1544
1545 /// Add options making relocation sections in the produced ELF files read-only
1546 /// and suppressing lazy binding.
1547 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1548     match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.relro_level) {
1549         RelroLevel::Full => cmd.full_relro(),
1550         RelroLevel::Partial => cmd.partial_relro(),
1551         RelroLevel::Off => cmd.no_relro(),
1552         RelroLevel::None => {}
1553     }
1554 }
1555
1556 /// Add library search paths used at runtime by dynamic linkers.
1557 fn add_rpath_args(
1558     cmd: &mut dyn Linker,
1559     sess: &Session,
1560     codegen_results: &CodegenResults,
1561     out_filename: &Path,
1562 ) {
1563     // FIXME (#2397): At some point we want to rpath our guesses as to
1564     // where extern libraries might live, based on the
1565     // addl_lib_search_paths
1566     if sess.opts.cg.rpath {
1567         let target_triple = sess.opts.target_triple.triple();
1568         let mut get_install_prefix_lib_path = || {
1569             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1570             let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1571             let mut path = PathBuf::from(install_prefix);
1572             path.push(&tlib);
1573
1574             path
1575         };
1576         let mut rpath_config = RPathConfig {
1577             used_crates: &codegen_results.crate_info.used_crates_dynamic,
1578             out_filename: out_filename.to_path_buf(),
1579             has_rpath: sess.target.has_rpath,
1580             is_like_osx: sess.target.is_like_osx,
1581             linker_is_gnu: sess.target.linker_is_gnu,
1582             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1583         };
1584         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1585     }
1586 }
1587
1588 /// Produce the linker command line containing linker path and arguments.
1589 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1590 /// by the user without creating a custom target specification.
1591 /// `OBJECT-FILES` specify whether the arguments can add object files.
1592 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1593 /// or by the target spec can be inserted here.
1594 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1595 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1596     path: &Path,
1597     flavor: LinkerFlavor,
1598     sess: &'a Session,
1599     crate_type: CrateType,
1600     tmpdir: &Path,
1601     out_filename: &Path,
1602     codegen_results: &CodegenResults,
1603     target_cpu: &str,
1604 ) -> Command {
1605     let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1606     let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1607     // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1608     // to the linker args construction.
1609     assert!(base_cmd.get_args().is_empty() || sess.target.vendor == "uwp");
1610     let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1611     let link_output_kind = link_output_kind(sess, crate_type);
1612
1613     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1614     add_pre_link_args(cmd, sess, flavor);
1615
1616     // NO-OPT-OUT, OBJECT-FILES-NO
1617     add_apple_sdk(cmd, sess, flavor);
1618
1619     // NO-OPT-OUT
1620     add_link_script(cmd, sess, tmpdir, crate_type);
1621
1622     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1623     if sess.target.is_like_fuchsia && crate_type == CrateType::Executable {
1624         let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1625             "asan/"
1626         } else {
1627             ""
1628         };
1629         cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1630     }
1631
1632     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1633     if sess.target.eh_frame_header {
1634         cmd.add_eh_frame_header();
1635     }
1636
1637     // NO-OPT-OUT, OBJECT-FILES-NO
1638     if crt_objects_fallback {
1639         cmd.no_crt_objects();
1640     }
1641
1642     // NO-OPT-OUT, OBJECT-FILES-YES
1643     add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1644
1645     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1646     if sess.target.is_like_emscripten {
1647         cmd.arg("-s");
1648         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1649             "DISABLE_EXCEPTION_CATCHING=1"
1650         } else {
1651             "DISABLE_EXCEPTION_CATCHING=0"
1652         });
1653     }
1654
1655     // OBJECT-FILES-YES, AUDIT-ORDER
1656     link_sanitizers(sess, crate_type, cmd);
1657
1658     // OBJECT-FILES-NO, AUDIT-ORDER
1659     // Linker plugins should be specified early in the list of arguments
1660     // FIXME: How "early" exactly?
1661     cmd.linker_plugin_lto();
1662
1663     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1664     // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1665     add_library_search_dirs(cmd, sess, crt_objects_fallback);
1666
1667     // OBJECT-FILES-YES
1668     add_local_crate_regular_objects(cmd, codegen_results);
1669
1670     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1671     cmd.output_filename(out_filename);
1672
1673     // OBJECT-FILES-NO, AUDIT-ORDER
1674     if crate_type == CrateType::Executable && sess.target.is_like_windows {
1675         if let Some(ref s) = codegen_results.windows_subsystem {
1676             cmd.subsystem(s);
1677         }
1678     }
1679
1680     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1681     // If we're building something like a dynamic library then some platforms
1682     // need to make sure that all symbols are exported correctly from the
1683     // dynamic library.
1684     cmd.export_symbols(tmpdir, crate_type);
1685
1686     // OBJECT-FILES-YES
1687     add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1688
1689     // OBJECT-FILES-YES
1690     add_local_crate_allocator_objects(cmd, codegen_results);
1691
1692     // OBJECT-FILES-NO, AUDIT-ORDER
1693     // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1694     // Try to strip as much out of the generated object by removing unused
1695     // sections if possible. See more comments in linker.rs
1696     if !sess.link_dead_code() {
1697         let keep_metadata = crate_type == CrateType::Dylib;
1698         cmd.gc_sections(keep_metadata);
1699     }
1700
1701     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1702     cmd.set_output_kind(link_output_kind, out_filename);
1703
1704     // OBJECT-FILES-NO, AUDIT-ORDER
1705     add_relro_args(cmd, sess);
1706
1707     // OBJECT-FILES-NO, AUDIT-ORDER
1708     // Pass optimization flags down to the linker.
1709     cmd.optimize();
1710
1711     // OBJECT-FILES-NO, AUDIT-ORDER
1712     // Pass debuginfo and strip flags down to the linker.
1713     cmd.debuginfo(sess.opts.debugging_opts.strip);
1714
1715     // OBJECT-FILES-NO, AUDIT-ORDER
1716     // We want to prevent the compiler from accidentally leaking in any system libraries,
1717     // so by default we tell linkers not to link to any default libraries.
1718     if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
1719         cmd.no_default_libraries();
1720     }
1721
1722     // OBJECT-FILES-YES
1723     link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1724         cmd,
1725         sess,
1726         crate_type,
1727         codegen_results,
1728         tmpdir,
1729     );
1730
1731     // OBJECT-FILES-NO, AUDIT-ORDER
1732     if sess.opts.cg.profile_generate.enabled() || sess.opts.debugging_opts.instrument_coverage {
1733         cmd.pgo_gen();
1734     }
1735
1736     // OBJECT-FILES-NO, AUDIT-ORDER
1737     if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1738         cmd.control_flow_guard();
1739     }
1740
1741     // OBJECT-FILES-NO, AUDIT-ORDER
1742     add_rpath_args(cmd, sess, codegen_results, out_filename);
1743
1744     // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1745     add_user_defined_link_args(cmd, sess, codegen_results);
1746
1747     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1748     cmd.finalize();
1749
1750     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1751     add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1752
1753     // NO-OPT-OUT, OBJECT-FILES-YES
1754     add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1755
1756     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1757     add_post_link_args(cmd, sess, flavor);
1758
1759     cmd.take_cmd()
1760 }
1761
1762 /// # Native library linking
1763 ///
1764 /// User-supplied library search paths (-L on the command line). These are the same paths used to
1765 /// find Rust crates, so some of them may have been added already by the previous crate linking
1766 /// code. This only allows them to be found at compile time so it is still entirely up to outside
1767 /// forces to make sure that library can be found at runtime.
1768 ///
1769 /// Also note that the native libraries linked here are only the ones located in the current crate.
1770 /// Upstream crates with native library dependencies may have their native library pulled in above.
1771 fn add_local_native_libraries(
1772     cmd: &mut dyn Linker,
1773     sess: &Session,
1774     codegen_results: &CodegenResults,
1775 ) {
1776     let filesearch = sess.target_filesearch(PathKind::All);
1777     for search_path in filesearch.search_paths() {
1778         match search_path.kind {
1779             PathKind::Framework => {
1780                 cmd.framework_path(&search_path.dir);
1781             }
1782             _ => {
1783                 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1784             }
1785         }
1786     }
1787
1788     let relevant_libs =
1789         codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1790
1791     let search_path = archive_search_paths(sess);
1792     for lib in relevant_libs {
1793         let name = match lib.name {
1794             Some(l) => l,
1795             None => continue,
1796         };
1797         match lib.kind {
1798             NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1799             NativeLibKind::Framework => cmd.link_framework(name),
1800             NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1801             NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1802             NativeLibKind::RawDylib => {
1803                 // FIXME(#58713): Proper handling for raw dylibs.
1804                 bug!("raw_dylib feature not yet implemented");
1805             }
1806         }
1807     }
1808 }
1809
1810 /// # Rust Crate linking
1811 ///
1812 /// Rust crates are not considered at all when creating an rlib output. All dependencies will be
1813 /// linked when producing the final output (instead of the intermediate rlib version).
1814 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1815     cmd: &mut dyn Linker,
1816     sess: &'a Session,
1817     codegen_results: &CodegenResults,
1818     crate_type: CrateType,
1819     tmpdir: &Path,
1820 ) {
1821     // All of the heavy lifting has previously been accomplished by the
1822     // dependency_format module of the compiler. This is just crawling the
1823     // output of that module, adding crates as necessary.
1824     //
1825     // Linking to a rlib involves just passing it to the linker (the linker
1826     // will slurp up the object files inside), and linking to a dynamic library
1827     // involves just passing the right -l flag.
1828
1829     let (_, data) = codegen_results
1830         .crate_info
1831         .dependency_formats
1832         .iter()
1833         .find(|(ty, _)| *ty == crate_type)
1834         .expect("failed to find crate type in dependency format list");
1835
1836     // Invoke get_used_crates to ensure that we get a topological sorting of
1837     // crates.
1838     let deps = &codegen_results.crate_info.used_crates_dynamic;
1839
1840     // There's a few internal crates in the standard library (aka libcore and
1841     // libstd) which actually have a circular dependence upon one another. This
1842     // currently arises through "weak lang items" where libcore requires things
1843     // like `rust_begin_unwind` but libstd ends up defining it. To get this
1844     // circular dependence to work correctly in all situations we'll need to be
1845     // sure to correctly apply the `--start-group` and `--end-group` options to
1846     // GNU linkers, otherwise if we don't use any other symbol from the standard
1847     // library it'll get discarded and the whole application won't link.
1848     //
1849     // In this loop we're calculating the `group_end`, after which crate to
1850     // pass `--end-group` and `group_start`, before which crate to pass
1851     // `--start-group`. We currently do this by passing `--end-group` after
1852     // the first crate (when iterating backwards) that requires a lang item
1853     // defined somewhere else. Once that's set then when we've defined all the
1854     // necessary lang items we'll pass `--start-group`.
1855     //
1856     // Note that this isn't amazing logic for now but it should do the trick
1857     // for the current implementation of the standard library.
1858     let mut group_end = None;
1859     let mut group_start = None;
1860     // Crates available for linking thus far.
1861     let mut available = FxHashSet::default();
1862     // Crates required to satisfy dependencies discovered so far.
1863     let mut required = FxHashSet::default();
1864
1865     let info = &codegen_results.crate_info;
1866     for &(cnum, _) in deps.iter().rev() {
1867         if let Some(missing) = info.missing_lang_items.get(&cnum) {
1868             let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1869             required.extend(missing_crates);
1870         }
1871
1872         required.insert(Some(cnum));
1873         available.insert(Some(cnum));
1874
1875         if required.len() > available.len() && group_end.is_none() {
1876             group_end = Some(cnum);
1877         }
1878         if required.len() == available.len() && group_end.is_some() {
1879             group_start = Some(cnum);
1880             break;
1881         }
1882     }
1883
1884     // If we didn't end up filling in all lang items from upstream crates then
1885     // we'll be filling it in with our crate. This probably means we're the
1886     // standard library itself, so skip this for now.
1887     if group_end.is_some() && group_start.is_none() {
1888         group_end = None;
1889     }
1890
1891     let mut compiler_builtins = None;
1892
1893     for &(cnum, _) in deps.iter() {
1894         if group_start == Some(cnum) {
1895             cmd.group_start();
1896         }
1897
1898         // We may not pass all crates through to the linker. Some crates may
1899         // appear statically in an existing dylib, meaning we'll pick up all the
1900         // symbols from the dylib.
1901         let src = &codegen_results.crate_info.used_crate_source[&cnum];
1902         match data[cnum.as_usize() - 1] {
1903             _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1904                 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1905             }
1906             // compiler-builtins are always placed last to ensure that they're
1907             // linked correctly.
1908             _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1909                 assert!(compiler_builtins.is_none());
1910                 compiler_builtins = Some(cnum);
1911             }
1912             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1913             Linkage::Static => {
1914                 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1915             }
1916             Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1917         }
1918
1919         if group_end == Some(cnum) {
1920             cmd.group_end();
1921         }
1922     }
1923
1924     // compiler-builtins are always placed last to ensure that they're
1925     // linked correctly.
1926     // We must always link the `compiler_builtins` crate statically. Even if it
1927     // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1928     // is used)
1929     if let Some(cnum) = compiler_builtins {
1930         add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1931     }
1932
1933     // Converts a library file-stem into a cc -l argument
1934     fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
1935         if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
1936     }
1937
1938     // Adds the static "rlib" versions of all crates to the command line.
1939     // There's a bit of magic which happens here specifically related to LTO and
1940     // dynamic libraries. Specifically:
1941     //
1942     // * For LTO, we remove upstream object files.
1943     // * For dylibs we remove metadata and bytecode from upstream rlibs
1944     //
1945     // When performing LTO, almost(*) all of the bytecode from the upstream
1946     // libraries has already been included in our object file output. As a
1947     // result we need to remove the object files in the upstream libraries so
1948     // the linker doesn't try to include them twice (or whine about duplicate
1949     // symbols). We must continue to include the rest of the rlib, however, as
1950     // it may contain static native libraries which must be linked in.
1951     //
1952     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1953     // their bytecode wasn't included. The object files in those libraries must
1954     // still be passed to the linker.
1955     //
1956     // When making a dynamic library, linkers by default don't include any
1957     // object files in an archive if they're not necessary to resolve the link.
1958     // We basically want to convert the archive (rlib) to a dylib, though, so we
1959     // *do* want everything included in the output, regardless of whether the
1960     // linker thinks it's needed or not. As a result we must use the
1961     // --whole-archive option (or the platform equivalent). When using this
1962     // option the linker will fail if there are non-objects in the archive (such
1963     // as our own metadata and/or bytecode). All in all, for rlibs to be
1964     // entirely included in dylibs, we need to remove all non-object files.
1965     //
1966     // Note, however, that if we're not doing LTO or we're not producing a dylib
1967     // (aka we're making an executable), we can just pass the rlib blindly to
1968     // the linker (fast) because it's fine if it's not actually included as
1969     // we're at the end of the dependency chain.
1970     fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1971         cmd: &mut dyn Linker,
1972         sess: &'a Session,
1973         codegen_results: &CodegenResults,
1974         tmpdir: &Path,
1975         crate_type: CrateType,
1976         cnum: CrateNum,
1977     ) {
1978         let src = &codegen_results.crate_info.used_crate_source[&cnum];
1979         let cratepath = &src.rlib.as_ref().unwrap().0;
1980
1981         // See the comment above in `link_staticlib` and `link_rlib` for why if
1982         // there's a static library that's not relevant we skip all object
1983         // files.
1984         let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1985         let skip_native = native_libs
1986             .iter()
1987             .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1988
1989         if (!are_upstream_rust_objects_already_included(sess)
1990             || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1991             && crate_type != CrateType::Dylib
1992             && !skip_native
1993         {
1994             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1995             return;
1996         }
1997
1998         let dst = tmpdir.join(cratepath.file_name().unwrap());
1999         let name = cratepath.file_name().unwrap().to_str().unwrap();
2000         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2001
2002         sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2003             let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
2004             archive.update_symbols();
2005
2006             let mut any_objects = false;
2007             for f in archive.src_files() {
2008                 if f == METADATA_FILENAME {
2009                     archive.remove_file(&f);
2010                     continue;
2011                 }
2012
2013                 let canonical = f.replace("-", "_");
2014                 let canonical_name = name.replace("-", "_");
2015
2016                 let is_rust_object =
2017                     canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2018
2019                 // If we've been requested to skip all native object files
2020                 // (those not generated by the rust compiler) then we can skip
2021                 // this file. See above for why we may want to do this.
2022                 let skip_because_cfg_say_so = skip_native && !is_rust_object;
2023
2024                 // If we're performing LTO and this is a rust-generated object
2025                 // file, then we don't need the object file as it's part of the
2026                 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2027                 // though, so we let that object file slide.
2028                 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
2029                     && is_rust_object
2030                     && (sess.target.no_builtins
2031                         || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
2032
2033                 if skip_because_cfg_say_so || skip_because_lto {
2034                     archive.remove_file(&f);
2035                 } else {
2036                     any_objects = true;
2037                 }
2038             }
2039
2040             if !any_objects {
2041                 return;
2042             }
2043             archive.build();
2044
2045             // If we're creating a dylib, then we need to include the
2046             // whole of each object in our archive into that artifact. This is
2047             // because a `dylib` can be reused as an intermediate artifact.
2048             //
2049             // Note, though, that we don't want to include the whole of a
2050             // compiler-builtins crate (e.g., compiler-rt) because it'll get
2051             // repeatedly linked anyway.
2052             if crate_type == CrateType::Dylib
2053                 && codegen_results.crate_info.compiler_builtins != Some(cnum)
2054             {
2055                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
2056             } else {
2057                 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
2058             }
2059         });
2060     }
2061
2062     // Same thing as above, but for dynamic crates instead of static crates.
2063     fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2064         // Just need to tell the linker about where the library lives and
2065         // what its name is
2066         let parent = cratepath.parent();
2067         if let Some(dir) = parent {
2068             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2069         }
2070         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2071         cmd.link_rust_dylib(
2072             Symbol::intern(&unlib(&sess.target, filestem)),
2073             parent.unwrap_or(Path::new("")),
2074         );
2075     }
2076 }
2077
2078 /// Link in all of our upstream crates' native dependencies. Remember that all of these upstream
2079 /// native dependencies are all non-static dependencies. We've got two cases then:
2080 ///
2081 /// 1. The upstream crate is an rlib. In this case we *must* link in the native dependency because
2082 /// the rlib is just an archive.
2083 ///
2084 /// 2. The upstream crate is a dylib. In order to use the dylib, we have to have the dependency
2085 /// present on the system somewhere. Thus, we don't gain a whole lot from not linking in the
2086 /// dynamic dependency to this crate as well.
2087 ///
2088 /// The use case for this is a little subtle. In theory the native dependencies of a crate are
2089 /// purely an implementation detail of the crate itself, but the problem arises with generic and
2090 /// inlined functions. If a generic function calls a native function, then the generic function
2091 /// must be instantiated in the target crate, meaning that the native symbol must also be resolved
2092 /// in the target crate.
2093 fn add_upstream_native_libraries(
2094     cmd: &mut dyn Linker,
2095     sess: &Session,
2096     codegen_results: &CodegenResults,
2097     crate_type: CrateType,
2098 ) {
2099     // Be sure to use a topological sorting of crates because there may be
2100     // interdependencies between native libraries. When passing -nodefaultlibs,
2101     // for example, almost all native libraries depend on libc, so we have to
2102     // make sure that's all the way at the right (liblibc is near the base of
2103     // the dependency chain).
2104     //
2105     // This passes RequireStatic, but the actual requirement doesn't matter,
2106     // we're just getting an ordering of crate numbers, we're not worried about
2107     // the paths.
2108     let (_, data) = codegen_results
2109         .crate_info
2110         .dependency_formats
2111         .iter()
2112         .find(|(ty, _)| *ty == crate_type)
2113         .expect("failed to find crate type in dependency format list");
2114
2115     let crates = &codegen_results.crate_info.used_crates_static;
2116     for &(cnum, _) in crates {
2117         for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2118             let name = match lib.name {
2119                 Some(l) => l,
2120                 None => continue,
2121             };
2122             if !relevant_lib(sess, &lib) {
2123                 continue;
2124             }
2125             match lib.kind {
2126                 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2127                 NativeLibKind::Framework => cmd.link_framework(name),
2128                 NativeLibKind::StaticNoBundle => {
2129                     // Link "static-nobundle" native libs only if the crate they originate from
2130                     // is being linked statically to the current crate.  If it's linked dynamically
2131                     // or is an rlib already included via some other dylib crate, the symbols from
2132                     // native libs will have already been included in that dylib.
2133                     if data[cnum.as_usize() - 1] == Linkage::Static {
2134                         cmd.link_staticlib(name)
2135                     }
2136                 }
2137                 // ignore statically included native libraries here as we've
2138                 // already included them when we included the rust library
2139                 // previously
2140                 NativeLibKind::StaticBundle => {}
2141                 NativeLibKind::RawDylib => {
2142                     // FIXME(#58713): Proper handling for raw dylibs.
2143                     bug!("raw_dylib feature not yet implemented");
2144                 }
2145             }
2146         }
2147     }
2148 }
2149
2150 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2151     match lib.cfg {
2152         Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2153         None => true,
2154     }
2155 }
2156
2157 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2158     match sess.lto() {
2159         config::Lto::Fat => true,
2160         config::Lto::Thin => {
2161             // If we defer LTO to the linker, we haven't run LTO ourselves, so
2162             // any upstream object files have not been copied yet.
2163             !sess.opts.cg.linker_plugin_lto.enabled()
2164         }
2165         config::Lto::No | config::Lto::ThinLocal => false,
2166     }
2167 }
2168
2169 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2170     let arch = &sess.target.arch;
2171     let os = &sess.target.os;
2172     let llvm_target = &sess.target.llvm_target;
2173     if sess.target.vendor != "apple"
2174         || !matches!(os.as_str(), "ios" | "tvos")
2175         || flavor != LinkerFlavor::Gcc
2176     {
2177         return;
2178     }
2179     let sdk_name = match (arch.as_str(), os.as_str()) {
2180         ("aarch64", "tvos") => "appletvos",
2181         ("x86_64", "tvos") => "appletvsimulator",
2182         ("arm", "ios") => "iphoneos",
2183         ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2184         ("aarch64", "ios") => "iphoneos",
2185         ("x86", "ios") => "iphonesimulator",
2186         ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2187         ("x86_64", "ios") => "iphonesimulator",
2188         _ => {
2189             sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2190             return;
2191         }
2192     };
2193     let sdk_root = match get_apple_sdk_root(sdk_name) {
2194         Ok(s) => s,
2195         Err(e) => {
2196             sess.err(&e);
2197             return;
2198         }
2199     };
2200     let arch_name = llvm_target.split('-').next().expect("LLVM target must have a hyphen");
2201     cmd.args(&["-arch", arch_name, "-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2202 }
2203
2204 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2205     // Following what clang does
2206     // (https://github.com/llvm/llvm-project/blob/
2207     // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2208     // to allow the SDK path to be set. (For clang, xcrun sets
2209     // SDKROOT; for rustc, the user or build system can set it, or we
2210     // can fall back to checking for xcrun on PATH.)
2211     if let Ok(sdkroot) = env::var("SDKROOT") {
2212         let p = Path::new(&sdkroot);
2213         match sdk_name {
2214             // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2215             "appletvos"
2216                 if sdkroot.contains("TVSimulator.platform")
2217                     || sdkroot.contains("MacOSX.platform") => {}
2218             "appletvsimulator"
2219                 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2220             "iphoneos"
2221                 if sdkroot.contains("iPhoneSimulator.platform")
2222                     || sdkroot.contains("MacOSX.platform") => {}
2223             "iphonesimulator"
2224                 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2225             }
2226             "macosx10.15"
2227                 if sdkroot.contains("iPhoneOS.platform")
2228                     || sdkroot.contains("iPhoneSimulator.platform") => {}
2229             // Ignore `SDKROOT` if it's not a valid path.
2230             _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2231             _ => return Ok(sdkroot),
2232         }
2233     }
2234     let res =
2235         Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2236             |output| {
2237                 if output.status.success() {
2238                     Ok(String::from_utf8(output.stdout).unwrap())
2239                 } else {
2240                     let error = String::from_utf8(output.stderr);
2241                     let error = format!("process exit with error: {}", error.unwrap());
2242                     Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2243                 }
2244             },
2245         );
2246
2247     match res {
2248         Ok(output) => Ok(output.trim().to_string()),
2249         Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),
2250     }
2251 }