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