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