]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/link.rs
Rollup merge of #79508 - jryans:check-dsymutil-result, r=nagisa
[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     fn escape_string(s: &[u8]) -> String {
647         str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
648             let mut x = "Non-UTF-8 output: ".to_string();
649             x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
650             x
651         })
652     }
653
654     match prog {
655         Ok(prog) => {
656             if !prog.status.success() {
657                 let mut output = prog.stderr.clone();
658                 output.extend_from_slice(&prog.stdout);
659                 sess.struct_err(&format!(
660                     "linking with `{}` failed: {}",
661                     linker_path.display(),
662                     prog.status
663                 ))
664                 .note(&format!("{:?}", &cmd))
665                 .note(&escape_string(&output))
666                 .emit();
667
668                 // If MSVC's `link.exe` was expected but the return code
669                 // is not a Microsoft LNK error then suggest a way to fix or
670                 // install the Visual Studio build tools.
671                 if let Some(code) = prog.status.code() {
672                     if sess.target.is_like_msvc
673                         && flavor == LinkerFlavor::Msvc
674                         // Respect the command line override
675                         && sess.opts.cg.linker.is_none()
676                         // Match exactly "link.exe"
677                         && linker_path.to_str() == Some("link.exe")
678                         // All Microsoft `link.exe` linking error codes are
679                         // four digit numbers in the range 1000 to 9999 inclusive
680                         && (code < 1000 || code > 9999)
681                     {
682                         let is_vs_installed = windows_registry::find_vs_version().is_ok();
683                         let has_linker = windows_registry::find_tool(
684                             &sess.opts.target_triple.triple(),
685                             "link.exe",
686                         )
687                         .is_some();
688
689                         sess.note_without_error("`link.exe` returned an unexpected error");
690                         if is_vs_installed && has_linker {
691                             // the linker is broken
692                             sess.note_without_error(
693                                 "the Visual Studio build tools may need to be repaired \
694                                 using the Visual Studio installer",
695                             );
696                             sess.note_without_error(
697                                 "or a necessary component may be missing from the \
698                                 \"C++ build tools\" workload",
699                             );
700                         } else if is_vs_installed {
701                             // the linker is not installed
702                             sess.note_without_error(
703                                 "in the Visual Studio installer, ensure the \
704                                 \"C++ build tools\" workload is selected",
705                             );
706                         } else {
707                             // visual studio is not installed
708                             sess.note_without_error(
709                                 "you may need to install Visual Studio build tools with the \
710                                 \"C++ build tools\" workload",
711                             );
712                         }
713                     }
714                 }
715
716                 sess.abort_if_errors();
717             }
718             info!("linker stderr:\n{}", escape_string(&prog.stderr));
719             info!("linker stdout:\n{}", escape_string(&prog.stdout));
720         }
721         Err(e) => {
722             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
723
724             let mut linker_error = {
725                 if linker_not_found {
726                     sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
727                 } else {
728                     sess.struct_err(&format!(
729                         "could not exec the linker `{}`",
730                         linker_path.display()
731                     ))
732                 }
733             };
734
735             linker_error.note(&e.to_string());
736
737             if !linker_not_found {
738                 linker_error.note(&format!("{:?}", &cmd));
739             }
740
741             linker_error.emit();
742
743             if sess.target.is_like_msvc && linker_not_found {
744                 sess.note_without_error(
745                     "the msvc targets depend on the msvc linker \
746                      but `link.exe` was not found",
747                 );
748                 sess.note_without_error(
749                     "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
750                      was installed with the Visual C++ option",
751                 );
752             }
753             sess.abort_if_errors();
754         }
755     }
756
757     // On macOS, debuggers need this utility to get run to do some munging of
758     // the symbols. Note, though, that if the object files are being preserved
759     // for their debug information there's no need for us to run dsymutil.
760     if sess.target.is_like_osx
761         && sess.opts.debuginfo != DebugInfo::None
762         && !preserve_objects_for_their_debuginfo(sess)
763     {
764         let prog = Command::new("dsymutil").arg(out_filename).output();
765         match prog {
766             Ok(prog) => {
767                 if !prog.status.success() {
768                     let mut output = prog.stderr.clone();
769                     output.extend_from_slice(&prog.stdout);
770                     sess.struct_warn(&format!(
771                         "processing debug info with `dsymutil` failed: {}",
772                         prog.status
773                     ))
774                     .note(&escape_string(&output))
775                     .emit();
776                 }
777             }
778             Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
779         }
780     }
781 }
782
783 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
784     // On macOS the runtimes are distributed as dylibs which should be linked to
785     // both executables and dynamic shared objects. Everywhere else the runtimes
786     // are currently distributed as static liraries which should be linked to
787     // executables only.
788     let needs_runtime = match crate_type {
789         CrateType::Executable => true,
790         CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
791         CrateType::Rlib | CrateType::Staticlib => false,
792     };
793
794     if !needs_runtime {
795         return;
796     }
797
798     let sanitizer = sess.opts.debugging_opts.sanitizer;
799     if sanitizer.contains(SanitizerSet::ADDRESS) {
800         link_sanitizer_runtime(sess, linker, "asan");
801     }
802     if sanitizer.contains(SanitizerSet::LEAK) {
803         link_sanitizer_runtime(sess, linker, "lsan");
804     }
805     if sanitizer.contains(SanitizerSet::MEMORY) {
806         link_sanitizer_runtime(sess, linker, "msan");
807     }
808     if sanitizer.contains(SanitizerSet::THREAD) {
809         link_sanitizer_runtime(sess, linker, "tsan");
810     }
811 }
812
813 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
814     let default_sysroot = filesearch::get_or_default_sysroot();
815     let default_tlib =
816         filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
817     let channel = option_env!("CFG_RELEASE_CHANNEL")
818         .map(|channel| format!("-{}", channel))
819         .unwrap_or_default();
820
821     match sess.opts.target_triple.triple() {
822         "x86_64-apple-darwin" => {
823             // On Apple platforms, the sanitizer is always built as a dylib, and
824             // LLVM will link to `@rpath/*.dylib`, so we need to specify an
825             // rpath to the library as well (the rpath should be absolute, see
826             // PR #41352 for details).
827             let libname = format!("rustc{}_rt.{}", channel, name);
828             let rpath = default_tlib.to_str().expect("non-utf8 component in path");
829             linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
830             linker.link_dylib(Symbol::intern(&libname));
831         }
832         "aarch64-fuchsia"
833         | "aarch64-unknown-linux-gnu"
834         | "x86_64-fuchsia"
835         | "x86_64-unknown-freebsd"
836         | "x86_64-unknown-linux-gnu" => {
837             let filename = format!("librustc{}_rt.{}.a", channel, name);
838             let path = default_tlib.join(&filename);
839             linker.link_whole_rlib(&path);
840         }
841         _ => {}
842     }
843 }
844
845 /// Returns a boolean indicating whether the specified crate should be ignored
846 /// during LTO.
847 ///
848 /// Crates ignored during LTO are not lumped together in the "massive object
849 /// file" that we create and are linked in their normal rlib states. See
850 /// comments below for what crates do not participate in LTO.
851 ///
852 /// It's unusual for a crate to not participate in LTO. Typically only
853 /// compiler-specific and unstable crates have a reason to not participate in
854 /// LTO.
855 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
856     // If our target enables builtin function lowering in LLVM then the
857     // crates providing these functions don't participate in LTO (e.g.
858     // no_builtins or compiler builtins crates).
859     !sess.target.no_builtins
860         && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
861 }
862
863 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
864     fn infer_from(
865         sess: &Session,
866         linker: Option<PathBuf>,
867         flavor: Option<LinkerFlavor>,
868     ) -> Option<(PathBuf, LinkerFlavor)> {
869         match (linker, flavor) {
870             (Some(linker), Some(flavor)) => Some((linker, flavor)),
871             // only the linker flavor is known; use the default linker for the selected flavor
872             (None, Some(flavor)) => Some((
873                 PathBuf::from(match flavor {
874                     LinkerFlavor::Em => {
875                         if cfg!(windows) {
876                             "emcc.bat"
877                         } else {
878                             "emcc"
879                         }
880                     }
881                     LinkerFlavor::Gcc => {
882                         if cfg!(any(target_os = "solaris", target_os = "illumos")) {
883                             // On historical Solaris systems, "cc" may have
884                             // been Sun Studio, which is not flag-compatible
885                             // with "gcc".  This history casts a long shadow,
886                             // and many modern illumos distributions today
887                             // ship GCC as "gcc" without also making it
888                             // available as "cc".
889                             "gcc"
890                         } else {
891                             "cc"
892                         }
893                     }
894                     LinkerFlavor::Ld => "ld",
895                     LinkerFlavor::Msvc => "link.exe",
896                     LinkerFlavor::Lld(_) => "lld",
897                     LinkerFlavor::PtxLinker => "rust-ptx-linker",
898                 }),
899                 flavor,
900             )),
901             (Some(linker), None) => {
902                 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
903                     sess.fatal("couldn't extract file stem from specified linker")
904                 });
905
906                 let flavor = if stem == "emcc" {
907                     LinkerFlavor::Em
908                 } else if stem == "gcc"
909                     || stem.ends_with("-gcc")
910                     || stem == "clang"
911                     || stem.ends_with("-clang")
912                 {
913                     LinkerFlavor::Gcc
914                 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
915                     LinkerFlavor::Ld
916                 } else if stem == "link" || stem == "lld-link" {
917                     LinkerFlavor::Msvc
918                 } else if stem == "lld" || stem == "rust-lld" {
919                     LinkerFlavor::Lld(sess.target.lld_flavor)
920                 } else {
921                     // fall back to the value in the target spec
922                     sess.target.linker_flavor
923                 };
924
925                 Some((linker, flavor))
926             }
927             (None, None) => None,
928         }
929     }
930
931     // linker and linker flavor specified via command line have precedence over what the target
932     // specification specifies
933     if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
934         return ret;
935     }
936
937     if let Some(ret) = infer_from(
938         sess,
939         sess.target.linker.clone().map(PathBuf::from),
940         Some(sess.target.linker_flavor),
941     ) {
942         return ret;
943     }
944
945     bug!("Not enough information provided to determine how to invoke the linker");
946 }
947
948 /// Returns a boolean indicating whether we should preserve the object files on
949 /// the filesystem for their debug information. This is often useful with
950 /// split-dwarf like schemes.
951 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
952     // If the objects don't have debuginfo there's nothing to preserve.
953     if sess.opts.debuginfo == config::DebugInfo::None {
954         return false;
955     }
956
957     // If we're only producing artifacts that are archives, no need to preserve
958     // the objects as they're losslessly contained inside the archives.
959     let output_linked =
960         sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
961     if !output_linked {
962         return false;
963     }
964
965     // If we're on OSX then the equivalent of split dwarf is turned on by
966     // default. The final executable won't actually have any debug information
967     // except it'll have pointers to elsewhere. Historically we've always run
968     // `dsymutil` to "link all the dwarf together" but this is actually sort of
969     // a bummer for incremental compilation! (the whole point of split dwarf is
970     // that you don't do this sort of dwarf link).
971     //
972     // Basically as a result this just means that if we're on OSX and we're
973     // *not* running dsymutil then the object files are the only source of truth
974     // for debug information, so we must preserve them.
975     if sess.target.is_like_osx {
976         return !sess.opts.debugging_opts.run_dsymutil;
977     }
978
979     false
980 }
981
982 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
983     sess.target_filesearch(PathKind::Native).search_path_dirs()
984 }
985
986 enum RlibFlavor {
987     Normal,
988     StaticlibBase,
989 }
990
991 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
992     let lib_args: Vec<_> = all_native_libs
993         .iter()
994         .filter(|l| relevant_lib(sess, l))
995         .filter_map(|lib| {
996             let name = lib.name?;
997             match lib.kind {
998                 NativeLibKind::StaticNoBundle
999                 | NativeLibKind::Dylib
1000                 | NativeLibKind::Unspecified => {
1001                     if sess.target.is_like_msvc {
1002                         Some(format!("{}.lib", name))
1003                     } else {
1004                         Some(format!("-l{}", name))
1005                     }
1006                 }
1007                 NativeLibKind::Framework => {
1008                     // ld-only syntax, since there are no frameworks in MSVC
1009                     Some(format!("-framework {}", name))
1010                 }
1011                 // These are included, no need to print them
1012                 NativeLibKind::StaticBundle | NativeLibKind::RawDylib => None,
1013             }
1014         })
1015         .collect();
1016     if !lib_args.is_empty() {
1017         sess.note_without_error(
1018             "Link against the following native artifacts when linking \
1019                                  against this static library. The order and any duplication \
1020                                  can be significant on some platforms.",
1021         );
1022         // Prefix for greppability
1023         sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1024     }
1025 }
1026
1027 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1028     let fs = sess.target_filesearch(PathKind::Native);
1029     let file_path = fs.get_lib_path().join(name);
1030     if file_path.exists() {
1031         return file_path;
1032     }
1033     // Special directory with objects used only in self-contained linkage mode
1034     if self_contained {
1035         let file_path = fs.get_self_contained_lib_path().join(name);
1036         if file_path.exists() {
1037             return file_path;
1038         }
1039     }
1040     for search_path in fs.search_paths() {
1041         let file_path = search_path.dir.join(name);
1042         if file_path.exists() {
1043             return file_path;
1044         }
1045     }
1046     PathBuf::from(name)
1047 }
1048
1049 fn exec_linker(
1050     sess: &Session,
1051     cmd: &Command,
1052     out_filename: &Path,
1053     tmpdir: &Path,
1054 ) -> io::Result<Output> {
1055     // When attempting to spawn the linker we run a risk of blowing out the
1056     // size limits for spawning a new process with respect to the arguments
1057     // we pass on the command line.
1058     //
1059     // Here we attempt to handle errors from the OS saying "your list of
1060     // arguments is too big" by reinvoking the linker again with an `@`-file
1061     // that contains all the arguments. The theory is that this is then
1062     // accepted on all linkers and the linker will read all its options out of
1063     // there instead of looking at the command line.
1064     if !cmd.very_likely_to_exceed_some_spawn_limit() {
1065         match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1066             Ok(child) => {
1067                 let output = child.wait_with_output();
1068                 flush_linked_file(&output, out_filename)?;
1069                 return output;
1070             }
1071             Err(ref e) if command_line_too_big(e) => {
1072                 info!("command line to linker was too big: {}", e);
1073             }
1074             Err(e) => return Err(e),
1075         }
1076     }
1077
1078     info!("falling back to passing arguments to linker via an @-file");
1079     let mut cmd2 = cmd.clone();
1080     let mut args = String::new();
1081     for arg in cmd2.take_args() {
1082         args.push_str(
1083             &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1084                 .to_string(),
1085         );
1086         args.push('\n');
1087     }
1088     let file = tmpdir.join("linker-arguments");
1089     let bytes = if sess.target.is_like_msvc {
1090         let mut out = Vec::with_capacity((1 + args.len()) * 2);
1091         // start the stream with a UTF-16 BOM
1092         for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1093             // encode in little endian
1094             out.push(c as u8);
1095             out.push((c >> 8) as u8);
1096         }
1097         out
1098     } else {
1099         args.into_bytes()
1100     };
1101     fs::write(&file, &bytes)?;
1102     cmd2.arg(format!("@{}", file.display()));
1103     info!("invoking linker {:?}", cmd2);
1104     let output = cmd2.output();
1105     flush_linked_file(&output, out_filename)?;
1106     return output;
1107
1108     #[cfg(unix)]
1109     fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1110         Ok(())
1111     }
1112
1113     #[cfg(windows)]
1114     fn flush_linked_file(
1115         command_output: &io::Result<Output>,
1116         out_filename: &Path,
1117     ) -> io::Result<()> {
1118         // On Windows, under high I/O load, output buffers are sometimes not flushed,
1119         // even long after process exit, causing nasty, non-reproducible output bugs.
1120         //
1121         // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1122         //
1123         // А full writeup of the original Chrome bug can be found at
1124         // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1125
1126         if let &Ok(ref out) = command_output {
1127             if out.status.success() {
1128                 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1129                     of.sync_all()?;
1130                 }
1131             }
1132         }
1133
1134         Ok(())
1135     }
1136
1137     #[cfg(unix)]
1138     fn command_line_too_big(err: &io::Error) -> bool {
1139         err.raw_os_error() == Some(::libc::E2BIG)
1140     }
1141
1142     #[cfg(windows)]
1143     fn command_line_too_big(err: &io::Error) -> bool {
1144         const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1145         err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1146     }
1147
1148     struct Escape<'a> {
1149         arg: &'a str,
1150         is_like_msvc: bool,
1151     }
1152
1153     impl<'a> fmt::Display for Escape<'a> {
1154         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1155             if self.is_like_msvc {
1156                 // This is "documented" at
1157                 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1158                 //
1159                 // Unfortunately there's not a great specification of the
1160                 // syntax I could find online (at least) but some local
1161                 // testing showed that this seemed sufficient-ish to catch
1162                 // at least a few edge cases.
1163                 write!(f, "\"")?;
1164                 for c in self.arg.chars() {
1165                     match c {
1166                         '"' => write!(f, "\\{}", c)?,
1167                         c => write!(f, "{}", c)?,
1168                     }
1169                 }
1170                 write!(f, "\"")?;
1171             } else {
1172                 // This is documented at https://linux.die.net/man/1/ld, namely:
1173                 //
1174                 // > Options in file are separated by whitespace. A whitespace
1175                 // > character may be included in an option by surrounding the
1176                 // > entire option in either single or double quotes. Any
1177                 // > character (including a backslash) may be included by
1178                 // > prefixing the character to be included with a backslash.
1179                 //
1180                 // We put an argument on each line, so all we need to do is
1181                 // ensure the line is interpreted as one whole argument.
1182                 for c in self.arg.chars() {
1183                     match c {
1184                         '\\' | ' ' => write!(f, "\\{}", c)?,
1185                         c => write!(f, "{}", c)?,
1186                     }
1187                 }
1188             }
1189             Ok(())
1190         }
1191     }
1192 }
1193
1194 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1195     let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1196         (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1197         (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1198         (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1199         (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1200         (_, true, _) => LinkOutputKind::StaticDylib,
1201         (_, false, _) => LinkOutputKind::DynamicDylib,
1202     };
1203
1204     // Adjust the output kind to target capabilities.
1205     let opts = &sess.target;
1206     let pic_exe_supported = opts.position_independent_executables;
1207     let static_pic_exe_supported = opts.static_position_independent_executables;
1208     let static_dylib_supported = opts.crt_static_allows_dylibs;
1209     match kind {
1210         LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1211         LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1212         LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1213         _ => kind,
1214     }
1215 }
1216
1217 // Returns true if linker is located within sysroot
1218 fn detect_self_contained_mingw(sess: &Session) -> bool {
1219     let (linker, _) = linker_and_flavor(&sess);
1220     // Assume `-C linker=rust-lld` as self-contained mode
1221     if linker == Path::new("rust-lld") {
1222         return true;
1223     }
1224     let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1225         linker.with_extension("exe")
1226     } else {
1227         linker
1228     };
1229     for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1230         let full_path = dir.join(&linker_with_extension);
1231         // If linker comes from sysroot assume self-contained mode
1232         if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1233             return false;
1234         }
1235     }
1236     true
1237 }
1238
1239 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1240 /// We only provide such support for a very limited number of targets.
1241 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1242     if let Some(self_contained) = sess.opts.cg.link_self_contained {
1243         return self_contained;
1244     }
1245
1246     match sess.target.crt_objects_fallback {
1247         // FIXME: Find a better heuristic for "native musl toolchain is available",
1248         // based on host and linker path, for example.
1249         // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1250         Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1251         Some(CrtObjectsFallback::Mingw) => {
1252             sess.host == sess.target
1253                 && sess.target.vendor != "uwp"
1254                 && detect_self_contained_mingw(&sess)
1255         }
1256         // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1257         Some(CrtObjectsFallback::Wasm) => true,
1258         None => false,
1259     }
1260 }
1261
1262 /// Add pre-link object files defined by the target spec.
1263 fn add_pre_link_objects(
1264     cmd: &mut dyn Linker,
1265     sess: &Session,
1266     link_output_kind: LinkOutputKind,
1267     self_contained: bool,
1268 ) {
1269     let opts = &sess.target;
1270     let objects =
1271         if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1272     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1273         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1274     }
1275 }
1276
1277 /// Add post-link object files defined by the target spec.
1278 fn add_post_link_objects(
1279     cmd: &mut dyn Linker,
1280     sess: &Session,
1281     link_output_kind: LinkOutputKind,
1282     self_contained: bool,
1283 ) {
1284     let opts = &sess.target;
1285     let objects =
1286         if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1287     for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1288         cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1289     }
1290 }
1291
1292 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1293 /// FIXME: Determine where exactly these args need to be inserted.
1294 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1295     if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1296         cmd.args(args);
1297     }
1298     cmd.args(&sess.opts.debugging_opts.pre_link_args);
1299 }
1300
1301 /// Add a link script embedded in the target, if applicable.
1302 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1303     match (crate_type, &sess.target.link_script) {
1304         (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1305             if !sess.target.linker_is_gnu {
1306                 sess.fatal("can only use link script when linking with GNU-like linker");
1307             }
1308
1309             let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1310
1311             let path = tmpdir.join(file_name);
1312             if let Err(e) = fs::write(&path, script) {
1313                 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1314             }
1315
1316             cmd.arg("--script");
1317             cmd.arg(path);
1318         }
1319         _ => {}
1320     }
1321 }
1322
1323 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1324 /// FIXME: Determine where exactly these args need to be inserted.
1325 fn add_user_defined_link_args(
1326     cmd: &mut dyn Linker,
1327     sess: &Session,
1328     codegen_results: &CodegenResults,
1329 ) {
1330     cmd.args(&sess.opts.cg.link_args);
1331     cmd.args(&*codegen_results.crate_info.link_args);
1332 }
1333
1334 /// Add arbitrary "late link" args defined by the target spec.
1335 /// FIXME: Determine where exactly these args need to be inserted.
1336 fn add_late_link_args(
1337     cmd: &mut dyn Linker,
1338     sess: &Session,
1339     flavor: LinkerFlavor,
1340     crate_type: CrateType,
1341     codegen_results: &CodegenResults,
1342 ) {
1343     let any_dynamic_crate = crate_type == CrateType::Dylib
1344         || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1345             *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1346         });
1347     if any_dynamic_crate {
1348         if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1349             cmd.args(args);
1350         }
1351     } else {
1352         if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1353             cmd.args(args);
1354         }
1355     }
1356     if let Some(args) = sess.target.late_link_args.get(&flavor) {
1357         cmd.args(args);
1358     }
1359 }
1360
1361 /// Add arbitrary "post-link" args defined by the target spec.
1362 /// FIXME: Determine where exactly these args need to be inserted.
1363 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1364     if let Some(args) = sess.target.post_link_args.get(&flavor) {
1365         cmd.args(args);
1366     }
1367 }
1368
1369 /// Add object files containing code from the current crate.
1370 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1371     for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1372         cmd.add_object(obj);
1373     }
1374 }
1375
1376 /// Add object files for allocator code linked once for the whole crate tree.
1377 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1378     if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1379         cmd.add_object(obj);
1380     }
1381 }
1382
1383 /// Add object files containing metadata for the current crate.
1384 fn add_local_crate_metadata_objects(
1385     cmd: &mut dyn Linker,
1386     crate_type: CrateType,
1387     codegen_results: &CodegenResults,
1388 ) {
1389     // When linking a dynamic library, we put the metadata into a section of the
1390     // executable. This metadata is in a separate object file from the main
1391     // object file, so we link that in here.
1392     if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1393         if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1394         {
1395             cmd.add_object(obj);
1396         }
1397     }
1398 }
1399
1400 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1401 /// all its dependency crates.
1402 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1403 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1404     cmd: &mut dyn Linker,
1405     sess: &'a Session,
1406     crate_type: CrateType,
1407     codegen_results: &CodegenResults,
1408     tmpdir: &Path,
1409 ) {
1410     // Take careful note of the ordering of the arguments we pass to the linker
1411     // here. Linkers will assume that things on the left depend on things to the
1412     // right. Things on the right cannot depend on things on the left. This is
1413     // all formally implemented in terms of resolving symbols (libs on the right
1414     // resolve unknown symbols of libs on the left, but not vice versa).
1415     //
1416     // For this reason, we have organized the arguments we pass to the linker as
1417     // such:
1418     //
1419     // 1. The local object that LLVM just generated
1420     // 2. Local native libraries
1421     // 3. Upstream rust libraries
1422     // 4. Upstream native libraries
1423     //
1424     // The rationale behind this ordering is that those items lower down in the
1425     // list can't depend on items higher up in the list. For example nothing can
1426     // depend on what we just generated (e.g., that'd be a circular dependency).
1427     // Upstream rust libraries are not allowed to depend on our local native
1428     // libraries as that would violate the structure of the DAG, in that
1429     // scenario they are required to link to them as well in a shared fashion.
1430     //
1431     // Note that upstream rust libraries may contain native dependencies as
1432     // well, but they also can't depend on what we just started to add to the
1433     // link line. And finally upstream native libraries can't depend on anything
1434     // in this DAG so far because they're only dylibs and dylibs can only depend
1435     // on other dylibs (e.g., other native deps).
1436     //
1437     // If -Zlink-native-libraries=false is set, then the assumption is that an
1438     // external build system already has the native dependencies defined, and it
1439     // will provide them to the linker itself.
1440     if sess.opts.debugging_opts.link_native_libraries {
1441         add_local_native_libraries(cmd, sess, codegen_results);
1442     }
1443     add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1444     if sess.opts.debugging_opts.link_native_libraries {
1445         add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1446     }
1447 }
1448
1449 /// Add sysroot and other globally set directories to the directory search list.
1450 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1451     // The default library location, we need this to find the runtime.
1452     // The location of crates will be determined as needed.
1453     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1454     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1455
1456     // Special directory with libraries used only in self-contained linkage mode
1457     if self_contained {
1458         let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1459         cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1460     }
1461 }
1462
1463 /// Add options making relocation sections in the produced ELF files read-only
1464 /// and suppressing lazy binding.
1465 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1466     match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.relro_level) {
1467         RelroLevel::Full => cmd.full_relro(),
1468         RelroLevel::Partial => cmd.partial_relro(),
1469         RelroLevel::Off => cmd.no_relro(),
1470         RelroLevel::None => {}
1471     }
1472 }
1473
1474 /// Add library search paths used at runtime by dynamic linkers.
1475 fn add_rpath_args(
1476     cmd: &mut dyn Linker,
1477     sess: &Session,
1478     codegen_results: &CodegenResults,
1479     out_filename: &Path,
1480 ) {
1481     // FIXME (#2397): At some point we want to rpath our guesses as to
1482     // where extern libraries might live, based on the
1483     // addl_lib_search_paths
1484     if sess.opts.cg.rpath {
1485         let target_triple = sess.opts.target_triple.triple();
1486         let mut get_install_prefix_lib_path = || {
1487             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1488             let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1489             let mut path = PathBuf::from(install_prefix);
1490             path.push(&tlib);
1491
1492             path
1493         };
1494         let mut rpath_config = RPathConfig {
1495             used_crates: &codegen_results.crate_info.used_crates_dynamic,
1496             out_filename: out_filename.to_path_buf(),
1497             has_rpath: sess.target.has_rpath,
1498             is_like_osx: sess.target.is_like_osx,
1499             linker_is_gnu: sess.target.linker_is_gnu,
1500             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1501         };
1502         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1503     }
1504 }
1505
1506 /// Produce the linker command line containing linker path and arguments.
1507 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1508 /// by the user without creating a custom target specification.
1509 /// `OBJECT-FILES` specify whether the arguments can add object files.
1510 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1511 /// or by the target spec can be inserted here.
1512 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1513 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1514     path: &Path,
1515     flavor: LinkerFlavor,
1516     sess: &'a Session,
1517     crate_type: CrateType,
1518     tmpdir: &Path,
1519     out_filename: &Path,
1520     codegen_results: &CodegenResults,
1521     target_cpu: &str,
1522 ) -> Command {
1523     let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1524     let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1525     // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1526     // to the linker args construction.
1527     assert!(base_cmd.get_args().is_empty() || sess.target.vendor == "uwp");
1528     let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1529     let link_output_kind = link_output_kind(sess, crate_type);
1530
1531     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1532     add_pre_link_args(cmd, sess, flavor);
1533
1534     // NO-OPT-OUT, OBJECT-FILES-NO
1535     add_apple_sdk(cmd, sess, flavor);
1536
1537     // NO-OPT-OUT
1538     add_link_script(cmd, sess, tmpdir, crate_type);
1539
1540     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1541     if sess.target.is_like_fuchsia && crate_type == CrateType::Executable {
1542         let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1543             "asan/"
1544         } else {
1545             ""
1546         };
1547         cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1548     }
1549
1550     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1551     if sess.target.eh_frame_header {
1552         cmd.add_eh_frame_header();
1553     }
1554
1555     // NO-OPT-OUT, OBJECT-FILES-NO
1556     if crt_objects_fallback {
1557         cmd.no_crt_objects();
1558     }
1559
1560     // NO-OPT-OUT, OBJECT-FILES-YES
1561     add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1562
1563     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1564     if sess.target.is_like_emscripten {
1565         cmd.arg("-s");
1566         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1567             "DISABLE_EXCEPTION_CATCHING=1"
1568         } else {
1569             "DISABLE_EXCEPTION_CATCHING=0"
1570         });
1571     }
1572
1573     // OBJECT-FILES-YES, AUDIT-ORDER
1574     link_sanitizers(sess, crate_type, cmd);
1575
1576     // OBJECT-FILES-NO, AUDIT-ORDER
1577     // Linker plugins should be specified early in the list of arguments
1578     // FIXME: How "early" exactly?
1579     cmd.linker_plugin_lto();
1580
1581     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1582     // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1583     add_library_search_dirs(cmd, sess, crt_objects_fallback);
1584
1585     // OBJECT-FILES-YES
1586     add_local_crate_regular_objects(cmd, codegen_results);
1587
1588     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1589     cmd.output_filename(out_filename);
1590
1591     // OBJECT-FILES-NO, AUDIT-ORDER
1592     if crate_type == CrateType::Executable && sess.target.is_like_windows {
1593         if let Some(ref s) = codegen_results.windows_subsystem {
1594             cmd.subsystem(s);
1595         }
1596     }
1597
1598     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1599     // If we're building something like a dynamic library then some platforms
1600     // need to make sure that all symbols are exported correctly from the
1601     // dynamic library.
1602     cmd.export_symbols(tmpdir, crate_type);
1603
1604     // OBJECT-FILES-YES
1605     add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1606
1607     // OBJECT-FILES-YES
1608     add_local_crate_allocator_objects(cmd, codegen_results);
1609
1610     // OBJECT-FILES-NO, AUDIT-ORDER
1611     // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1612     // Try to strip as much out of the generated object by removing unused
1613     // sections if possible. See more comments in linker.rs
1614     if !sess.link_dead_code() {
1615         let keep_metadata = crate_type == CrateType::Dylib;
1616         cmd.gc_sections(keep_metadata);
1617     }
1618
1619     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1620     cmd.set_output_kind(link_output_kind, out_filename);
1621
1622     // OBJECT-FILES-NO, AUDIT-ORDER
1623     add_relro_args(cmd, sess);
1624
1625     // OBJECT-FILES-NO, AUDIT-ORDER
1626     // Pass optimization flags down to the linker.
1627     cmd.optimize();
1628
1629     // OBJECT-FILES-NO, AUDIT-ORDER
1630     // Pass debuginfo and strip flags down to the linker.
1631     cmd.debuginfo(sess.opts.debugging_opts.strip);
1632
1633     // OBJECT-FILES-NO, AUDIT-ORDER
1634     // We want to prevent the compiler from accidentally leaking in any system libraries,
1635     // so by default we tell linkers not to link to any default libraries.
1636     if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
1637         cmd.no_default_libraries();
1638     }
1639
1640     // OBJECT-FILES-YES
1641     link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1642         cmd,
1643         sess,
1644         crate_type,
1645         codegen_results,
1646         tmpdir,
1647     );
1648
1649     // OBJECT-FILES-NO, AUDIT-ORDER
1650     if sess.opts.cg.profile_generate.enabled() || sess.opts.debugging_opts.instrument_coverage {
1651         cmd.pgo_gen();
1652     }
1653
1654     // OBJECT-FILES-NO, AUDIT-ORDER
1655     if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1656         cmd.control_flow_guard();
1657     }
1658
1659     // OBJECT-FILES-NO, AUDIT-ORDER
1660     add_rpath_args(cmd, sess, codegen_results, out_filename);
1661
1662     // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1663     add_user_defined_link_args(cmd, sess, codegen_results);
1664
1665     // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1666     cmd.finalize();
1667
1668     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1669     add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1670
1671     // NO-OPT-OUT, OBJECT-FILES-YES
1672     add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1673
1674     // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1675     add_post_link_args(cmd, sess, flavor);
1676
1677     cmd.take_cmd()
1678 }
1679
1680 // # Native library linking
1681 //
1682 // User-supplied library search paths (-L on the command line). These are
1683 // the same paths used to find Rust crates, so some of them may have been
1684 // added already by the previous crate linking code. This only allows them
1685 // to be found at compile time so it is still entirely up to outside
1686 // forces to make sure that library can be found at runtime.
1687 //
1688 // Also note that the native libraries linked here are only the ones located
1689 // in the current crate. Upstream crates with native library dependencies
1690 // may have their native library pulled in above.
1691 fn add_local_native_libraries(
1692     cmd: &mut dyn Linker,
1693     sess: &Session,
1694     codegen_results: &CodegenResults,
1695 ) {
1696     let filesearch = sess.target_filesearch(PathKind::All);
1697     for search_path in filesearch.search_paths() {
1698         match search_path.kind {
1699             PathKind::Framework => {
1700                 cmd.framework_path(&search_path.dir);
1701             }
1702             _ => {
1703                 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1704             }
1705         }
1706     }
1707
1708     let relevant_libs =
1709         codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1710
1711     let search_path = archive_search_paths(sess);
1712     for lib in relevant_libs {
1713         let name = match lib.name {
1714             Some(l) => l,
1715             None => continue,
1716         };
1717         match lib.kind {
1718             NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1719             NativeLibKind::Framework => cmd.link_framework(name),
1720             NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1721             NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1722             NativeLibKind::RawDylib => {
1723                 // FIXME(#58713): Proper handling for raw dylibs.
1724                 bug!("raw_dylib feature not yet implemented");
1725             }
1726         }
1727     }
1728 }
1729
1730 // # Rust Crate linking
1731 //
1732 // Rust crates are not considered at all when creating an rlib output. All
1733 // dependencies will be linked when producing the final output (instead of
1734 // the intermediate rlib version)
1735 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1736     cmd: &mut dyn Linker,
1737     sess: &'a Session,
1738     codegen_results: &CodegenResults,
1739     crate_type: CrateType,
1740     tmpdir: &Path,
1741 ) {
1742     // All of the heavy lifting has previously been accomplished by the
1743     // dependency_format module of the compiler. This is just crawling the
1744     // output of that module, adding crates as necessary.
1745     //
1746     // Linking to a rlib involves just passing it to the linker (the linker
1747     // will slurp up the object files inside), and linking to a dynamic library
1748     // involves just passing the right -l flag.
1749
1750     let (_, data) = codegen_results
1751         .crate_info
1752         .dependency_formats
1753         .iter()
1754         .find(|(ty, _)| *ty == crate_type)
1755         .expect("failed to find crate type in dependency format list");
1756
1757     // Invoke get_used_crates to ensure that we get a topological sorting of
1758     // crates.
1759     let deps = &codegen_results.crate_info.used_crates_dynamic;
1760
1761     // There's a few internal crates in the standard library (aka libcore and
1762     // libstd) which actually have a circular dependence upon one another. This
1763     // currently arises through "weak lang items" where libcore requires things
1764     // like `rust_begin_unwind` but libstd ends up defining it. To get this
1765     // circular dependence to work correctly in all situations we'll need to be
1766     // sure to correctly apply the `--start-group` and `--end-group` options to
1767     // GNU linkers, otherwise if we don't use any other symbol from the standard
1768     // library it'll get discarded and the whole application won't link.
1769     //
1770     // In this loop we're calculating the `group_end`, after which crate to
1771     // pass `--end-group` and `group_start`, before which crate to pass
1772     // `--start-group`. We currently do this by passing `--end-group` after
1773     // the first crate (when iterating backwards) that requires a lang item
1774     // defined somewhere else. Once that's set then when we've defined all the
1775     // necessary lang items we'll pass `--start-group`.
1776     //
1777     // Note that this isn't amazing logic for now but it should do the trick
1778     // for the current implementation of the standard library.
1779     let mut group_end = None;
1780     let mut group_start = None;
1781     // Crates available for linking thus far.
1782     let mut available = FxHashSet::default();
1783     // Crates required to satisfy dependencies discovered so far.
1784     let mut required = FxHashSet::default();
1785
1786     let info = &codegen_results.crate_info;
1787     for &(cnum, _) in deps.iter().rev() {
1788         if let Some(missing) = info.missing_lang_items.get(&cnum) {
1789             let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1790             required.extend(missing_crates);
1791         }
1792
1793         required.insert(Some(cnum));
1794         available.insert(Some(cnum));
1795
1796         if required.len() > available.len() && group_end.is_none() {
1797             group_end = Some(cnum);
1798         }
1799         if required.len() == available.len() && group_end.is_some() {
1800             group_start = Some(cnum);
1801             break;
1802         }
1803     }
1804
1805     // If we didn't end up filling in all lang items from upstream crates then
1806     // we'll be filling it in with our crate. This probably means we're the
1807     // standard library itself, so skip this for now.
1808     if group_end.is_some() && group_start.is_none() {
1809         group_end = None;
1810     }
1811
1812     let mut compiler_builtins = None;
1813
1814     for &(cnum, _) in deps.iter() {
1815         if group_start == Some(cnum) {
1816             cmd.group_start();
1817         }
1818
1819         // We may not pass all crates through to the linker. Some crates may
1820         // appear statically in an existing dylib, meaning we'll pick up all the
1821         // symbols from the dylib.
1822         let src = &codegen_results.crate_info.used_crate_source[&cnum];
1823         match data[cnum.as_usize() - 1] {
1824             _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1825                 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1826             }
1827             // compiler-builtins are always placed last to ensure that they're
1828             // linked correctly.
1829             _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1830                 assert!(compiler_builtins.is_none());
1831                 compiler_builtins = Some(cnum);
1832             }
1833             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1834             Linkage::Static => {
1835                 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1836             }
1837             Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1838         }
1839
1840         if group_end == Some(cnum) {
1841             cmd.group_end();
1842         }
1843     }
1844
1845     // compiler-builtins are always placed last to ensure that they're
1846     // linked correctly.
1847     // We must always link the `compiler_builtins` crate statically. Even if it
1848     // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1849     // is used)
1850     if let Some(cnum) = compiler_builtins {
1851         add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1852     }
1853
1854     // Converts a library file-stem into a cc -l argument
1855     fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
1856         if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
1857     }
1858
1859     // Adds the static "rlib" versions of all crates to the command line.
1860     // There's a bit of magic which happens here specifically related to LTO and
1861     // dynamic libraries. Specifically:
1862     //
1863     // * For LTO, we remove upstream object files.
1864     // * For dylibs we remove metadata and bytecode from upstream rlibs
1865     //
1866     // When performing LTO, almost(*) all of the bytecode from the upstream
1867     // libraries has already been included in our object file output. As a
1868     // result we need to remove the object files in the upstream libraries so
1869     // the linker doesn't try to include them twice (or whine about duplicate
1870     // symbols). We must continue to include the rest of the rlib, however, as
1871     // it may contain static native libraries which must be linked in.
1872     //
1873     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1874     // their bytecode wasn't included. The object files in those libraries must
1875     // still be passed to the linker.
1876     //
1877     // When making a dynamic library, linkers by default don't include any
1878     // object files in an archive if they're not necessary to resolve the link.
1879     // We basically want to convert the archive (rlib) to a dylib, though, so we
1880     // *do* want everything included in the output, regardless of whether the
1881     // linker thinks it's needed or not. As a result we must use the
1882     // --whole-archive option (or the platform equivalent). When using this
1883     // option the linker will fail if there are non-objects in the archive (such
1884     // as our own metadata and/or bytecode). All in all, for rlibs to be
1885     // entirely included in dylibs, we need to remove all non-object files.
1886     //
1887     // Note, however, that if we're not doing LTO or we're not producing a dylib
1888     // (aka we're making an executable), we can just pass the rlib blindly to
1889     // the linker (fast) because it's fine if it's not actually included as
1890     // we're at the end of the dependency chain.
1891     fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1892         cmd: &mut dyn Linker,
1893         sess: &'a Session,
1894         codegen_results: &CodegenResults,
1895         tmpdir: &Path,
1896         crate_type: CrateType,
1897         cnum: CrateNum,
1898     ) {
1899         let src = &codegen_results.crate_info.used_crate_source[&cnum];
1900         let cratepath = &src.rlib.as_ref().unwrap().0;
1901
1902         // See the comment above in `link_staticlib` and `link_rlib` for why if
1903         // there's a static library that's not relevant we skip all object
1904         // files.
1905         let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1906         let skip_native = native_libs
1907             .iter()
1908             .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1909
1910         if (!are_upstream_rust_objects_already_included(sess)
1911             || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1912             && crate_type != CrateType::Dylib
1913             && !skip_native
1914         {
1915             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1916             return;
1917         }
1918
1919         let dst = tmpdir.join(cratepath.file_name().unwrap());
1920         let name = cratepath.file_name().unwrap().to_str().unwrap();
1921         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1922
1923         sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1924             let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1925             archive.update_symbols();
1926
1927             let mut any_objects = false;
1928             for f in archive.src_files() {
1929                 if f == METADATA_FILENAME {
1930                     archive.remove_file(&f);
1931                     continue;
1932                 }
1933
1934                 let canonical = f.replace("-", "_");
1935                 let canonical_name = name.replace("-", "_");
1936
1937                 let is_rust_object =
1938                     canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
1939
1940                 // If we've been requested to skip all native object files
1941                 // (those not generated by the rust compiler) then we can skip
1942                 // this file. See above for why we may want to do this.
1943                 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1944
1945                 // If we're performing LTO and this is a rust-generated object
1946                 // file, then we don't need the object file as it's part of the
1947                 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1948                 // though, so we let that object file slide.
1949                 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
1950                     && is_rust_object
1951                     && (sess.target.no_builtins
1952                         || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1953
1954                 if skip_because_cfg_say_so || skip_because_lto {
1955                     archive.remove_file(&f);
1956                 } else {
1957                     any_objects = true;
1958                 }
1959             }
1960
1961             if !any_objects {
1962                 return;
1963             }
1964             archive.build();
1965
1966             // If we're creating a dylib, then we need to include the
1967             // whole of each object in our archive into that artifact. This is
1968             // because a `dylib` can be reused as an intermediate artifact.
1969             //
1970             // Note, though, that we don't want to include the whole of a
1971             // compiler-builtins crate (e.g., compiler-rt) because it'll get
1972             // repeatedly linked anyway.
1973             if crate_type == CrateType::Dylib
1974                 && codegen_results.crate_info.compiler_builtins != Some(cnum)
1975             {
1976                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1977             } else {
1978                 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1979             }
1980         });
1981     }
1982
1983     // Same thing as above, but for dynamic crates instead of static crates.
1984     fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1985         // Just need to tell the linker about where the library lives and
1986         // what its name is
1987         let parent = cratepath.parent();
1988         if let Some(dir) = parent {
1989             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1990         }
1991         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1992         cmd.link_rust_dylib(
1993             Symbol::intern(&unlib(&sess.target, filestem)),
1994             parent.unwrap_or(Path::new("")),
1995         );
1996     }
1997 }
1998
1999 // Link in all of our upstream crates' native dependencies. Remember that
2000 // all of these upstream native dependencies are all non-static
2001 // dependencies. We've got two cases then:
2002 //
2003 // 1. The upstream crate is an rlib. In this case we *must* link in the
2004 // native dependency because the rlib is just an archive.
2005 //
2006 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
2007 // have the dependency present on the system somewhere. Thus, we don't
2008 // gain a whole lot from not linking in the dynamic dependency to this
2009 // crate as well.
2010 //
2011 // The use case for this is a little subtle. In theory the native
2012 // dependencies of a crate are purely an implementation detail of the crate
2013 // itself, but the problem arises with generic and inlined functions. If a
2014 // generic function calls a native function, then the generic function must
2015 // be instantiated in the target crate, meaning that the native symbol must
2016 // also be resolved in the target crate.
2017 fn add_upstream_native_libraries(
2018     cmd: &mut dyn Linker,
2019     sess: &Session,
2020     codegen_results: &CodegenResults,
2021     crate_type: CrateType,
2022 ) {
2023     // Be sure to use a topological sorting of crates because there may be
2024     // interdependencies between native libraries. When passing -nodefaultlibs,
2025     // for example, almost all native libraries depend on libc, so we have to
2026     // make sure that's all the way at the right (liblibc is near the base of
2027     // the dependency chain).
2028     //
2029     // This passes RequireStatic, but the actual requirement doesn't matter,
2030     // we're just getting an ordering of crate numbers, we're not worried about
2031     // the paths.
2032     let (_, data) = codegen_results
2033         .crate_info
2034         .dependency_formats
2035         .iter()
2036         .find(|(ty, _)| *ty == crate_type)
2037         .expect("failed to find crate type in dependency format list");
2038
2039     let crates = &codegen_results.crate_info.used_crates_static;
2040     for &(cnum, _) in crates {
2041         for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2042             let name = match lib.name {
2043                 Some(l) => l,
2044                 None => continue,
2045             };
2046             if !relevant_lib(sess, &lib) {
2047                 continue;
2048             }
2049             match lib.kind {
2050                 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2051                 NativeLibKind::Framework => cmd.link_framework(name),
2052                 NativeLibKind::StaticNoBundle => {
2053                     // Link "static-nobundle" native libs only if the crate they originate from
2054                     // is being linked statically to the current crate.  If it's linked dynamically
2055                     // or is an rlib already included via some other dylib crate, the symbols from
2056                     // native libs will have already been included in that dylib.
2057                     if data[cnum.as_usize() - 1] == Linkage::Static {
2058                         cmd.link_staticlib(name)
2059                     }
2060                 }
2061                 // ignore statically included native libraries here as we've
2062                 // already included them when we included the rust library
2063                 // previously
2064                 NativeLibKind::StaticBundle => {}
2065                 NativeLibKind::RawDylib => {
2066                     // FIXME(#58713): Proper handling for raw dylibs.
2067                     bug!("raw_dylib feature not yet implemented");
2068                 }
2069             }
2070         }
2071     }
2072 }
2073
2074 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2075     match lib.cfg {
2076         Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2077         None => true,
2078     }
2079 }
2080
2081 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2082     match sess.lto() {
2083         config::Lto::Fat => true,
2084         config::Lto::Thin => {
2085             // If we defer LTO to the linker, we haven't run LTO ourselves, so
2086             // any upstream object files have not been copied yet.
2087             !sess.opts.cg.linker_plugin_lto.enabled()
2088         }
2089         config::Lto::No | config::Lto::ThinLocal => false,
2090     }
2091 }
2092
2093 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2094     let arch = &sess.target.arch;
2095     let os = &sess.target.os;
2096     let llvm_target = &sess.target.llvm_target;
2097     if sess.target.vendor != "apple"
2098         || !matches!(os.as_str(), "ios" | "tvos")
2099         || flavor != LinkerFlavor::Gcc
2100     {
2101         return;
2102     }
2103     let sdk_name = match (arch.as_str(), os.as_str()) {
2104         ("aarch64", "tvos") => "appletvos",
2105         ("x86_64", "tvos") => "appletvsimulator",
2106         ("arm", "ios") => "iphoneos",
2107         ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2108         ("aarch64", "ios") => "iphoneos",
2109         ("x86", "ios") => "iphonesimulator",
2110         ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2111         ("x86_64", "ios") => "iphonesimulator",
2112         _ => {
2113             sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2114             return;
2115         }
2116     };
2117     let sdk_root = match get_apple_sdk_root(sdk_name) {
2118         Ok(s) => s,
2119         Err(e) => {
2120             sess.err(&e);
2121             return;
2122         }
2123     };
2124     let arch_name = llvm_target.split('-').next().expect("LLVM target must have a hyphen");
2125     cmd.args(&["-arch", arch_name, "-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2126 }
2127
2128 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2129     // Following what clang does
2130     // (https://github.com/llvm/llvm-project/blob/
2131     // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2132     // to allow the SDK path to be set. (For clang, xcrun sets
2133     // SDKROOT; for rustc, the user or build system can set it, or we
2134     // can fall back to checking for xcrun on PATH.)
2135     if let Ok(sdkroot) = env::var("SDKROOT") {
2136         let p = Path::new(&sdkroot);
2137         match sdk_name {
2138             // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2139             "appletvos"
2140                 if sdkroot.contains("TVSimulator.platform")
2141                     || sdkroot.contains("MacOSX.platform") => {}
2142             "appletvsimulator"
2143                 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2144             "iphoneos"
2145                 if sdkroot.contains("iPhoneSimulator.platform")
2146                     || sdkroot.contains("MacOSX.platform") => {}
2147             "iphonesimulator"
2148                 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2149             }
2150             "macosx10.15"
2151                 if sdkroot.contains("iPhoneOS.platform")
2152                     || sdkroot.contains("iPhoneSimulator.platform") => {}
2153             // Ignore `SDKROOT` if it's not a valid path.
2154             _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2155             _ => return Ok(sdkroot),
2156         }
2157     }
2158     let res =
2159         Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2160             |output| {
2161                 if output.status.success() {
2162                     Ok(String::from_utf8(output.stdout).unwrap())
2163                 } else {
2164                     let error = String::from_utf8(output.stderr);
2165                     let error = format!("process exit with error: {}", error.unwrap());
2166                     Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2167                 }
2168             },
2169         );
2170
2171     match res {
2172         Ok(output) => Ok(output.trim().to_string()),
2173         Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),
2174     }
2175 }