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