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