1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::temp_dir::MaybeTempDir;
3 use rustc_fs_util::fix_windows_verbatim_for_gcc;
4 use rustc_hir::def_id::CrateNum;
5 use rustc_middle::middle::cstore::{EncodedMetadata, LibSource, NativeLib};
6 use rustc_middle::middle::dependency_format::Linkage;
7 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo};
8 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SanitizerSet};
9 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
10 use rustc_session::search_paths::PathKind;
11 use rustc_session::utils::NativeLibKind;
12 /// For all the linkers we support, and information they might
13 /// need out of the shared crate context before we get rid of it.
14 use rustc_session::{filesearch, Session};
15 use rustc_span::symbol::Symbol;
16 use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
17 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
18 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target};
20 use super::archive::ArchiveBuilder;
21 use super::command::Command;
22 use super::linker::{self, Linker};
23 use super::rpath::{self, RPathConfig};
24 use crate::{looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME};
26 use cc::windows_registry;
27 use tempfile::Builder as TempFileBuilder;
29 use std::ffi::OsString;
30 use std::path::{Path, PathBuf};
31 use std::process::{ExitStatus, Output, Stdio};
32 use std::{ascii, char, env, fmt, fs, io, mem, str};
34 pub fn remove(sess: &Session, path: &Path) {
35 if let Err(e) = fs::remove_file(path) {
36 sess.err(&format!("failed to remove {}: {}", path.display(), e));
40 /// Performs the linkage portion of the compilation phase. This will generate all
41 /// of the requested outputs for this compilation session.
42 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
44 codegen_results: &CodegenResults,
45 outputs: &OutputFilenames,
49 let _timer = sess.timer("link_binary");
50 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
51 for &crate_type in sess.crate_types().iter() {
52 // Ignore executable crates if we have -Z no-codegen, as they will error.
53 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
55 && crate_type == CrateType::Executable
60 if invalid_output_for_target(sess, crate_type) {
62 "invalid output type `{:?}` for target os `{}`",
64 sess.opts.target_triple
68 sess.time("link_binary_check_files_are_writeable", || {
69 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
70 check_file_is_writeable(obj, sess);
74 if outputs.outputs.should_codegen() {
75 let tmpdir = TempFileBuilder::new()
78 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
79 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
80 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
83 let _timer = sess.timer("link_rlib");
84 link_rlib::<B>(sess, codegen_results, RlibFlavor::Normal, &out_filename, &path)
87 CrateType::Staticlib => {
88 link_staticlib::<B>(sess, codegen_results, &out_filename, &path);
101 if sess.opts.json_artifact_notifications {
102 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
107 // Remove the temporary object file and metadata if we aren't saving temps
108 sess.time("link_binary_remove_temps", || {
109 if !sess.opts.cg.save_temps {
110 if sess.opts.output_types.should_codegen()
111 && !preserve_objects_for_their_debuginfo(sess)
113 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
117 if let Some(ref metadata_module) = codegen_results.metadata_module {
118 if let Some(ref obj) = metadata_module.object {
122 if let Some(ref allocator_module) = codegen_results.allocator_module {
123 if let Some(ref obj) = allocator_module.object {
131 // The third parameter is for env vars, used on windows to set up the
132 // path for MSVC to find its DLLs, and gcc to find its bundled
137 flavor: LinkerFlavor,
138 self_contained: bool,
140 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
142 // If our linker looks like a batch script on Windows then to execute this
143 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
144 // emscripten where the linker is `emcc.bat` and needs to be spawned as
145 // `cmd /c emcc.bat ...`.
147 // This worked historically but is needed manually since #42436 (regression
148 // was tagged as #42791) and some more info can be found on #44443 for
149 // emscripten itself.
150 let mut cmd = match linker.to_str() {
151 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
153 LinkerFlavor::Lld(f) => Command::lld(linker, f),
154 LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
155 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
157 _ => Command::new(linker),
161 // UWP apps have API restrictions enforced during Store submissions.
162 // To comply with the Windows App Certification Kit,
163 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
164 let t = &sess.target;
165 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
168 if let Some(ref tool) = msvc_tool {
169 let original_path = tool.path();
170 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
171 let arch = match t.arch.as_str() {
172 "x86_64" => Some("x64".to_string()),
173 "x86" => Some("x86".to_string()),
174 "aarch64" => Some("arm64".to_string()),
175 "arm" => Some("arm".to_string()),
178 if let Some(ref a) = arch {
179 // FIXME: Move this to `fn linker_with_args`.
180 let mut arg = OsString::from("/LIBPATH:");
181 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
184 warn!("arch is not supported");
187 warn!("MSVC root path lib location not found");
190 warn!("link.exe not found");
194 // The compiler's sysroot often has some bundled tools, so add it to the
195 // PATH for the child.
196 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(self_contained);
197 let mut msvc_changed_path = false;
198 if sess.target.is_like_msvc {
199 if let Some(ref tool) = msvc_tool {
200 cmd.args(tool.args());
201 for &(ref k, ref v) in tool.env() {
203 new_path.extend(env::split_paths(v));
204 msvc_changed_path = true;
212 if !msvc_changed_path {
213 if let Some(path) = env::var_os("PATH") {
214 new_path.extend(env::split_paths(&path));
217 cmd.env("PATH", env::join_paths(new_path).unwrap());
222 pub fn each_linked_rlib(
224 f: &mut dyn FnMut(CrateNum, &Path),
225 ) -> Result<(), String> {
226 let crates = info.used_crates_static.iter();
228 for (ty, list) in info.dependency_formats.iter() {
230 CrateType::Executable
231 | CrateType::Staticlib
233 | CrateType::ProcMacro => {
240 let fmts = match fmts {
242 None => return Err("could not find formats for rlibs".to_string()),
244 for &(cnum, ref path) in crates {
245 match fmts.get(cnum.as_usize() - 1) {
246 Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
248 None => return Err("could not find formats for rlibs".to_string()),
250 let name = &info.crate_name[&cnum];
251 let path = match *path {
252 LibSource::Some(ref p) => p,
253 LibSource::MetadataOnly => {
255 "could not find rlib for: `{}`, found rmeta (metadata) file",
259 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
266 /// We use a temp directory here to avoid races between concurrent rustc processes,
267 /// such as builds in the same directory using the same filename for metadata while
268 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
269 /// directory being searched for `extern crate` (observing an incomplete file).
270 /// The returned path is the temporary file containing the complete metadata.
271 pub fn emit_metadata(sess: &Session, metadata: &EncodedMetadata, tmpdir: &MaybeTempDir) -> PathBuf {
272 let out_filename = tmpdir.as_ref().join(METADATA_FILENAME);
273 let result = fs::write(&out_filename, &metadata.raw_data);
275 if let Err(e) = result {
276 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
284 // An rlib in its current incarnation is essentially a renamed .a file. The
285 // rlib primarily contains the object file of the crate, but it also contains
286 // all of the object files from native libraries. This is done by unzipping
287 // native libraries and inserting all of the contents into this archive.
288 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
290 codegen_results: &CodegenResults,
293 tmpdir: &MaybeTempDir,
295 info!("preparing rlib to {:?}", out_filename);
296 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
298 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
302 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
303 // we may not be configured to actually include a static library if we're
304 // adding it here. That's because later when we consume this rlib we'll
305 // decide whether we actually needed the static library or not.
307 // To do this "correctly" we'd need to keep track of which libraries added
308 // which object files to the archive. We don't do that here, however. The
309 // #[link(cfg(..))] feature is unstable, though, and only intended to get
310 // liblibc working. In that sense the check below just indicates that if
311 // there are any libraries we want to omit object files for at link time we
312 // just exclude all custom object files.
314 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
315 // feature then we'll need to figure out how to record what objects were
316 // loaded from the libraries found here and then encode that into the
317 // metadata of the rlib we're generating somehow.
318 for lib in codegen_results.crate_info.used_libraries.iter() {
320 NativeLibKind::StaticBundle => {}
321 NativeLibKind::StaticNoBundle
322 | NativeLibKind::Dylib
323 | NativeLibKind::Framework
324 | NativeLibKind::RawDylib
325 | NativeLibKind::Unspecified => continue,
327 if let Some(name) = lib.name {
328 ab.add_native_library(name);
332 // After adding all files to the archive, we need to update the
333 // symbol table of the archive.
336 // Note that it is important that we add all of our non-object "magical
337 // files" *after* all of the object files in the archive. The reason for
338 // this is as follows:
340 // * When performing LTO, this archive will be modified to remove
341 // objects from above. The reason for this is described below.
343 // * When the system linker looks at an archive, it will attempt to
344 // determine the architecture of the archive in order to see whether its
347 // The algorithm for this detection is: iterate over the files in the
348 // archive. Skip magical SYMDEF names. Interpret the first file as an
349 // object file. Read architecture from the object file.
351 // * As one can probably see, if "metadata" and "foo.bc" were placed
352 // before all of the objects, then the architecture of this archive would
353 // not be correctly inferred once 'foo.o' is removed.
355 // Basically, all this means is that this code should not move above the
358 RlibFlavor::Normal => {
359 // Instead of putting the metadata in an object file section, rlibs
360 // contain the metadata in a separate file.
361 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
363 // After adding all files to the archive, we need to update the
364 // symbol table of the archive. This currently dies on macOS (see
365 // #11162), and isn't necessary there anyway
366 if !sess.target.is_like_osx {
371 RlibFlavor::StaticlibBase => {
372 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
373 if let Some(obj) = obj {
382 // Create a static archive
384 // This is essentially the same thing as an rlib, but it also involves adding
385 // all of the upstream crates' objects into the archive. This will slurp in
386 // all of the native libraries of upstream dependencies as well.
388 // Additionally, there's no way for us to link dynamic libraries, so we warn
389 // about all dynamic library dependencies that they're not linked in.
391 // There's no need to include metadata in a static archive, so ensure to not
392 // link in the metadata object file (and also don't prepare the archive with a
394 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
396 codegen_results: &CodegenResults,
398 tempdir: &MaybeTempDir,
401 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
402 let mut all_native_libs = vec![];
404 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
405 let name = &codegen_results.crate_info.crate_name[&cnum];
406 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
408 // Here when we include the rlib into our staticlib we need to make a
409 // decision whether to include the extra object files along the way.
410 // These extra object files come from statically included native
411 // libraries, but they may be cfg'd away with #[link(cfg(..))].
413 // This unstable feature, though, only needs liblibc to work. The only
414 // use case there is where musl is statically included in liblibc.rlib,
415 // so if we don't want the included version we just need to skip it. As
416 // a result the logic here is that if *any* linked library is cfg'd away
417 // we just skip all object files.
419 // Clearly this is not sufficient for a general purpose feature, and
420 // we'd want to read from the library's metadata to determine which
421 // object files come from where and selectively skip them.
422 let skip_object_files = native_libs
424 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
428 are_upstream_rust_objects_already_included(sess)
429 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
434 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
436 if let Err(e) = res {
443 if !all_native_libs.is_empty() {
444 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
445 print_native_static_libs(sess, &all_native_libs);
450 // Create a dynamic library or executable
452 // This will invoke the system linker/cc to create the resulting file. This
453 // links to all upstream files as well.
454 fn link_natively<'a, B: ArchiveBuilder<'a>>(
456 crate_type: CrateType,
458 codegen_results: &CodegenResults,
462 info!("preparing {:?} to {:?}", crate_type, out_filename);
463 let (linker_path, flavor) = linker_and_flavor(sess);
464 let mut cmd = linker_with_args::<B>(
475 linker::disable_localization(&mut cmd);
477 for &(ref k, ref v) in &sess.target.link_env {
480 for k in &sess.target.link_env_remove {
484 if sess.opts.debugging_opts.print_link_args {
485 println!("{:?}", &cmd);
488 // May have not found libraries in the right formats.
489 sess.abort_if_errors();
491 // Invoke the system linker
493 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
498 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
499 let output = match prog {
500 Ok(ref output) => output,
503 if output.status.success() {
506 let mut out = output.stderr.clone();
507 out.extend(&output.stdout);
508 let out = String::from_utf8_lossy(&out);
510 // Check to see if the link failed with "unrecognized command line option:
511 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
512 // reperform the link step without the -no-pie option. This is safe because
513 // if the linker doesn't support -no-pie then it should not default to
514 // linking executables as pie. Different versions of gcc seem to use
515 // different quotes in the error message so don't check for them.
516 if sess.target.linker_is_gnu
517 && flavor != LinkerFlavor::Ld
518 && (out.contains("unrecognized command line option")
519 || out.contains("unknown argument"))
520 && out.contains("-no-pie")
521 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
523 info!("linker output: {:?}", out);
524 warn!("Linker does not support -no-pie command line option. Retrying without.");
525 for arg in cmd.take_args() {
526 if arg.to_string_lossy() != "-no-pie" {
534 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
535 // Fallback from '-static-pie' to '-static' in that case.
536 if sess.target.linker_is_gnu
537 && flavor != LinkerFlavor::Ld
538 && (out.contains("unrecognized command line option")
539 || out.contains("unknown argument"))
540 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
541 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
543 info!("linker output: {:?}", out);
545 "Linker does not support -static-pie command line option. Retrying with -static instead."
547 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
548 let self_contained = crt_objects_fallback(sess, crate_type);
549 let opts = &sess.target;
550 let pre_objects = if self_contained {
551 &opts.pre_link_objects_fallback
553 &opts.pre_link_objects
555 let post_objects = if self_contained {
556 &opts.post_link_objects_fallback
558 &opts.post_link_objects
560 let get_objects = |objects: &CrtObjects, kind| {
566 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
569 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
570 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
571 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
572 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
573 // Assume that we know insertion positions for the replacement arguments from replaced
574 // arguments, which is true for all supported targets.
575 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
576 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
577 for arg in cmd.take_args() {
578 if arg.to_string_lossy() == "-static-pie" {
579 // Replace the output kind.
581 } else if pre_objects_static_pie.contains(&arg) {
582 // Replace the pre-link objects (replace the first and remove the rest).
583 cmd.args(mem::take(&mut pre_objects_static));
584 } else if post_objects_static_pie.contains(&arg) {
585 // Replace the post-link objects (replace the first and remove the rest).
586 cmd.args(mem::take(&mut post_objects_static));
595 // Here's a terribly awful hack that really shouldn't be present in any
596 // compiler. Here an environment variable is supported to automatically
597 // retry the linker invocation if the linker looks like it segfaulted.
599 // Gee that seems odd, normally segfaults are things we want to know
600 // about! Unfortunately though in rust-lang/rust#38878 we're
601 // experiencing the linker segfaulting on Travis quite a bit which is
602 // causing quite a bit of pain to land PRs when they spuriously fail
603 // due to a segfault.
605 // The issue #38878 has some more debugging information on it as well,
606 // but this unfortunately looks like it's just a race condition in
607 // macOS's linker with some thread pool working in the background. It
608 // seems that no one currently knows a fix for this so in the meantime
609 // we're left with this...
610 if !retry_on_segfault || i > 3 {
613 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
614 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
615 if out.contains(msg_segv) || out.contains(msg_bus) {
617 "looks like the linker segfaulted when we tried to call it, \
618 automatically retrying again. cmd = {:?}, out = {}.",
624 if is_illegal_instruction(&output.status) {
626 "looks like the linker hit an illegal instruction when we \
627 tried to call it, automatically retrying again. cmd = {:?}, ]\
628 out = {}, status = {}.",
629 cmd, out, output.status,
635 fn is_illegal_instruction(status: &ExitStatus) -> bool {
636 use std::os::unix::prelude::*;
637 status.signal() == Some(libc::SIGILL)
641 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
648 fn escape_string(s: &[u8]) -> String {
649 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
650 let mut x = "Non-UTF-8 output: ".to_string();
651 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
655 if !prog.status.success() {
656 let mut output = prog.stderr.clone();
657 output.extend_from_slice(&prog.stdout);
658 sess.struct_err(&format!(
659 "linking with `{}` failed: {}",
660 linker_path.display(),
663 .note(&format!("{:?}", &cmd))
664 .note(&escape_string(&output))
667 // If MSVC's `link.exe` was expected but the return code
668 // is not a Microsoft LNK error then suggest a way to fix or
669 // install the Visual Studio build tools.
670 if let Some(code) = prog.status.code() {
671 if sess.target.is_like_msvc
672 && flavor == LinkerFlavor::Msvc
673 // Respect the command line override
674 && sess.opts.cg.linker.is_none()
675 // Match exactly "link.exe"
676 && linker_path.to_str() == Some("link.exe")
677 // All Microsoft `link.exe` linking error codes are
678 // four digit numbers in the range 1000 to 9999 inclusive
679 && (code < 1000 || code > 9999)
681 let is_vs_installed = windows_registry::find_vs_version().is_ok();
682 let has_linker = windows_registry::find_tool(
683 &sess.opts.target_triple.triple(),
688 sess.note_without_error("`link.exe` returned an unexpected error");
689 if is_vs_installed && has_linker {
690 // the linker is broken
691 sess.note_without_error(
692 "the Visual Studio build tools may need to be repaired \
693 using the Visual Studio installer",
695 sess.note_without_error(
696 "or a necessary component may be missing from the \
697 \"C++ build tools\" workload",
699 } else if is_vs_installed {
700 // the linker is not installed
701 sess.note_without_error(
702 "in the Visual Studio installer, ensure the \
703 \"C++ build tools\" workload is selected",
706 // visual studio is not installed
707 sess.note_without_error(
708 "you may need to install Visual Studio build tools with the \
709 \"C++ build tools\" workload",
715 sess.abort_if_errors();
717 info!("linker stderr:\n{}", escape_string(&prog.stderr));
718 info!("linker stdout:\n{}", escape_string(&prog.stdout));
721 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
723 let mut linker_error = {
724 if linker_not_found {
725 sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
727 sess.struct_err(&format!(
728 "could not exec the linker `{}`",
729 linker_path.display()
734 linker_error.note(&e.to_string());
736 if !linker_not_found {
737 linker_error.note(&format!("{:?}", &cmd));
742 if sess.target.is_like_msvc && linker_not_found {
743 sess.note_without_error(
744 "the msvc targets depend on the msvc linker \
745 but `link.exe` was not found",
747 sess.note_without_error(
748 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
749 was installed with the Visual C++ option",
752 sess.abort_if_errors();
756 // On macOS, debuggers need this utility to get run to do some munging of
757 // the symbols. Note, though, that if the object files are being preserved
758 // for their debug information there's no need for us to run dsymutil.
759 if sess.target.is_like_osx
760 && sess.opts.debuginfo != DebugInfo::None
761 && !preserve_objects_for_their_debuginfo(sess)
763 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
764 sess.fatal(&format!("failed to run dsymutil: {}", e))
769 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
770 // On macOS the runtimes are distributed as dylibs which should be linked to
771 // both executables and dynamic shared objects. Everywhere else the runtimes
772 // are currently distributed as static liraries which should be linked to
774 let needs_runtime = match crate_type {
775 CrateType::Executable => true,
776 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
777 CrateType::Rlib | CrateType::Staticlib => false,
784 let sanitizer = sess.opts.debugging_opts.sanitizer;
785 if sanitizer.contains(SanitizerSet::ADDRESS) {
786 link_sanitizer_runtime(sess, linker, "asan");
788 if sanitizer.contains(SanitizerSet::LEAK) {
789 link_sanitizer_runtime(sess, linker, "lsan");
791 if sanitizer.contains(SanitizerSet::MEMORY) {
792 link_sanitizer_runtime(sess, linker, "msan");
794 if sanitizer.contains(SanitizerSet::THREAD) {
795 link_sanitizer_runtime(sess, linker, "tsan");
799 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
800 let default_sysroot = filesearch::get_or_default_sysroot();
802 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
803 let channel = option_env!("CFG_RELEASE_CHANNEL")
804 .map(|channel| format!("-{}", channel))
805 .unwrap_or_default();
807 match sess.opts.target_triple.triple() {
808 "x86_64-apple-darwin" => {
809 // On Apple platforms, the sanitizer is always built as a dylib, and
810 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
811 // rpath to the library as well (the rpath should be absolute, see
812 // PR #41352 for details).
813 let libname = format!("rustc{}_rt.{}", channel, name);
814 let rpath = default_tlib.to_str().expect("non-utf8 component in path");
815 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
816 linker.link_dylib(Symbol::intern(&libname));
819 | "aarch64-unknown-linux-gnu"
821 | "x86_64-unknown-freebsd"
822 | "x86_64-unknown-linux-gnu" => {
823 let filename = format!("librustc{}_rt.{}.a", channel, name);
824 let path = default_tlib.join(&filename);
825 linker.link_whole_rlib(&path);
831 /// Returns a boolean indicating whether the specified crate should be ignored
834 /// Crates ignored during LTO are not lumped together in the "massive object
835 /// file" that we create and are linked in their normal rlib states. See
836 /// comments below for what crates do not participate in LTO.
838 /// It's unusual for a crate to not participate in LTO. Typically only
839 /// compiler-specific and unstable crates have a reason to not participate in
841 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
842 // If our target enables builtin function lowering in LLVM then the
843 // crates providing these functions don't participate in LTO (e.g.
844 // no_builtins or compiler builtins crates).
845 !sess.target.no_builtins
846 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
849 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
852 linker: Option<PathBuf>,
853 flavor: Option<LinkerFlavor>,
854 ) -> Option<(PathBuf, LinkerFlavor)> {
855 match (linker, flavor) {
856 (Some(linker), Some(flavor)) => Some((linker, flavor)),
857 // only the linker flavor is known; use the default linker for the selected flavor
858 (None, Some(flavor)) => Some((
859 PathBuf::from(match flavor {
860 LinkerFlavor::Em => {
867 LinkerFlavor::Gcc => {
868 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
869 // On historical Solaris systems, "cc" may have
870 // been Sun Studio, which is not flag-compatible
871 // with "gcc". This history casts a long shadow,
872 // and many modern illumos distributions today
873 // ship GCC as "gcc" without also making it
874 // available as "cc".
880 LinkerFlavor::Ld => "ld",
881 LinkerFlavor::Msvc => "link.exe",
882 LinkerFlavor::Lld(_) => "lld",
883 LinkerFlavor::PtxLinker => "rust-ptx-linker",
887 (Some(linker), None) => {
888 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
889 sess.fatal("couldn't extract file stem from specified linker")
892 let flavor = if stem == "emcc" {
894 } else if stem == "gcc"
895 || stem.ends_with("-gcc")
897 || stem.ends_with("-clang")
900 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
902 } else if stem == "link" || stem == "lld-link" {
904 } else if stem == "lld" || stem == "rust-lld" {
905 LinkerFlavor::Lld(sess.target.lld_flavor)
907 // fall back to the value in the target spec
908 sess.target.linker_flavor
911 Some((linker, flavor))
913 (None, None) => None,
917 // linker and linker flavor specified via command line have precedence over what the target
918 // specification specifies
919 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
923 if let Some(ret) = infer_from(
925 sess.target.linker.clone().map(PathBuf::from),
926 Some(sess.target.linker_flavor),
931 bug!("Not enough information provided to determine how to invoke the linker");
934 /// Returns a boolean indicating whether we should preserve the object files on
935 /// the filesystem for their debug information. This is often useful with
936 /// split-dwarf like schemes.
937 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
938 // If the objects don't have debuginfo there's nothing to preserve.
939 if sess.opts.debuginfo == config::DebugInfo::None {
943 // If we're only producing artifacts that are archives, no need to preserve
944 // the objects as they're losslessly contained inside the archives.
946 sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
951 // If we're on OSX then the equivalent of split dwarf is turned on by
952 // default. The final executable won't actually have any debug information
953 // except it'll have pointers to elsewhere. Historically we've always run
954 // `dsymutil` to "link all the dwarf together" but this is actually sort of
955 // a bummer for incremental compilation! (the whole point of split dwarf is
956 // that you don't do this sort of dwarf link).
958 // Basically as a result this just means that if we're on OSX and we're
959 // *not* running dsymutil then the object files are the only source of truth
960 // for debug information, so we must preserve them.
961 if sess.target.is_like_osx {
962 return !sess.opts.debugging_opts.run_dsymutil;
968 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
969 sess.target_filesearch(PathKind::Native).search_path_dirs()
977 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
978 let lib_args: Vec<_> = all_native_libs
980 .filter(|l| relevant_lib(sess, l))
982 let name = lib.name?;
984 NativeLibKind::StaticNoBundle
985 | NativeLibKind::Dylib
986 | NativeLibKind::Unspecified => {
987 if sess.target.is_like_msvc {
988 Some(format!("{}.lib", name))
990 Some(format!("-l{}", name))
993 NativeLibKind::Framework => {
994 // ld-only syntax, since there are no frameworks in MSVC
995 Some(format!("-framework {}", name))
997 // These are included, no need to print them
998 NativeLibKind::StaticBundle | NativeLibKind::RawDylib => None,
1002 if !lib_args.is_empty() {
1003 sess.note_without_error(
1004 "Link against the following native artifacts when linking \
1005 against this static library. The order and any duplication \
1006 can be significant on some platforms.",
1008 // Prefix for greppability
1009 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1013 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1014 let fs = sess.target_filesearch(PathKind::Native);
1015 let file_path = fs.get_lib_path().join(name);
1016 if file_path.exists() {
1019 // Special directory with objects used only in self-contained linkage mode
1021 let file_path = fs.get_self_contained_lib_path().join(name);
1022 if file_path.exists() {
1026 for search_path in fs.search_paths() {
1027 let file_path = search_path.dir.join(name);
1028 if file_path.exists() {
1038 out_filename: &Path,
1040 ) -> io::Result<Output> {
1041 // When attempting to spawn the linker we run a risk of blowing out the
1042 // size limits for spawning a new process with respect to the arguments
1043 // we pass on the command line.
1045 // Here we attempt to handle errors from the OS saying "your list of
1046 // arguments is too big" by reinvoking the linker again with an `@`-file
1047 // that contains all the arguments. The theory is that this is then
1048 // accepted on all linkers and the linker will read all its options out of
1049 // there instead of looking at the command line.
1050 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1051 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1053 let output = child.wait_with_output();
1054 flush_linked_file(&output, out_filename)?;
1057 Err(ref e) if command_line_too_big(e) => {
1058 info!("command line to linker was too big: {}", e);
1060 Err(e) => return Err(e),
1064 info!("falling back to passing arguments to linker via an @-file");
1065 let mut cmd2 = cmd.clone();
1066 let mut args = String::new();
1067 for arg in cmd2.take_args() {
1069 &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1074 let file = tmpdir.join("linker-arguments");
1075 let bytes = if sess.target.is_like_msvc {
1076 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1077 // start the stream with a UTF-16 BOM
1078 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1079 // encode in little endian
1081 out.push((c >> 8) as u8);
1087 fs::write(&file, &bytes)?;
1088 cmd2.arg(format!("@{}", file.display()));
1089 info!("invoking linker {:?}", cmd2);
1090 let output = cmd2.output();
1091 flush_linked_file(&output, out_filename)?;
1095 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1100 fn flush_linked_file(
1101 command_output: &io::Result<Output>,
1102 out_filename: &Path,
1103 ) -> io::Result<()> {
1104 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1105 // even long after process exit, causing nasty, non-reproducible output bugs.
1107 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1109 // А full writeup of the original Chrome bug can be found at
1110 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1112 if let &Ok(ref out) = command_output {
1113 if out.status.success() {
1114 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1124 fn command_line_too_big(err: &io::Error) -> bool {
1125 err.raw_os_error() == Some(::libc::E2BIG)
1129 fn command_line_too_big(err: &io::Error) -> bool {
1130 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1131 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1139 impl<'a> fmt::Display for Escape<'a> {
1140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1141 if self.is_like_msvc {
1142 // This is "documented" at
1143 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1145 // Unfortunately there's not a great specification of the
1146 // syntax I could find online (at least) but some local
1147 // testing showed that this seemed sufficient-ish to catch
1148 // at least a few edge cases.
1150 for c in self.arg.chars() {
1152 '"' => write!(f, "\\{}", c)?,
1153 c => write!(f, "{}", c)?,
1158 // This is documented at https://linux.die.net/man/1/ld, namely:
1160 // > Options in file are separated by whitespace. A whitespace
1161 // > character may be included in an option by surrounding the
1162 // > entire option in either single or double quotes. Any
1163 // > character (including a backslash) may be included by
1164 // > prefixing the character to be included with a backslash.
1166 // We put an argument on each line, so all we need to do is
1167 // ensure the line is interpreted as one whole argument.
1168 for c in self.arg.chars() {
1170 '\\' | ' ' => write!(f, "\\{}", c)?,
1171 c => write!(f, "{}", c)?,
1180 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1181 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1182 (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1183 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1184 (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1185 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1186 (_, true, _) => LinkOutputKind::StaticDylib,
1187 (_, false, _) => LinkOutputKind::DynamicDylib,
1190 // Adjust the output kind to target capabilities.
1191 let opts = &sess.target;
1192 let pic_exe_supported = opts.position_independent_executables;
1193 let static_pic_exe_supported = opts.static_position_independent_executables;
1194 let static_dylib_supported = opts.crt_static_allows_dylibs;
1196 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1197 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1198 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1203 // Returns true if linker is located within sysroot
1204 fn detect_self_contained_mingw(sess: &Session) -> bool {
1205 let (linker, _) = linker_and_flavor(&sess);
1206 // Assume `-C linker=rust-lld` as self-contained mode
1207 if linker == Path::new("rust-lld") {
1210 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1211 linker.with_extension("exe")
1215 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1216 let full_path = dir.join(&linker_with_extension);
1217 // If linker comes from sysroot assume self-contained mode
1218 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1225 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1226 /// We only provide such support for a very limited number of targets.
1227 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1228 if let Some(self_contained) = sess.opts.cg.link_self_contained {
1229 return self_contained;
1232 match sess.target.crt_objects_fallback {
1233 // FIXME: Find a better heuristic for "native musl toolchain is available",
1234 // based on host and linker path, for example.
1235 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1236 Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1237 Some(CrtObjectsFallback::Mingw) => {
1238 sess.host == sess.target
1239 && sess.target.vendor != "uwp"
1240 && detect_self_contained_mingw(&sess)
1242 // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1243 Some(CrtObjectsFallback::Wasm) => true,
1248 /// Add pre-link object files defined by the target spec.
1249 fn add_pre_link_objects(
1250 cmd: &mut dyn Linker,
1252 link_output_kind: LinkOutputKind,
1253 self_contained: bool,
1255 let opts = &sess.target;
1257 if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1258 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1259 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1263 /// Add post-link object files defined by the target spec.
1264 fn add_post_link_objects(
1265 cmd: &mut dyn Linker,
1267 link_output_kind: LinkOutputKind,
1268 self_contained: bool,
1270 let opts = &sess.target;
1272 if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1273 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1274 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1278 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1279 /// FIXME: Determine where exactly these args need to be inserted.
1280 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1281 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1284 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1287 /// Add a link script embedded in the target, if applicable.
1288 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1289 match (crate_type, &sess.target.link_script) {
1290 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1291 if !sess.target.linker_is_gnu {
1292 sess.fatal("can only use link script when linking with GNU-like linker");
1295 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1297 let path = tmpdir.join(file_name);
1298 if let Err(e) = fs::write(&path, script) {
1299 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1302 cmd.arg("--script");
1309 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1310 /// FIXME: Determine where exactly these args need to be inserted.
1311 fn add_user_defined_link_args(
1312 cmd: &mut dyn Linker,
1314 codegen_results: &CodegenResults,
1316 cmd.args(&sess.opts.cg.link_args);
1317 cmd.args(&*codegen_results.crate_info.link_args);
1320 /// Add arbitrary "late link" args defined by the target spec.
1321 /// FIXME: Determine where exactly these args need to be inserted.
1322 fn add_late_link_args(
1323 cmd: &mut dyn Linker,
1325 flavor: LinkerFlavor,
1326 crate_type: CrateType,
1327 codegen_results: &CodegenResults,
1329 let any_dynamic_crate = crate_type == CrateType::Dylib
1330 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1331 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1333 if any_dynamic_crate {
1334 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1338 if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1342 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1347 /// Add arbitrary "post-link" args defined by the target spec.
1348 /// FIXME: Determine where exactly these args need to be inserted.
1349 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1350 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1355 /// Add object files containing code from the current crate.
1356 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1357 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1358 cmd.add_object(obj);
1362 /// Add object files for allocator code linked once for the whole crate tree.
1363 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1364 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1365 cmd.add_object(obj);
1369 /// Add object files containing metadata for the current crate.
1370 fn add_local_crate_metadata_objects(
1371 cmd: &mut dyn Linker,
1372 crate_type: CrateType,
1373 codegen_results: &CodegenResults,
1375 // When linking a dynamic library, we put the metadata into a section of the
1376 // executable. This metadata is in a separate object file from the main
1377 // object file, so we link that in here.
1378 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1379 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1381 cmd.add_object(obj);
1386 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1387 /// all its dependency crates.
1388 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1389 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1390 cmd: &mut dyn Linker,
1392 crate_type: CrateType,
1393 codegen_results: &CodegenResults,
1396 // Take careful note of the ordering of the arguments we pass to the linker
1397 // here. Linkers will assume that things on the left depend on things to the
1398 // right. Things on the right cannot depend on things on the left. This is
1399 // all formally implemented in terms of resolving symbols (libs on the right
1400 // resolve unknown symbols of libs on the left, but not vice versa).
1402 // For this reason, we have organized the arguments we pass to the linker as
1405 // 1. The local object that LLVM just generated
1406 // 2. Local native libraries
1407 // 3. Upstream rust libraries
1408 // 4. Upstream native libraries
1410 // The rationale behind this ordering is that those items lower down in the
1411 // list can't depend on items higher up in the list. For example nothing can
1412 // depend on what we just generated (e.g., that'd be a circular dependency).
1413 // Upstream rust libraries are not allowed to depend on our local native
1414 // libraries as that would violate the structure of the DAG, in that
1415 // scenario they are required to link to them as well in a shared fashion.
1417 // Note that upstream rust libraries may contain native dependencies as
1418 // well, but they also can't depend on what we just started to add to the
1419 // link line. And finally upstream native libraries can't depend on anything
1420 // in this DAG so far because they're only dylibs and dylibs can only depend
1421 // on other dylibs (e.g., other native deps).
1423 // If -Zlink-native-libraries=false is set, then the assumption is that an
1424 // external build system already has the native dependencies defined, and it
1425 // will provide them to the linker itself.
1426 if sess.opts.debugging_opts.link_native_libraries {
1427 add_local_native_libraries(cmd, sess, codegen_results);
1429 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1430 if sess.opts.debugging_opts.link_native_libraries {
1431 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1435 /// Add sysroot and other globally set directories to the directory search list.
1436 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1437 // The default library location, we need this to find the runtime.
1438 // The location of crates will be determined as needed.
1439 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1440 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1442 // Special directory with libraries used only in self-contained linkage mode
1444 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1445 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1449 /// Add options making relocation sections in the produced ELF files read-only
1450 /// and suppressing lazy binding.
1451 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1452 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.relro_level) {
1453 RelroLevel::Full => cmd.full_relro(),
1454 RelroLevel::Partial => cmd.partial_relro(),
1455 RelroLevel::Off => cmd.no_relro(),
1456 RelroLevel::None => {}
1460 /// Add library search paths used at runtime by dynamic linkers.
1462 cmd: &mut dyn Linker,
1464 codegen_results: &CodegenResults,
1465 out_filename: &Path,
1467 // FIXME (#2397): At some point we want to rpath our guesses as to
1468 // where extern libraries might live, based on the
1469 // addl_lib_search_paths
1470 if sess.opts.cg.rpath {
1471 let target_triple = sess.opts.target_triple.triple();
1472 let mut get_install_prefix_lib_path = || {
1473 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1474 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1475 let mut path = PathBuf::from(install_prefix);
1480 let mut rpath_config = RPathConfig {
1481 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1482 out_filename: out_filename.to_path_buf(),
1483 has_rpath: sess.target.has_rpath,
1484 is_like_osx: sess.target.is_like_osx,
1485 linker_is_gnu: sess.target.linker_is_gnu,
1486 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1488 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1492 /// Produce the linker command line containing linker path and arguments.
1493 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1494 /// by the user without creating a custom target specification.
1495 /// `OBJECT-FILES` specify whether the arguments can add object files.
1496 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1497 /// or by the target spec can be inserted here.
1498 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1499 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1501 flavor: LinkerFlavor,
1503 crate_type: CrateType,
1505 out_filename: &Path,
1506 codegen_results: &CodegenResults,
1509 let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1510 let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1511 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1512 // to the linker args construction.
1513 assert!(base_cmd.get_args().is_empty() || sess.target.vendor == "uwp");
1514 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1515 let link_output_kind = link_output_kind(sess, crate_type);
1517 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1518 add_pre_link_args(cmd, sess, flavor);
1520 // NO-OPT-OUT, OBJECT-FILES-NO
1521 add_apple_sdk(cmd, sess, flavor);
1524 add_link_script(cmd, sess, tmpdir, crate_type);
1526 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1527 if sess.target.is_like_fuchsia && crate_type == CrateType::Executable {
1528 let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1533 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1536 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1537 if sess.target.eh_frame_header {
1538 cmd.add_eh_frame_header();
1541 // NO-OPT-OUT, OBJECT-FILES-NO
1542 if crt_objects_fallback {
1543 cmd.no_crt_objects();
1546 // NO-OPT-OUT, OBJECT-FILES-YES
1547 add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1549 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1550 if sess.target.is_like_emscripten {
1552 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1553 "DISABLE_EXCEPTION_CATCHING=1"
1555 "DISABLE_EXCEPTION_CATCHING=0"
1559 // OBJECT-FILES-YES, AUDIT-ORDER
1560 link_sanitizers(sess, crate_type, cmd);
1562 // OBJECT-FILES-NO, AUDIT-ORDER
1563 // Linker plugins should be specified early in the list of arguments
1564 // FIXME: How "early" exactly?
1565 cmd.linker_plugin_lto();
1567 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1568 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1569 add_library_search_dirs(cmd, sess, crt_objects_fallback);
1572 add_local_crate_regular_objects(cmd, codegen_results);
1574 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1575 cmd.output_filename(out_filename);
1577 // OBJECT-FILES-NO, AUDIT-ORDER
1578 if crate_type == CrateType::Executable && sess.target.is_like_windows {
1579 if let Some(ref s) = codegen_results.windows_subsystem {
1584 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1585 // If we're building something like a dynamic library then some platforms
1586 // need to make sure that all symbols are exported correctly from the
1588 cmd.export_symbols(tmpdir, crate_type);
1591 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1594 add_local_crate_allocator_objects(cmd, codegen_results);
1596 // OBJECT-FILES-NO, AUDIT-ORDER
1597 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1598 // Try to strip as much out of the generated object by removing unused
1599 // sections if possible. See more comments in linker.rs
1600 if !sess.link_dead_code() {
1601 let keep_metadata = crate_type == CrateType::Dylib;
1602 cmd.gc_sections(keep_metadata);
1605 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1606 cmd.set_output_kind(link_output_kind, out_filename);
1608 // OBJECT-FILES-NO, AUDIT-ORDER
1609 add_relro_args(cmd, sess);
1611 // OBJECT-FILES-NO, AUDIT-ORDER
1612 // Pass optimization flags down to the linker.
1615 // OBJECT-FILES-NO, AUDIT-ORDER
1616 // Pass debuginfo and strip flags down to the linker.
1617 cmd.debuginfo(sess.opts.debugging_opts.strip);
1619 // OBJECT-FILES-NO, AUDIT-ORDER
1620 // We want to prevent the compiler from accidentally leaking in any system libraries,
1621 // so by default we tell linkers not to link to any default libraries.
1622 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
1623 cmd.no_default_libraries();
1627 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1635 // OBJECT-FILES-NO, AUDIT-ORDER
1636 if sess.opts.cg.profile_generate.enabled() || sess.opts.debugging_opts.instrument_coverage {
1640 // OBJECT-FILES-NO, AUDIT-ORDER
1641 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1642 cmd.control_flow_guard();
1645 // OBJECT-FILES-NO, AUDIT-ORDER
1646 add_rpath_args(cmd, sess, codegen_results, out_filename);
1648 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1649 add_user_defined_link_args(cmd, sess, codegen_results);
1651 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1654 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1655 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1657 // NO-OPT-OUT, OBJECT-FILES-YES
1658 add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1660 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1661 add_post_link_args(cmd, sess, flavor);
1666 // # Native library linking
1668 // User-supplied library search paths (-L on the command line). These are
1669 // the same paths used to find Rust crates, so some of them may have been
1670 // added already by the previous crate linking code. This only allows them
1671 // to be found at compile time so it is still entirely up to outside
1672 // forces to make sure that library can be found at runtime.
1674 // Also note that the native libraries linked here are only the ones located
1675 // in the current crate. Upstream crates with native library dependencies
1676 // may have their native library pulled in above.
1677 fn add_local_native_libraries(
1678 cmd: &mut dyn Linker,
1680 codegen_results: &CodegenResults,
1682 let filesearch = sess.target_filesearch(PathKind::All);
1683 for search_path in filesearch.search_paths() {
1684 match search_path.kind {
1685 PathKind::Framework => {
1686 cmd.framework_path(&search_path.dir);
1689 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1695 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1697 let search_path = archive_search_paths(sess);
1698 for lib in relevant_libs {
1699 let name = match lib.name {
1704 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1705 NativeLibKind::Framework => cmd.link_framework(name),
1706 NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1707 NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1708 NativeLibKind::RawDylib => {
1709 // FIXME(#58713): Proper handling for raw dylibs.
1710 bug!("raw_dylib feature not yet implemented");
1716 // # Rust Crate linking
1718 // Rust crates are not considered at all when creating an rlib output. All
1719 // dependencies will be linked when producing the final output (instead of
1720 // the intermediate rlib version)
1721 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1722 cmd: &mut dyn Linker,
1724 codegen_results: &CodegenResults,
1725 crate_type: CrateType,
1728 // All of the heavy lifting has previously been accomplished by the
1729 // dependency_format module of the compiler. This is just crawling the
1730 // output of that module, adding crates as necessary.
1732 // Linking to a rlib involves just passing it to the linker (the linker
1733 // will slurp up the object files inside), and linking to a dynamic library
1734 // involves just passing the right -l flag.
1736 let (_, data) = codegen_results
1740 .find(|(ty, _)| *ty == crate_type)
1741 .expect("failed to find crate type in dependency format list");
1743 // Invoke get_used_crates to ensure that we get a topological sorting of
1745 let deps = &codegen_results.crate_info.used_crates_dynamic;
1747 // There's a few internal crates in the standard library (aka libcore and
1748 // libstd) which actually have a circular dependence upon one another. This
1749 // currently arises through "weak lang items" where libcore requires things
1750 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1751 // circular dependence to work correctly in all situations we'll need to be
1752 // sure to correctly apply the `--start-group` and `--end-group` options to
1753 // GNU linkers, otherwise if we don't use any other symbol from the standard
1754 // library it'll get discarded and the whole application won't link.
1756 // In this loop we're calculating the `group_end`, after which crate to
1757 // pass `--end-group` and `group_start`, before which crate to pass
1758 // `--start-group`. We currently do this by passing `--end-group` after
1759 // the first crate (when iterating backwards) that requires a lang item
1760 // defined somewhere else. Once that's set then when we've defined all the
1761 // necessary lang items we'll pass `--start-group`.
1763 // Note that this isn't amazing logic for now but it should do the trick
1764 // for the current implementation of the standard library.
1765 let mut group_end = None;
1766 let mut group_start = None;
1767 // Crates available for linking thus far.
1768 let mut available = FxHashSet::default();
1769 // Crates required to satisfy dependencies discovered so far.
1770 let mut required = FxHashSet::default();
1772 let info = &codegen_results.crate_info;
1773 for &(cnum, _) in deps.iter().rev() {
1774 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1775 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1776 required.extend(missing_crates);
1779 required.insert(Some(cnum));
1780 available.insert(Some(cnum));
1782 if required.len() > available.len() && group_end.is_none() {
1783 group_end = Some(cnum);
1785 if required.len() == available.len() && group_end.is_some() {
1786 group_start = Some(cnum);
1791 // If we didn't end up filling in all lang items from upstream crates then
1792 // we'll be filling it in with our crate. This probably means we're the
1793 // standard library itself, so skip this for now.
1794 if group_end.is_some() && group_start.is_none() {
1798 let mut compiler_builtins = None;
1800 for &(cnum, _) in deps.iter() {
1801 if group_start == Some(cnum) {
1805 // We may not pass all crates through to the linker. Some crates may
1806 // appear statically in an existing dylib, meaning we'll pick up all the
1807 // symbols from the dylib.
1808 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1809 match data[cnum.as_usize() - 1] {
1810 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1811 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1813 // compiler-builtins are always placed last to ensure that they're
1814 // linked correctly.
1815 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1816 assert!(compiler_builtins.is_none());
1817 compiler_builtins = Some(cnum);
1819 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1820 Linkage::Static => {
1821 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1823 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1826 if group_end == Some(cnum) {
1831 // compiler-builtins are always placed last to ensure that they're
1832 // linked correctly.
1833 // We must always link the `compiler_builtins` crate statically. Even if it
1834 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1836 if let Some(cnum) = compiler_builtins {
1837 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1840 // Converts a library file-stem into a cc -l argument
1841 fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
1842 if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
1845 // Adds the static "rlib" versions of all crates to the command line.
1846 // There's a bit of magic which happens here specifically related to LTO and
1847 // dynamic libraries. Specifically:
1849 // * For LTO, we remove upstream object files.
1850 // * For dylibs we remove metadata and bytecode from upstream rlibs
1852 // When performing LTO, almost(*) all of the bytecode from the upstream
1853 // libraries has already been included in our object file output. As a
1854 // result we need to remove the object files in the upstream libraries so
1855 // the linker doesn't try to include them twice (or whine about duplicate
1856 // symbols). We must continue to include the rest of the rlib, however, as
1857 // it may contain static native libraries which must be linked in.
1859 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1860 // their bytecode wasn't included. The object files in those libraries must
1861 // still be passed to the linker.
1863 // When making a dynamic library, linkers by default don't include any
1864 // object files in an archive if they're not necessary to resolve the link.
1865 // We basically want to convert the archive (rlib) to a dylib, though, so we
1866 // *do* want everything included in the output, regardless of whether the
1867 // linker thinks it's needed or not. As a result we must use the
1868 // --whole-archive option (or the platform equivalent). When using this
1869 // option the linker will fail if there are non-objects in the archive (such
1870 // as our own metadata and/or bytecode). All in all, for rlibs to be
1871 // entirely included in dylibs, we need to remove all non-object files.
1873 // Note, however, that if we're not doing LTO or we're not producing a dylib
1874 // (aka we're making an executable), we can just pass the rlib blindly to
1875 // the linker (fast) because it's fine if it's not actually included as
1876 // we're at the end of the dependency chain.
1877 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1878 cmd: &mut dyn Linker,
1880 codegen_results: &CodegenResults,
1882 crate_type: CrateType,
1885 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1886 let cratepath = &src.rlib.as_ref().unwrap().0;
1888 // See the comment above in `link_staticlib` and `link_rlib` for why if
1889 // there's a static library that's not relevant we skip all object
1891 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1892 let skip_native = native_libs
1894 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1896 if (!are_upstream_rust_objects_already_included(sess)
1897 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1898 && crate_type != CrateType::Dylib
1901 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1905 let dst = tmpdir.join(cratepath.file_name().unwrap());
1906 let name = cratepath.file_name().unwrap().to_str().unwrap();
1907 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1909 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1910 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1911 archive.update_symbols();
1913 let mut any_objects = false;
1914 for f in archive.src_files() {
1915 if f == METADATA_FILENAME {
1916 archive.remove_file(&f);
1920 let canonical = f.replace("-", "_");
1921 let canonical_name = name.replace("-", "_");
1923 let is_rust_object =
1924 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
1926 // If we've been requested to skip all native object files
1927 // (those not generated by the rust compiler) then we can skip
1928 // this file. See above for why we may want to do this.
1929 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1931 // If we're performing LTO and this is a rust-generated object
1932 // file, then we don't need the object file as it's part of the
1933 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1934 // though, so we let that object file slide.
1935 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
1937 && (sess.target.no_builtins
1938 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1940 if skip_because_cfg_say_so || skip_because_lto {
1941 archive.remove_file(&f);
1952 // If we're creating a dylib, then we need to include the
1953 // whole of each object in our archive into that artifact. This is
1954 // because a `dylib` can be reused as an intermediate artifact.
1956 // Note, though, that we don't want to include the whole of a
1957 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1958 // repeatedly linked anyway.
1959 if crate_type == CrateType::Dylib
1960 && codegen_results.crate_info.compiler_builtins != Some(cnum)
1962 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1964 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1969 // Same thing as above, but for dynamic crates instead of static crates.
1970 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1971 // Just need to tell the linker about where the library lives and
1973 let parent = cratepath.parent();
1974 if let Some(dir) = parent {
1975 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1977 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1978 cmd.link_rust_dylib(
1979 Symbol::intern(&unlib(&sess.target, filestem)),
1980 parent.unwrap_or(Path::new("")),
1985 // Link in all of our upstream crates' native dependencies. Remember that
1986 // all of these upstream native dependencies are all non-static
1987 // dependencies. We've got two cases then:
1989 // 1. The upstream crate is an rlib. In this case we *must* link in the
1990 // native dependency because the rlib is just an archive.
1992 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1993 // have the dependency present on the system somewhere. Thus, we don't
1994 // gain a whole lot from not linking in the dynamic dependency to this
1997 // The use case for this is a little subtle. In theory the native
1998 // dependencies of a crate are purely an implementation detail of the crate
1999 // itself, but the problem arises with generic and inlined functions. If a
2000 // generic function calls a native function, then the generic function must
2001 // be instantiated in the target crate, meaning that the native symbol must
2002 // also be resolved in the target crate.
2003 fn add_upstream_native_libraries(
2004 cmd: &mut dyn Linker,
2006 codegen_results: &CodegenResults,
2007 crate_type: CrateType,
2009 // Be sure to use a topological sorting of crates because there may be
2010 // interdependencies between native libraries. When passing -nodefaultlibs,
2011 // for example, almost all native libraries depend on libc, so we have to
2012 // make sure that's all the way at the right (liblibc is near the base of
2013 // the dependency chain).
2015 // This passes RequireStatic, but the actual requirement doesn't matter,
2016 // we're just getting an ordering of crate numbers, we're not worried about
2018 let (_, data) = codegen_results
2022 .find(|(ty, _)| *ty == crate_type)
2023 .expect("failed to find crate type in dependency format list");
2025 let crates = &codegen_results.crate_info.used_crates_static;
2026 for &(cnum, _) in crates {
2027 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2028 let name = match lib.name {
2032 if !relevant_lib(sess, &lib) {
2036 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2037 NativeLibKind::Framework => cmd.link_framework(name),
2038 NativeLibKind::StaticNoBundle => {
2039 // Link "static-nobundle" native libs only if the crate they originate from
2040 // is being linked statically to the current crate. If it's linked dynamically
2041 // or is an rlib already included via some other dylib crate, the symbols from
2042 // native libs will have already been included in that dylib.
2043 if data[cnum.as_usize() - 1] == Linkage::Static {
2044 cmd.link_staticlib(name)
2047 // ignore statically included native libraries here as we've
2048 // already included them when we included the rust library
2050 NativeLibKind::StaticBundle => {}
2051 NativeLibKind::RawDylib => {
2052 // FIXME(#58713): Proper handling for raw dylibs.
2053 bug!("raw_dylib feature not yet implemented");
2060 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2062 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2067 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2069 config::Lto::Fat => true,
2070 config::Lto::Thin => {
2071 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2072 // any upstream object files have not been copied yet.
2073 !sess.opts.cg.linker_plugin_lto.enabled()
2075 config::Lto::No | config::Lto::ThinLocal => false,
2079 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2080 let arch = &sess.target.arch;
2081 let os = &sess.target.os;
2082 let llvm_target = &sess.target.llvm_target;
2083 if sess.target.vendor != "apple"
2084 || !matches!(os.as_str(), "ios" | "tvos")
2085 || flavor != LinkerFlavor::Gcc
2089 let sdk_name = match (arch.as_str(), os.as_str()) {
2090 ("aarch64", "tvos") => "appletvos",
2091 ("x86_64", "tvos") => "appletvsimulator",
2092 ("arm", "ios") => "iphoneos",
2093 ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2094 ("aarch64", "ios") => "iphoneos",
2095 ("x86", "ios") => "iphonesimulator",
2096 ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2097 ("x86_64", "ios") => "iphonesimulator",
2099 sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2103 let sdk_root = match get_apple_sdk_root(sdk_name) {
2110 let arch_name = llvm_target.split('-').next().expect("LLVM target must have a hyphen");
2111 cmd.args(&["-arch", arch_name, "-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2114 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2115 // Following what clang does
2116 // (https://github.com/llvm/llvm-project/blob/
2117 // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2118 // to allow the SDK path to be set. (For clang, xcrun sets
2119 // SDKROOT; for rustc, the user or build system can set it, or we
2120 // can fall back to checking for xcrun on PATH.)
2121 if let Ok(sdkroot) = env::var("SDKROOT") {
2122 let p = Path::new(&sdkroot);
2124 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2126 if sdkroot.contains("TVSimulator.platform")
2127 || sdkroot.contains("MacOSX.platform") => {}
2129 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2131 if sdkroot.contains("iPhoneSimulator.platform")
2132 || sdkroot.contains("MacOSX.platform") => {}
2134 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2137 if sdkroot.contains("iPhoneOS.platform")
2138 || sdkroot.contains("iPhoneSimulator.platform") => {}
2139 // Ignore `SDKROOT` if it's not a valid path.
2140 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2141 _ => return Ok(sdkroot),
2145 Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2147 if output.status.success() {
2148 Ok(String::from_utf8(output.stdout).unwrap())
2150 let error = String::from_utf8(output.stderr);
2151 let error = format!("process exit with error: {}", error.unwrap());
2152 Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2158 Ok(output) => Ok(output.trim().to_string()),
2159 Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),