1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_fs_util::fix_windows_verbatim_for_gcc;
3 use rustc_hir::def_id::CrateNum;
4 use rustc_middle::middle::cstore::{EncodedMetadata, LibSource, NativeLib};
5 use rustc_middle::middle::dependency_format::Linkage;
6 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo};
7 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SanitizerSet};
8 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
9 use rustc_session::search_paths::PathKind;
10 use rustc_session::utils::NativeLibKind;
11 /// For all the linkers we support, and information they might
12 /// need out of the shared crate context before we get rid of it.
13 use rustc_session::{filesearch, Session};
14 use rustc_span::symbol::Symbol;
15 use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
16 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
17 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel};
19 use super::archive::ArchiveBuilder;
20 use super::command::Command;
21 use super::linker::{self, Linker};
22 use super::rpath::{self, RPathConfig};
23 use crate::{looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME};
25 use cc::windows_registry;
26 use tempfile::{Builder as TempFileBuilder, TempDir};
28 use std::ffi::OsString;
29 use std::path::{Path, PathBuf};
30 use std::process::{ExitStatus, Output, Stdio};
31 use std::{ascii, char, env, fmt, fs, io, mem, str};
33 pub fn remove(sess: &Session, path: &Path) {
34 if let Err(e) = fs::remove_file(path) {
35 sess.err(&format!("failed to remove {}: {}", path.display(), e));
39 /// Performs the linkage portion of the compilation phase. This will generate all
40 /// of the requested outputs for this compilation session.
41 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
43 codegen_results: &CodegenResults,
44 outputs: &OutputFilenames,
48 let _timer = sess.timer("link_binary");
49 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
50 for &crate_type in sess.crate_types().iter() {
51 // Ignore executable crates if we have -Z no-codegen, as they will error.
52 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
54 && crate_type == CrateType::Executable
59 if invalid_output_for_target(sess, crate_type) {
61 "invalid output type `{:?}` for target os `{}`",
63 sess.opts.target_triple
67 sess.time("link_binary_check_files_are_writeable", || {
68 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
69 check_file_is_writeable(obj, sess);
73 let tmpdir = TempFileBuilder::new()
76 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
78 if outputs.outputs.should_codegen() {
79 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
82 let _timer = sess.timer("link_rlib");
92 CrateType::Staticlib => {
93 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
106 if sess.opts.json_artifact_notifications {
107 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
111 if sess.opts.cg.save_temps {
112 let _ = tmpdir.into_path();
116 // Remove the temporary object file and metadata if we aren't saving temps
117 sess.time("link_binary_remove_temps", || {
118 if !sess.opts.cg.save_temps {
119 if sess.opts.output_types.should_codegen()
120 && !preserve_objects_for_their_debuginfo(sess)
122 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
126 if let Some(ref metadata_module) = codegen_results.metadata_module {
127 if let Some(ref obj) = metadata_module.object {
131 if let Some(ref allocator_module) = codegen_results.allocator_module {
132 if let Some(ref obj) = allocator_module.object {
140 // The third parameter is for env vars, used on windows to set up the
141 // path for MSVC to find its DLLs, and gcc to find its bundled
146 flavor: LinkerFlavor,
147 self_contained: bool,
149 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
151 // If our linker looks like a batch script on Windows then to execute this
152 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
153 // emscripten where the linker is `emcc.bat` and needs to be spawned as
154 // `cmd /c emcc.bat ...`.
156 // This worked historically but is needed manually since #42436 (regression
157 // was tagged as #42791) and some more info can be found on #44443 for
158 // emscripten itself.
159 let mut cmd = match linker.to_str() {
160 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
162 LinkerFlavor::Lld(f) => Command::lld(linker, f),
164 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
166 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
168 _ => Command::new(linker),
172 // UWP apps have API restrictions enforced during Store submissions.
173 // To comply with the Windows App Certification Kit,
174 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
175 let t = &sess.target.target;
176 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
177 && t.target_vendor == "uwp"
179 if let Some(ref tool) = msvc_tool {
180 let original_path = tool.path();
181 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
182 let arch = match t.arch.as_str() {
183 "x86_64" => Some("x64".to_string()),
184 "x86" => Some("x86".to_string()),
185 "aarch64" => Some("arm64".to_string()),
186 "arm" => Some("arm".to_string()),
189 if let Some(ref a) = arch {
190 // FIXME: Move this to `fn linker_with_args`.
191 let mut arg = OsString::from("/LIBPATH:");
192 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
195 warn!("arch is not supported");
198 warn!("MSVC root path lib location not found");
201 warn!("link.exe not found");
205 // The compiler's sysroot often has some bundled tools, so add it to the
206 // PATH for the child.
207 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(self_contained);
208 let mut msvc_changed_path = false;
209 if sess.target.target.options.is_like_msvc {
210 if let Some(ref tool) = msvc_tool {
211 cmd.args(tool.args());
212 for &(ref k, ref v) in tool.env() {
214 new_path.extend(env::split_paths(v));
215 msvc_changed_path = true;
223 if !msvc_changed_path {
224 if let Some(path) = env::var_os("PATH") {
225 new_path.extend(env::split_paths(&path));
228 cmd.env("PATH", env::join_paths(new_path).unwrap());
233 pub fn each_linked_rlib(
235 f: &mut dyn FnMut(CrateNum, &Path),
236 ) -> Result<(), String> {
237 let crates = info.used_crates_static.iter();
239 for (ty, list) in info.dependency_formats.iter() {
241 CrateType::Executable
242 | CrateType::Staticlib
244 | CrateType::ProcMacro => {
251 let fmts = match fmts {
253 None => return Err("could not find formats for rlibs".to_string()),
255 for &(cnum, ref path) in crates {
256 match fmts.get(cnum.as_usize() - 1) {
257 Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
259 None => return Err("could not find formats for rlibs".to_string()),
261 let name = &info.crate_name[&cnum];
262 let path = match *path {
263 LibSource::Some(ref p) => p,
264 LibSource::MetadataOnly => {
266 "could not find rlib for: `{}`, found rmeta (metadata) file",
270 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
277 /// We use a temp directory here to avoid races between concurrent rustc processes,
278 /// such as builds in the same directory using the same filename for metadata while
279 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
280 /// directory being searched for `extern crate` (observing an incomplete file).
281 /// The returned path is the temporary file containing the complete metadata.
282 pub fn emit_metadata(sess: &Session, metadata: &EncodedMetadata, tmpdir: &TempDir) -> PathBuf {
283 let out_filename = tmpdir.path().join(METADATA_FILENAME);
284 let result = fs::write(&out_filename, &metadata.raw_data);
286 if let Err(e) = result {
287 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
295 // An rlib in its current incarnation is essentially a renamed .a file. The
296 // rlib primarily contains the object file of the crate, but it also contains
297 // all of the object files from native libraries. This is done by unzipping
298 // native libraries and inserting all of the contents into this archive.
299 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
301 codegen_results: &CodegenResults,
306 info!("preparing rlib to {:?}", out_filename);
307 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
309 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
313 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
314 // we may not be configured to actually include a static library if we're
315 // adding it here. That's because later when we consume this rlib we'll
316 // decide whether we actually needed the static library or not.
318 // To do this "correctly" we'd need to keep track of which libraries added
319 // which object files to the archive. We don't do that here, however. The
320 // #[link(cfg(..))] feature is unstable, though, and only intended to get
321 // liblibc working. In that sense the check below just indicates that if
322 // there are any libraries we want to omit object files for at link time we
323 // just exclude all custom object files.
325 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
326 // feature then we'll need to figure out how to record what objects were
327 // loaded from the libraries found here and then encode that into the
328 // metadata of the rlib we're generating somehow.
329 for lib in codegen_results.crate_info.used_libraries.iter() {
331 NativeLibKind::StaticBundle => {}
332 NativeLibKind::StaticNoBundle
333 | NativeLibKind::Dylib
334 | NativeLibKind::Framework
335 | NativeLibKind::RawDylib
336 | NativeLibKind::Unspecified => continue,
338 if let Some(name) = lib.name {
339 ab.add_native_library(name);
343 // After adding all files to the archive, we need to update the
344 // symbol table of the archive.
347 // Note that it is important that we add all of our non-object "magical
348 // files" *after* all of the object files in the archive. The reason for
349 // this is as follows:
351 // * When performing LTO, this archive will be modified to remove
352 // objects from above. The reason for this is described below.
354 // * When the system linker looks at an archive, it will attempt to
355 // determine the architecture of the archive in order to see whether its
358 // The algorithm for this detection is: iterate over the files in the
359 // archive. Skip magical SYMDEF names. Interpret the first file as an
360 // object file. Read architecture from the object file.
362 // * As one can probably see, if "metadata" and "foo.bc" were placed
363 // before all of the objects, then the architecture of this archive would
364 // not be correctly inferred once 'foo.o' is removed.
366 // Basically, all this means is that this code should not move above the
369 RlibFlavor::Normal => {
370 // Instead of putting the metadata in an object file section, rlibs
371 // contain the metadata in a separate file.
372 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
374 // After adding all files to the archive, we need to update the
375 // symbol table of the archive. This currently dies on macOS (see
376 // #11162), and isn't necessary there anyway
377 if !sess.target.target.options.is_like_osx {
382 RlibFlavor::StaticlibBase => {
383 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
384 if let Some(obj) = obj {
393 // Create a static archive
395 // This is essentially the same thing as an rlib, but it also involves adding
396 // all of the upstream crates' objects into the archive. This will slurp in
397 // all of the native libraries of upstream dependencies as well.
399 // Additionally, there's no way for us to link dynamic libraries, so we warn
400 // about all dynamic library dependencies that they're not linked in.
402 // There's no need to include metadata in a static archive, so ensure to not
403 // link in the metadata object file (and also don't prepare the archive with a
405 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
407 codegen_results: &CodegenResults,
412 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
413 let mut all_native_libs = vec![];
415 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
416 let name = &codegen_results.crate_info.crate_name[&cnum];
417 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
419 // Here when we include the rlib into our staticlib we need to make a
420 // decision whether to include the extra object files along the way.
421 // These extra object files come from statically included native
422 // libraries, but they may be cfg'd away with #[link(cfg(..))].
424 // This unstable feature, though, only needs liblibc to work. The only
425 // use case there is where musl is statically included in liblibc.rlib,
426 // so if we don't want the included version we just need to skip it. As
427 // a result the logic here is that if *any* linked library is cfg'd away
428 // we just skip all object files.
430 // Clearly this is not sufficient for a general purpose feature, and
431 // we'd want to read from the library's metadata to determine which
432 // object files come from where and selectively skip them.
433 let skip_object_files = native_libs
435 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
439 are_upstream_rust_objects_already_included(sess)
440 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
445 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
447 if let Err(e) = res {
454 if !all_native_libs.is_empty() {
455 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
456 print_native_static_libs(sess, &all_native_libs);
461 // Create a dynamic library or executable
463 // This will invoke the system linker/cc to create the resulting file. This
464 // links to all upstream files as well.
465 fn link_natively<'a, B: ArchiveBuilder<'a>>(
467 crate_type: CrateType,
469 codegen_results: &CodegenResults,
473 info!("preparing {:?} to {:?}", crate_type, out_filename);
474 let (linker_path, flavor) = linker_and_flavor(sess);
475 let mut cmd = linker_with_args::<B>(
486 linker::disable_localization(&mut cmd);
488 for &(ref k, ref v) in &sess.target.target.options.link_env {
491 for k in &sess.target.target.options.link_env_remove {
495 if sess.opts.debugging_opts.print_link_args {
496 println!("{:?}", &cmd);
499 // May have not found libraries in the right formats.
500 sess.abort_if_errors();
502 // Invoke the system linker
504 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
509 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
510 let output = match prog {
511 Ok(ref output) => output,
514 if output.status.success() {
517 let mut out = output.stderr.clone();
518 out.extend(&output.stdout);
519 let out = String::from_utf8_lossy(&out);
521 // Check to see if the link failed with "unrecognized command line option:
522 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
523 // reperform the link step without the -no-pie option. This is safe because
524 // if the linker doesn't support -no-pie then it should not default to
525 // linking executables as pie. Different versions of gcc seem to use
526 // different quotes in the error message so don't check for them.
527 if sess.target.target.options.linker_is_gnu
528 && flavor != LinkerFlavor::Ld
529 && (out.contains("unrecognized command line option")
530 || out.contains("unknown argument"))
531 && out.contains("-no-pie")
532 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
534 info!("linker output: {:?}", out);
535 warn!("Linker does not support -no-pie command line option. Retrying without.");
536 for arg in cmd.take_args() {
537 if arg.to_string_lossy() != "-no-pie" {
545 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
546 // Fallback from '-static-pie' to '-static' in that case.
547 if sess.target.target.options.linker_is_gnu
548 && flavor != LinkerFlavor::Ld
549 && (out.contains("unrecognized command line option")
550 || out.contains("unknown argument"))
551 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
552 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
554 info!("linker output: {:?}", out);
556 "Linker does not support -static-pie command line option. Retrying with -static instead."
558 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
559 let self_contained = crt_objects_fallback(sess, crate_type);
560 let opts = &sess.target.target.options;
561 let pre_objects = if self_contained {
562 &opts.pre_link_objects_fallback
564 &opts.pre_link_objects
566 let post_objects = if self_contained {
567 &opts.post_link_objects_fallback
569 &opts.post_link_objects
571 let get_objects = |objects: &CrtObjects, kind| {
577 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
580 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
581 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
582 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
583 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
584 // Assume that we know insertion positions for the replacement arguments from replaced
585 // arguments, which is true for all supported targets.
586 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
587 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
588 for arg in cmd.take_args() {
589 if arg.to_string_lossy() == "-static-pie" {
590 // Replace the output kind.
592 } else if pre_objects_static_pie.contains(&arg) {
593 // Replace the pre-link objects (replace the first and remove the rest).
594 cmd.args(mem::take(&mut pre_objects_static));
595 } else if post_objects_static_pie.contains(&arg) {
596 // Replace the post-link objects (replace the first and remove the rest).
597 cmd.args(mem::take(&mut post_objects_static));
606 // Here's a terribly awful hack that really shouldn't be present in any
607 // compiler. Here an environment variable is supported to automatically
608 // retry the linker invocation if the linker looks like it segfaulted.
610 // Gee that seems odd, normally segfaults are things we want to know
611 // about! Unfortunately though in rust-lang/rust#38878 we're
612 // experiencing the linker segfaulting on Travis quite a bit which is
613 // causing quite a bit of pain to land PRs when they spuriously fail
614 // due to a segfault.
616 // The issue #38878 has some more debugging information on it as well,
617 // but this unfortunately looks like it's just a race condition in
618 // macOS's linker with some thread pool working in the background. It
619 // seems that no one currently knows a fix for this so in the meantime
620 // we're left with this...
621 if !retry_on_segfault || i > 3 {
624 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
625 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
626 if out.contains(msg_segv) || out.contains(msg_bus) {
628 "looks like the linker segfaulted when we tried to call it, \
629 automatically retrying again. cmd = {:?}, out = {}.",
635 if is_illegal_instruction(&output.status) {
637 "looks like the linker hit an illegal instruction when we \
638 tried to call it, automatically retrying again. cmd = {:?}, ]\
639 out = {}, status = {}.",
640 cmd, out, output.status,
646 fn is_illegal_instruction(status: &ExitStatus) -> bool {
647 use std::os::unix::prelude::*;
648 status.signal() == Some(libc::SIGILL)
652 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
659 fn escape_string(s: &[u8]) -> String {
660 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
661 let mut x = "Non-UTF-8 output: ".to_string();
662 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
666 if !prog.status.success() {
667 let mut output = prog.stderr.clone();
668 output.extend_from_slice(&prog.stdout);
669 sess.struct_err(&format!(
670 "linking with `{}` failed: {}",
671 linker_path.display(),
674 .note(&format!("{:?}", &cmd))
675 .note(&escape_string(&output))
678 // If MSVC's `link.exe` was expected but the return code
679 // is not a Microsoft LNK error then suggest a way to fix or
680 // install the Visual Studio build tools.
681 if let Some(code) = prog.status.code() {
682 if sess.target.target.options.is_like_msvc
683 && flavor == LinkerFlavor::Msvc
684 // Respect the command line override
685 && sess.opts.cg.linker.is_none()
686 // Match exactly "link.exe"
687 && linker_path.to_str() == Some("link.exe")
688 // All Microsoft `link.exe` linking error codes are
689 // four digit numbers in the range 1000 to 9999 inclusive
690 && (code < 1000 || code > 9999)
692 let is_vs_installed = windows_registry::find_vs_version().is_ok();
693 let has_linker = windows_registry::find_tool(
694 &sess.opts.target_triple.triple(),
699 sess.note_without_error("`link.exe` returned an unexpected error");
700 if is_vs_installed && has_linker {
701 // the linker is broken
702 sess.note_without_error(
703 "the Visual Studio build tools may need to be repaired \
704 using the Visual Studio installer",
706 sess.note_without_error(
707 "or a necessary component may be missing from the \
708 \"C++ build tools\" workload",
710 } else if is_vs_installed {
711 // the linker is not installed
712 sess.note_without_error(
713 "in the Visual Studio installer, ensure the \
714 \"C++ build tools\" workload is selected",
717 // visual studio is not installed
718 sess.note_without_error(
719 "you may need to install Visual Studio build tools with the \
720 \"C++ build tools\" workload",
726 sess.abort_if_errors();
728 info!("linker stderr:\n{}", escape_string(&prog.stderr));
729 info!("linker stdout:\n{}", escape_string(&prog.stdout));
732 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
734 let mut linker_error = {
735 if linker_not_found {
736 sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
738 sess.struct_err(&format!(
739 "could not exec the linker `{}`",
740 linker_path.display()
745 linker_error.note(&e.to_string());
747 if !linker_not_found {
748 linker_error.note(&format!("{:?}", &cmd));
753 if sess.target.target.options.is_like_msvc && linker_not_found {
754 sess.note_without_error(
755 "the msvc targets depend on the msvc linker \
756 but `link.exe` was not found",
758 sess.note_without_error(
759 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
760 was installed with the Visual C++ option",
763 sess.abort_if_errors();
767 // On macOS, debuggers need this utility to get run to do some munging of
768 // the symbols. Note, though, that if the object files are being preserved
769 // for their debug information there's no need for us to run dsymutil.
770 if sess.target.target.options.is_like_osx
771 && sess.opts.debuginfo != DebugInfo::None
772 && !preserve_objects_for_their_debuginfo(sess)
774 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
775 sess.fatal(&format!("failed to run dsymutil: {}", e))
780 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
781 if crate_type != CrateType::Executable {
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-linux-gnu" => {
822 let filename = format!("librustc{}_rt.{}.a", channel, name);
823 let path = default_tlib.join(&filename);
824 linker.link_whole_rlib(&path);
830 /// Returns a boolean indicating whether the specified crate should be ignored
833 /// Crates ignored during LTO are not lumped together in the "massive object
834 /// file" that we create and are linked in their normal rlib states. See
835 /// comments below for what crates do not participate in LTO.
837 /// It's unusual for a crate to not participate in LTO. Typically only
838 /// compiler-specific and unstable crates have a reason to not participate in
840 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
841 // If our target enables builtin function lowering in LLVM then the
842 // crates providing these functions don't participate in LTO (e.g.
843 // no_builtins or compiler builtins crates).
844 !sess.target.target.options.no_builtins
845 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
848 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
851 linker: Option<PathBuf>,
852 flavor: Option<LinkerFlavor>,
853 ) -> Option<(PathBuf, LinkerFlavor)> {
854 match (linker, flavor) {
855 (Some(linker), Some(flavor)) => Some((linker, flavor)),
856 // only the linker flavor is known; use the default linker for the selected flavor
857 (None, Some(flavor)) => Some((
858 PathBuf::from(match flavor {
859 LinkerFlavor::Em => {
866 LinkerFlavor::Gcc => {
867 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
868 // On historical Solaris systems, "cc" may have
869 // been Sun Studio, which is not flag-compatible
870 // with "gcc". This history casts a long shadow,
871 // and many modern illumos distributions today
872 // ship GCC as "gcc" without also making it
873 // available as "cc".
879 LinkerFlavor::Ld => "ld",
880 LinkerFlavor::Msvc => "link.exe",
881 LinkerFlavor::Lld(_) => "lld",
882 LinkerFlavor::PtxLinker => "rust-ptx-linker",
886 (Some(linker), None) => {
887 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
888 sess.fatal("couldn't extract file stem from specified linker")
891 let flavor = if stem == "emcc" {
893 } else if stem == "gcc"
894 || stem.ends_with("-gcc")
896 || stem.ends_with("-clang")
899 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
901 } else if stem == "link" || stem == "lld-link" {
903 } else if stem == "lld" || stem == "rust-lld" {
904 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
906 // fall back to the value in the target spec
907 sess.target.target.linker_flavor
910 Some((linker, flavor))
912 (None, None) => None,
916 // linker and linker flavor specified via command line have precedence over what the target
917 // specification specifies
918 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
922 if let Some(ret) = infer_from(
924 sess.target.target.options.linker.clone().map(PathBuf::from),
925 Some(sess.target.target.linker_flavor),
930 bug!("Not enough information provided to determine how to invoke the linker");
933 /// Returns a boolean indicating whether we should preserve the object files on
934 /// the filesystem for their debug information. This is often useful with
935 /// split-dwarf like schemes.
936 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
937 // If the objects don't have debuginfo there's nothing to preserve.
938 if sess.opts.debuginfo == config::DebugInfo::None {
942 // If we're only producing artifacts that are archives, no need to preserve
943 // the objects as they're losslessly contained inside the archives.
945 sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
950 // If we're on OSX then the equivalent of split dwarf is turned on by
951 // default. The final executable won't actually have any debug information
952 // except it'll have pointers to elsewhere. Historically we've always run
953 // `dsymutil` to "link all the dwarf together" but this is actually sort of
954 // a bummer for incremental compilation! (the whole point of split dwarf is
955 // that you don't do this sort of dwarf link).
957 // Basically as a result this just means that if we're on OSX and we're
958 // *not* running dsymutil then the object files are the only source of truth
959 // for debug information, so we must preserve them.
960 if sess.target.target.options.is_like_osx {
961 return !sess.opts.debugging_opts.run_dsymutil;
967 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
968 sess.target_filesearch(PathKind::Native).search_path_dirs()
976 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
977 let lib_args: Vec<_> = all_native_libs
979 .filter(|l| relevant_lib(sess, l))
981 let name = lib.name?;
983 NativeLibKind::StaticNoBundle
984 | NativeLibKind::Dylib
985 | NativeLibKind::Unspecified => {
986 if sess.target.target.options.is_like_msvc {
987 Some(format!("{}.lib", name))
989 Some(format!("-l{}", name))
992 NativeLibKind::Framework => {
993 // ld-only syntax, since there are no frameworks in MSVC
994 Some(format!("-framework {}", name))
996 // These are included, no need to print them
997 NativeLibKind::StaticBundle | NativeLibKind::RawDylib => None,
1001 if !lib_args.is_empty() {
1002 sess.note_without_error(
1003 "Link against the following native artifacts when linking \
1004 against this static library. The order and any duplication \
1005 can be significant on some platforms.",
1007 // Prefix for greppability
1008 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1012 // Because windows-gnu target is meant to be self-contained for pure Rust code it bundles
1013 // own mingw-w64 libraries. These libraries are usually not compatible with mingw-w64
1014 // installed in the system. This breaks many cases where Rust is mixed with other languages
1015 // (e.g. *-sys crates).
1016 // We prefer system mingw-w64 libraries if they are available to avoid this issue.
1017 fn get_crt_libs_path(sess: &Session) -> Option<PathBuf> {
1018 fn find_exe_in_path<P>(exe_name: P) -> Option<PathBuf>
1022 for dir in env::split_paths(&env::var_os("PATH")?) {
1023 let full_path = dir.join(&exe_name);
1024 if full_path.is_file() {
1025 return Some(fix_windows_verbatim_for_gcc(&full_path));
1031 fn probe(sess: &Session) -> Option<PathBuf> {
1032 if let (linker, LinkerFlavor::Gcc) = linker_and_flavor(&sess) {
1033 let linker_path = if cfg!(windows) && linker.extension().is_none() {
1034 linker.with_extension("exe")
1038 if let Some(linker_path) = find_exe_in_path(linker_path) {
1039 let mingw_arch = match &sess.target.target.arch {
1040 x if x == "x86" => "i686",
1043 let mingw_bits = &sess.target.target.target_pointer_width;
1044 let mingw_dir = format!("{}-w64-mingw32", mingw_arch);
1045 // Here we have path/bin/gcc but we need path/
1046 let mut path = linker_path;
1049 // Loosely based on Clang MinGW driver
1050 let probe_paths = vec![
1051 path.join(&mingw_dir).join("lib"), // Typical path
1052 path.join(&mingw_dir).join("sys-root/mingw/lib"), // Rare path
1054 "lib/mingw/tools/install/mingw{}/{}/lib",
1055 &mingw_bits, &mingw_dir
1056 )), // Chocolatey is creative
1058 for probe_path in probe_paths {
1059 if probe_path.join("crt2.o").exists() {
1060 return Some(probe_path);
1068 let mut system_library_path = sess.system_library_path.borrow_mut();
1069 match &*system_library_path {
1070 Some(Some(compiler_libs_path)) => Some(compiler_libs_path.clone()),
1073 let path = probe(sess);
1074 *system_library_path = Some(path.clone());
1080 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1081 // prefer system {,dll}crt2.o libs, see get_crt_libs_path comment for more details
1082 if sess.opts.debugging_opts.link_self_contained.is_none()
1083 && sess.target.target.llvm_target.contains("windows-gnu")
1085 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1086 let file_path = compiler_libs_path.join(name);
1087 if file_path.exists() {
1092 let fs = sess.target_filesearch(PathKind::Native);
1093 let file_path = fs.get_lib_path().join(name);
1094 if file_path.exists() {
1097 // Special directory with objects used only in self-contained linkage mode
1099 let file_path = fs.get_self_contained_lib_path().join(name);
1100 if file_path.exists() {
1104 for search_path in fs.search_paths() {
1105 let file_path = search_path.dir.join(name);
1106 if file_path.exists() {
1116 out_filename: &Path,
1118 ) -> io::Result<Output> {
1119 // When attempting to spawn the linker we run a risk of blowing out the
1120 // size limits for spawning a new process with respect to the arguments
1121 // we pass on the command line.
1123 // Here we attempt to handle errors from the OS saying "your list of
1124 // arguments is too big" by reinvoking the linker again with an `@`-file
1125 // that contains all the arguments. The theory is that this is then
1126 // accepted on all linkers and the linker will read all its options out of
1127 // there instead of looking at the command line.
1128 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1129 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1131 let output = child.wait_with_output();
1132 flush_linked_file(&output, out_filename)?;
1135 Err(ref e) if command_line_too_big(e) => {
1136 info!("command line to linker was too big: {}", e);
1138 Err(e) => return Err(e),
1142 info!("falling back to passing arguments to linker via an @-file");
1143 let mut cmd2 = cmd.clone();
1144 let mut args = String::new();
1145 for arg in cmd2.take_args() {
1148 arg: arg.to_str().unwrap(),
1149 is_like_msvc: sess.target.target.options.is_like_msvc,
1153 args.push_str("\n");
1155 let file = tmpdir.join("linker-arguments");
1156 let bytes = if sess.target.target.options.is_like_msvc {
1157 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1158 // start the stream with a UTF-16 BOM
1159 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1160 // encode in little endian
1162 out.push((c >> 8) as u8);
1168 fs::write(&file, &bytes)?;
1169 cmd2.arg(format!("@{}", file.display()));
1170 info!("invoking linker {:?}", cmd2);
1171 let output = cmd2.output();
1172 flush_linked_file(&output, out_filename)?;
1176 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1181 fn flush_linked_file(
1182 command_output: &io::Result<Output>,
1183 out_filename: &Path,
1184 ) -> io::Result<()> {
1185 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1186 // even long after process exit, causing nasty, non-reproducible output bugs.
1188 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1190 // А full writeup of the original Chrome bug can be found at
1191 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1193 if let &Ok(ref out) = command_output {
1194 if out.status.success() {
1195 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1205 fn command_line_too_big(err: &io::Error) -> bool {
1206 err.raw_os_error() == Some(::libc::E2BIG)
1210 fn command_line_too_big(err: &io::Error) -> bool {
1211 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1212 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1220 impl<'a> fmt::Display for Escape<'a> {
1221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222 if self.is_like_msvc {
1223 // This is "documented" at
1224 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1226 // Unfortunately there's not a great specification of the
1227 // syntax I could find online (at least) but some local
1228 // testing showed that this seemed sufficient-ish to catch
1229 // at least a few edge cases.
1231 for c in self.arg.chars() {
1233 '"' => write!(f, "\\{}", c)?,
1234 c => write!(f, "{}", c)?,
1239 // This is documented at https://linux.die.net/man/1/ld, namely:
1241 // > Options in file are separated by whitespace. A whitespace
1242 // > character may be included in an option by surrounding the
1243 // > entire option in either single or double quotes. Any
1244 // > character (including a backslash) may be included by
1245 // > prefixing the character to be included with a backslash.
1247 // We put an argument on each line, so all we need to do is
1248 // ensure the line is interpreted as one whole argument.
1249 for c in self.arg.chars() {
1251 '\\' | ' ' => write!(f, "\\{}", c)?,
1252 c => write!(f, "{}", c)?,
1261 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1262 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1263 (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1264 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1265 (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1266 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1267 (_, true, _) => LinkOutputKind::StaticDylib,
1268 (_, false, _) => LinkOutputKind::DynamicDylib,
1271 // Adjust the output kind to target capabilities.
1272 let opts = &sess.target.target.options;
1273 let pic_exe_supported = opts.position_independent_executables;
1274 let static_pic_exe_supported = opts.static_position_independent_executables;
1275 let static_dylib_supported = opts.crt_static_allows_dylibs;
1277 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1278 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1279 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1284 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1285 /// We only provide such support for a very limited number of targets.
1286 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1287 if let Some(self_contained) = sess.opts.debugging_opts.link_self_contained {
1288 return self_contained;
1291 match sess.target.target.options.crt_objects_fallback {
1292 // FIXME: Find a better heuristic for "native musl toolchain is available",
1293 // based on host and linker path, for example.
1294 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1295 Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1296 // FIXME: Find some heuristic for "native mingw toolchain is available",
1297 // likely based on `get_crt_libs_path` (https://github.com/rust-lang/rust/pull/67429).
1298 Some(CrtObjectsFallback::Mingw) => sess.target.target.target_vendor != "uwp",
1299 // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1300 Some(CrtObjectsFallback::Wasm) => true,
1305 /// Add pre-link object files defined by the target spec.
1306 fn add_pre_link_objects(
1307 cmd: &mut dyn Linker,
1309 link_output_kind: LinkOutputKind,
1310 self_contained: bool,
1312 let opts = &sess.target.target.options;
1314 if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1315 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1316 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1320 /// Add post-link object files defined by the target spec.
1321 fn add_post_link_objects(
1322 cmd: &mut dyn Linker,
1324 link_output_kind: LinkOutputKind,
1325 self_contained: bool,
1327 let opts = &sess.target.target.options;
1329 if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1330 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1331 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1335 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1336 /// FIXME: Determine where exactly these args need to be inserted.
1337 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1338 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
1341 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1344 /// Add a link script embedded in the target, if applicable.
1345 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1346 match (crate_type, &sess.target.target.options.link_script) {
1347 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1348 if !sess.target.target.options.linker_is_gnu {
1349 sess.fatal("can only use link script when linking with GNU-like linker");
1352 let file_name = ["rustc", &sess.target.target.llvm_target, "linkfile.ld"].join("-");
1354 let path = tmpdir.join(file_name);
1355 if let Err(e) = fs::write(&path, script) {
1356 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1359 cmd.arg("--script");
1366 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1367 /// FIXME: Determine where exactly these args need to be inserted.
1368 fn add_user_defined_link_args(
1369 cmd: &mut dyn Linker,
1371 codegen_results: &CodegenResults,
1373 cmd.args(&sess.opts.cg.link_args);
1374 cmd.args(&*codegen_results.crate_info.link_args);
1377 /// Add arbitrary "late link" args defined by the target spec.
1378 /// FIXME: Determine where exactly these args need to be inserted.
1379 fn add_late_link_args(
1380 cmd: &mut dyn Linker,
1382 flavor: LinkerFlavor,
1383 crate_type: CrateType,
1384 codegen_results: &CodegenResults,
1386 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
1389 let any_dynamic_crate = crate_type == CrateType::Dylib
1390 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1391 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1393 if any_dynamic_crate {
1394 if let Some(args) = sess.target.target.options.late_link_args_dynamic.get(&flavor) {
1398 if let Some(args) = sess.target.target.options.late_link_args_static.get(&flavor) {
1404 /// Add arbitrary "post-link" args defined by the target spec.
1405 /// FIXME: Determine where exactly these args need to be inserted.
1406 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1407 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
1412 /// Add object files containing code from the current crate.
1413 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1414 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1415 cmd.add_object(obj);
1419 /// Add object files for allocator code linked once for the whole crate tree.
1420 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1421 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1422 cmd.add_object(obj);
1426 /// Add object files containing metadata for the current crate.
1427 fn add_local_crate_metadata_objects(
1428 cmd: &mut dyn Linker,
1429 crate_type: CrateType,
1430 codegen_results: &CodegenResults,
1432 // When linking a dynamic library, we put the metadata into a section of the
1433 // executable. This metadata is in a separate object file from the main
1434 // object file, so we link that in here.
1435 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1436 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1438 cmd.add_object(obj);
1443 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1444 /// all its dependency crates.
1445 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1446 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1447 cmd: &mut dyn Linker,
1449 crate_type: CrateType,
1450 codegen_results: &CodegenResults,
1453 // Take careful note of the ordering of the arguments we pass to the linker
1454 // here. Linkers will assume that things on the left depend on things to the
1455 // right. Things on the right cannot depend on things on the left. This is
1456 // all formally implemented in terms of resolving symbols (libs on the right
1457 // resolve unknown symbols of libs on the left, but not vice versa).
1459 // For this reason, we have organized the arguments we pass to the linker as
1462 // 1. The local object that LLVM just generated
1463 // 2. Local native libraries
1464 // 3. Upstream rust libraries
1465 // 4. Upstream native libraries
1467 // The rationale behind this ordering is that those items lower down in the
1468 // list can't depend on items higher up in the list. For example nothing can
1469 // depend on what we just generated (e.g., that'd be a circular dependency).
1470 // Upstream rust libraries are not allowed to depend on our local native
1471 // libraries as that would violate the structure of the DAG, in that
1472 // scenario they are required to link to them as well in a shared fashion.
1474 // Note that upstream rust libraries may contain native dependencies as
1475 // well, but they also can't depend on what we just started to add to the
1476 // link line. And finally upstream native libraries can't depend on anything
1477 // in this DAG so far because they're only dylibs and dylibs can only depend
1478 // on other dylibs (e.g., other native deps).
1480 // If -Zlink-native-libraries=false is set, then the assumption is that an
1481 // external build system already has the native dependencies defined, and it
1482 // will provide them to the linker itself.
1483 if sess.opts.debugging_opts.link_native_libraries {
1484 add_local_native_libraries(cmd, sess, codegen_results);
1486 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1487 if sess.opts.debugging_opts.link_native_libraries {
1488 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1492 /// Add sysroot and other globally set directories to the directory search list.
1493 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1494 // Prefer system mingw-w64 libs, see get_crt_libs_path comment for more details.
1495 if sess.opts.debugging_opts.link_self_contained.is_none()
1497 && sess.target.target.llvm_target.contains("windows-gnu")
1499 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1500 cmd.include_path(&compiler_libs_path);
1504 // The default library location, we need this to find the runtime.
1505 // The location of crates will be determined as needed.
1506 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1507 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1509 // Special directory with libraries used only in self-contained linkage mode
1511 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1512 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1516 /// Add options making relocation sections in the produced ELF files read-only
1517 /// and suppressing lazy binding.
1518 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1519 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.target.options.relro_level) {
1520 RelroLevel::Full => cmd.full_relro(),
1521 RelroLevel::Partial => cmd.partial_relro(),
1522 RelroLevel::Off => cmd.no_relro(),
1523 RelroLevel::None => {}
1527 /// Add library search paths used at runtime by dynamic linkers.
1529 cmd: &mut dyn Linker,
1531 codegen_results: &CodegenResults,
1532 out_filename: &Path,
1534 // FIXME (#2397): At some point we want to rpath our guesses as to
1535 // where extern libraries might live, based on the
1536 // addl_lib_search_paths
1537 if sess.opts.cg.rpath {
1538 let target_triple = sess.opts.target_triple.triple();
1539 let mut get_install_prefix_lib_path = || {
1540 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1541 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1542 let mut path = PathBuf::from(install_prefix);
1547 let mut rpath_config = RPathConfig {
1548 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1549 out_filename: out_filename.to_path_buf(),
1550 has_rpath: sess.target.target.options.has_rpath,
1551 is_like_osx: sess.target.target.options.is_like_osx,
1552 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1553 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1555 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1559 /// Produce the linker command line containing linker path and arguments.
1560 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1561 /// by the user without creating a custom target specification.
1562 /// `OBJECT-FILES` specify whether the arguments can add object files.
1563 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1564 /// or by the target spec can be inserted here.
1565 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1566 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1568 flavor: LinkerFlavor,
1570 crate_type: CrateType,
1572 out_filename: &Path,
1573 codegen_results: &CodegenResults,
1576 let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1577 let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1578 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1579 // to the linker args construction.
1580 assert!(base_cmd.get_args().is_empty() || sess.target.target.target_vendor == "uwp");
1581 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1582 let link_output_kind = link_output_kind(sess, crate_type);
1584 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1585 add_pre_link_args(cmd, sess, flavor);
1588 add_link_script(cmd, sess, tmpdir, crate_type);
1590 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1591 if sess.target.target.options.is_like_fuchsia && crate_type == CrateType::Executable {
1592 let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1597 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1600 // NO-OPT-OUT, OBJECT-FILES-NO
1601 if crt_objects_fallback {
1602 cmd.no_crt_objects();
1605 // NO-OPT-OUT, OBJECT-FILES-YES
1606 add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1608 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1609 if sess.target.target.options.is_like_emscripten {
1611 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1612 "DISABLE_EXCEPTION_CATCHING=1"
1614 "DISABLE_EXCEPTION_CATCHING=0"
1618 // OBJECT-FILES-YES, AUDIT-ORDER
1619 link_sanitizers(sess, crate_type, cmd);
1621 // OBJECT-FILES-NO, AUDIT-ORDER
1622 // Linker plugins should be specified early in the list of arguments
1623 // FIXME: How "early" exactly?
1624 cmd.linker_plugin_lto();
1626 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1627 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1628 add_library_search_dirs(cmd, sess, crt_objects_fallback);
1631 add_local_crate_regular_objects(cmd, codegen_results);
1633 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1634 cmd.output_filename(out_filename);
1636 // OBJECT-FILES-NO, AUDIT-ORDER
1637 if crate_type == CrateType::Executable && sess.target.target.options.is_like_windows {
1638 if let Some(ref s) = codegen_results.windows_subsystem {
1643 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1644 // If we're building something like a dynamic library then some platforms
1645 // need to make sure that all symbols are exported correctly from the
1647 cmd.export_symbols(tmpdir, crate_type);
1650 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1653 add_local_crate_allocator_objects(cmd, codegen_results);
1655 // OBJECT-FILES-NO, AUDIT-ORDER
1656 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1657 // Try to strip as much out of the generated object by removing unused
1658 // sections if possible. See more comments in linker.rs
1659 if !sess.opts.cg.link_dead_code {
1660 let keep_metadata = crate_type == CrateType::Dylib;
1661 cmd.gc_sections(keep_metadata);
1664 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1665 cmd.set_output_kind(link_output_kind, out_filename);
1667 // OBJECT-FILES-NO, AUDIT-ORDER
1668 add_relro_args(cmd, sess);
1670 // OBJECT-FILES-NO, AUDIT-ORDER
1671 // Pass optimization flags down to the linker.
1674 // OBJECT-FILES-NO, AUDIT-ORDER
1675 // Pass debuginfo and strip flags down to the linker.
1676 cmd.debuginfo(sess.opts.debugging_opts.strip);
1678 // OBJECT-FILES-NO, AUDIT-ORDER
1679 // We want to prevent the compiler from accidentally leaking in any system libraries,
1680 // so by default we tell linkers not to link to any default libraries.
1681 if !sess.opts.cg.default_linker_libraries && sess.target.target.options.no_default_libraries {
1682 cmd.no_default_libraries();
1686 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1694 // OBJECT-FILES-NO, AUDIT-ORDER
1695 if sess.opts.cg.profile_generate.enabled() {
1699 // OBJECT-FILES-NO, AUDIT-ORDER
1700 if sess.opts.debugging_opts.control_flow_guard != CFGuard::Disabled {
1701 cmd.control_flow_guard();
1704 // OBJECT-FILES-NO, AUDIT-ORDER
1705 add_rpath_args(cmd, sess, codegen_results, out_filename);
1707 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1708 add_user_defined_link_args(cmd, sess, codegen_results);
1710 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1713 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1714 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1716 // NO-OPT-OUT, OBJECT-FILES-YES
1717 add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1719 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1720 add_post_link_args(cmd, sess, flavor);
1725 // # Native library linking
1727 // User-supplied library search paths (-L on the command line). These are
1728 // the same paths used to find Rust crates, so some of them may have been
1729 // added already by the previous crate linking code. This only allows them
1730 // to be found at compile time so it is still entirely up to outside
1731 // forces to make sure that library can be found at runtime.
1733 // Also note that the native libraries linked here are only the ones located
1734 // in the current crate. Upstream crates with native library dependencies
1735 // may have their native library pulled in above.
1736 fn add_local_native_libraries(
1737 cmd: &mut dyn Linker,
1739 codegen_results: &CodegenResults,
1741 let filesearch = sess.target_filesearch(PathKind::All);
1742 for search_path in filesearch.search_paths() {
1743 match search_path.kind {
1744 PathKind::Framework => {
1745 cmd.framework_path(&search_path.dir);
1748 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1754 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1756 let search_path = archive_search_paths(sess);
1757 for lib in relevant_libs {
1758 let name = match lib.name {
1763 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1764 NativeLibKind::Framework => cmd.link_framework(name),
1765 NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1766 NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1767 NativeLibKind::RawDylib => {
1768 // FIXME(#58713): Proper handling for raw dylibs.
1769 bug!("raw_dylib feature not yet implemented");
1775 // # Rust Crate linking
1777 // Rust crates are not considered at all when creating an rlib output. All
1778 // dependencies will be linked when producing the final output (instead of
1779 // the intermediate rlib version)
1780 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1781 cmd: &mut dyn Linker,
1783 codegen_results: &CodegenResults,
1784 crate_type: CrateType,
1787 // All of the heavy lifting has previously been accomplished by the
1788 // dependency_format module of the compiler. This is just crawling the
1789 // output of that module, adding crates as necessary.
1791 // Linking to a rlib involves just passing it to the linker (the linker
1792 // will slurp up the object files inside), and linking to a dynamic library
1793 // involves just passing the right -l flag.
1795 let (_, data) = codegen_results
1799 .find(|(ty, _)| *ty == crate_type)
1800 .expect("failed to find crate type in dependency format list");
1802 // Invoke get_used_crates to ensure that we get a topological sorting of
1804 let deps = &codegen_results.crate_info.used_crates_dynamic;
1806 // There's a few internal crates in the standard library (aka libcore and
1807 // libstd) which actually have a circular dependence upon one another. This
1808 // currently arises through "weak lang items" where libcore requires things
1809 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1810 // circular dependence to work correctly in all situations we'll need to be
1811 // sure to correctly apply the `--start-group` and `--end-group` options to
1812 // GNU linkers, otherwise if we don't use any other symbol from the standard
1813 // library it'll get discarded and the whole application won't link.
1815 // In this loop we're calculating the `group_end`, after which crate to
1816 // pass `--end-group` and `group_start`, before which crate to pass
1817 // `--start-group`. We currently do this by passing `--end-group` after
1818 // the first crate (when iterating backwards) that requires a lang item
1819 // defined somewhere else. Once that's set then when we've defined all the
1820 // necessary lang items we'll pass `--start-group`.
1822 // Note that this isn't amazing logic for now but it should do the trick
1823 // for the current implementation of the standard library.
1824 let mut group_end = None;
1825 let mut group_start = None;
1826 // Crates available for linking thus far.
1827 let mut available = FxHashSet::default();
1828 // Crates required to satisfy dependencies discovered so far.
1829 let mut required = FxHashSet::default();
1831 let info = &codegen_results.crate_info;
1832 for &(cnum, _) in deps.iter().rev() {
1833 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1834 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1835 required.extend(missing_crates);
1838 required.insert(Some(cnum));
1839 available.insert(Some(cnum));
1841 if required.len() > available.len() && group_end.is_none() {
1842 group_end = Some(cnum);
1844 if required.len() == available.len() && group_end.is_some() {
1845 group_start = Some(cnum);
1850 // If we didn't end up filling in all lang items from upstream crates then
1851 // we'll be filling it in with our crate. This probably means we're the
1852 // standard library itself, so skip this for now.
1853 if group_end.is_some() && group_start.is_none() {
1857 let mut compiler_builtins = None;
1859 for &(cnum, _) in deps.iter() {
1860 if group_start == Some(cnum) {
1864 // We may not pass all crates through to the linker. Some crates may
1865 // appear statically in an existing dylib, meaning we'll pick up all the
1866 // symbols from the dylib.
1867 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1868 match data[cnum.as_usize() - 1] {
1869 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1870 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1872 // compiler-builtins are always placed last to ensure that they're
1873 // linked correctly.
1874 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1875 assert!(compiler_builtins.is_none());
1876 compiler_builtins = Some(cnum);
1878 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1879 Linkage::Static => {
1880 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1882 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1885 if group_end == Some(cnum) {
1890 // compiler-builtins are always placed last to ensure that they're
1891 // linked correctly.
1892 // We must always link the `compiler_builtins` crate statically. Even if it
1893 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1895 if let Some(cnum) = compiler_builtins {
1896 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1899 // Converts a library file-stem into a cc -l argument
1900 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1901 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1908 // Adds the static "rlib" versions of all crates to the command line.
1909 // There's a bit of magic which happens here specifically related to LTO and
1910 // dynamic libraries. Specifically:
1912 // * For LTO, we remove upstream object files.
1913 // * For dylibs we remove metadata and bytecode from upstream rlibs
1915 // When performing LTO, almost(*) all of the bytecode from the upstream
1916 // libraries has already been included in our object file output. As a
1917 // result we need to remove the object files in the upstream libraries so
1918 // the linker doesn't try to include them twice (or whine about duplicate
1919 // symbols). We must continue to include the rest of the rlib, however, as
1920 // it may contain static native libraries which must be linked in.
1922 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1923 // their bytecode wasn't included. The object files in those libraries must
1924 // still be passed to the linker.
1926 // When making a dynamic library, linkers by default don't include any
1927 // object files in an archive if they're not necessary to resolve the link.
1928 // We basically want to convert the archive (rlib) to a dylib, though, so we
1929 // *do* want everything included in the output, regardless of whether the
1930 // linker thinks it's needed or not. As a result we must use the
1931 // --whole-archive option (or the platform equivalent). When using this
1932 // option the linker will fail if there are non-objects in the archive (such
1933 // as our own metadata and/or bytecode). All in all, for rlibs to be
1934 // entirely included in dylibs, we need to remove all non-object files.
1936 // Note, however, that if we're not doing LTO or we're not producing a dylib
1937 // (aka we're making an executable), we can just pass the rlib blindly to
1938 // the linker (fast) because it's fine if it's not actually included as
1939 // we're at the end of the dependency chain.
1940 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1941 cmd: &mut dyn Linker,
1943 codegen_results: &CodegenResults,
1945 crate_type: CrateType,
1948 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1949 let cratepath = &src.rlib.as_ref().unwrap().0;
1951 // See the comment above in `link_staticlib` and `link_rlib` for why if
1952 // there's a static library that's not relevant we skip all object
1954 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1955 let skip_native = native_libs
1957 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1959 if (!are_upstream_rust_objects_already_included(sess)
1960 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1961 && crate_type != CrateType::Dylib
1964 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1968 let dst = tmpdir.join(cratepath.file_name().unwrap());
1969 let name = cratepath.file_name().unwrap().to_str().unwrap();
1970 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1972 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1973 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1974 archive.update_symbols();
1976 let mut any_objects = false;
1977 for f in archive.src_files() {
1978 if f == METADATA_FILENAME {
1979 archive.remove_file(&f);
1983 let canonical = f.replace("-", "_");
1984 let canonical_name = name.replace("-", "_");
1986 let is_rust_object =
1987 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
1989 // If we've been requested to skip all native object files
1990 // (those not generated by the rust compiler) then we can skip
1991 // this file. See above for why we may want to do this.
1992 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1994 // If we're performing LTO and this is a rust-generated object
1995 // file, then we don't need the object file as it's part of the
1996 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1997 // though, so we let that object file slide.
1998 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
2000 && (sess.target.target.options.no_builtins
2001 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
2003 if skip_because_cfg_say_so || skip_because_lto {
2004 archive.remove_file(&f);
2015 // If we're creating a dylib, then we need to include the
2016 // whole of each object in our archive into that artifact. This is
2017 // because a `dylib` can be reused as an intermediate artifact.
2019 // Note, though, that we don't want to include the whole of a
2020 // compiler-builtins crate (e.g., compiler-rt) because it'll get
2021 // repeatedly linked anyway.
2022 if crate_type == CrateType::Dylib
2023 && codegen_results.crate_info.compiler_builtins != Some(cnum)
2025 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
2027 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
2032 // Same thing as above, but for dynamic crates instead of static crates.
2033 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2034 // Just need to tell the linker about where the library lives and
2036 let parent = cratepath.parent();
2037 if let Some(dir) = parent {
2038 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2040 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2041 cmd.link_rust_dylib(
2042 Symbol::intern(&unlib(&sess.target, filestem)),
2043 parent.unwrap_or(Path::new("")),
2048 // Link in all of our upstream crates' native dependencies. Remember that
2049 // all of these upstream native dependencies are all non-static
2050 // dependencies. We've got two cases then:
2052 // 1. The upstream crate is an rlib. In this case we *must* link in the
2053 // native dependency because the rlib is just an archive.
2055 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
2056 // have the dependency present on the system somewhere. Thus, we don't
2057 // gain a whole lot from not linking in the dynamic dependency to this
2060 // The use case for this is a little subtle. In theory the native
2061 // dependencies of a crate are purely an implementation detail of the crate
2062 // itself, but the problem arises with generic and inlined functions. If a
2063 // generic function calls a native function, then the generic function must
2064 // be instantiated in the target crate, meaning that the native symbol must
2065 // also be resolved in the target crate.
2066 fn add_upstream_native_libraries(
2067 cmd: &mut dyn Linker,
2069 codegen_results: &CodegenResults,
2070 crate_type: CrateType,
2072 // Be sure to use a topological sorting of crates because there may be
2073 // interdependencies between native libraries. When passing -nodefaultlibs,
2074 // for example, almost all native libraries depend on libc, so we have to
2075 // make sure that's all the way at the right (liblibc is near the base of
2076 // the dependency chain).
2078 // This passes RequireStatic, but the actual requirement doesn't matter,
2079 // we're just getting an ordering of crate numbers, we're not worried about
2081 let (_, data) = codegen_results
2085 .find(|(ty, _)| *ty == crate_type)
2086 .expect("failed to find crate type in dependency format list");
2088 let crates = &codegen_results.crate_info.used_crates_static;
2089 for &(cnum, _) in crates {
2090 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2091 let name = match lib.name {
2095 if !relevant_lib(sess, &lib) {
2099 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2100 NativeLibKind::Framework => cmd.link_framework(name),
2101 NativeLibKind::StaticNoBundle => {
2102 // Link "static-nobundle" native libs only if the crate they originate from
2103 // is being linked statically to the current crate. If it's linked dynamically
2104 // or is an rlib already included via some other dylib crate, the symbols from
2105 // native libs will have already been included in that dylib.
2106 if data[cnum.as_usize() - 1] == Linkage::Static {
2107 cmd.link_staticlib(name)
2110 // ignore statically included native libraries here as we've
2111 // already included them when we included the rust library
2113 NativeLibKind::StaticBundle => {}
2114 NativeLibKind::RawDylib => {
2115 // FIXME(#58713): Proper handling for raw dylibs.
2116 bug!("raw_dylib feature not yet implemented");
2123 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2125 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2130 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2132 config::Lto::Fat => true,
2133 config::Lto::Thin => {
2134 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2135 // any upstream object files have not been copied yet.
2136 !sess.opts.cg.linker_plugin_lto.enabled()
2138 config::Lto::No | config::Lto::ThinLocal => false,