1 use rustc::middle::cstore::{EncodedMetadata, LibSource, NativeLibrary, NativeLibraryKind};
2 use rustc::middle::dependency_format::Linkage;
3 use rustc::session::config::{
4 self, CFGuard, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer,
6 use rustc::session::search_paths::PathKind;
7 /// For all the linkers we support, and information they might
8 /// need out of the shared crate context before we get rid of it.
9 use rustc::session::{filesearch, Session};
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_fs_util::fix_windows_verbatim_for_gcc;
12 use rustc_hir::def_id::CrateNum;
13 use rustc_span::symbol::Symbol;
14 use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
16 use super::archive::ArchiveBuilder;
17 use super::command::Command;
18 use super::linker::Linker;
19 use super::rpath::{self, RPathConfig};
21 looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME,
22 RLIB_BYTECODE_EXTENSION,
25 use cc::windows_registry;
26 use tempfile::{Builder as TempFileBuilder, TempDir};
31 use std::ffi::OsString;
35 use std::path::{Path, PathBuf};
36 use std::process::{ExitStatus, Output, Stdio};
39 pub use rustc_codegen_utils::link::*;
41 pub fn remove(sess: &Session, path: &Path) {
42 if let Err(e) = fs::remove_file(path) {
43 sess.err(&format!("failed to remove {}: {}", path.display(), e));
47 /// Performs the linkage portion of the compilation phase. This will generate all
48 /// of the requested outputs for this compilation session.
49 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
51 codegen_results: &CodegenResults,
52 outputs: &OutputFilenames,
56 let _timer = sess.timer("link_binary");
57 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
58 for &crate_type in sess.crate_types.borrow().iter() {
59 // Ignore executable crates if we have -Z no-codegen, as they will error.
60 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
62 && crate_type == config::CrateType::Executable
67 if invalid_output_for_target(sess, crate_type) {
69 "invalid output type `{:?}` for target os `{}`",
71 sess.opts.target_triple
75 sess.time("link_binary_check_files_are_writeable", || {
76 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
77 check_file_is_writeable(obj, sess);
81 let tmpdir = TempFileBuilder::new()
84 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
86 if outputs.outputs.should_codegen() {
87 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
89 config::CrateType::Rlib => {
90 let _timer = sess.timer("link_rlib");
100 config::CrateType::Staticlib => {
101 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
114 if sess.opts.json_artifact_notifications {
115 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
119 if sess.opts.cg.save_temps {
120 let _ = tmpdir.into_path();
124 // Remove the temporary object file and metadata if we aren't saving temps
125 sess.time("link_binary_remove_temps", || {
126 if !sess.opts.cg.save_temps {
127 if sess.opts.output_types.should_codegen()
128 && !preserve_objects_for_their_debuginfo(sess)
130 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
134 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref())
138 if let Some(ref metadata_module) = codegen_results.metadata_module {
139 if let Some(ref obj) = metadata_module.object {
143 if let Some(ref allocator_module) = codegen_results.allocator_module {
144 if let Some(ref obj) = allocator_module.object {
147 if let Some(ref bc) = allocator_module.bytecode_compressed {
155 // The third parameter is for env vars, used on windows to set up the
156 // path for MSVC to find its DLLs, and gcc to find its bundled
158 pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
159 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
161 // If our linker looks like a batch script on Windows then to execute this
162 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
163 // emscripten where the linker is `emcc.bat` and needs to be spawned as
164 // `cmd /c emcc.bat ...`.
166 // This worked historically but is needed manually since #42436 (regression
167 // was tagged as #42791) and some more info can be found on #44443 for
168 // emscripten itself.
169 let mut cmd = match linker.to_str() {
170 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
172 LinkerFlavor::Lld(f) => Command::lld(linker, f),
174 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
176 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
178 _ => Command::new(linker),
182 // UWP apps have API restrictions enforced during Store submissions.
183 // To comply with the Windows App Certification Kit,
184 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
185 let t = &sess.target.target;
186 if flavor == LinkerFlavor::Msvc && t.target_vendor == "uwp" {
187 if let Some(ref tool) = msvc_tool {
188 let original_path = tool.path();
189 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
190 let arch = match t.arch.as_str() {
191 "x86_64" => Some("x64".to_string()),
192 "x86" => Some("x86".to_string()),
193 "aarch64" => Some("arm64".to_string()),
196 if let Some(ref a) = arch {
197 let mut arg = OsString::from("/LIBPATH:");
198 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
201 warn!("arch is not supported");
204 warn!("MSVC root path lib location not found");
207 warn!("link.exe not found");
211 // The compiler's sysroot often has some bundled tools, so add it to the
212 // PATH for the child.
213 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
214 let mut msvc_changed_path = false;
215 if sess.target.target.options.is_like_msvc {
216 if let Some(ref tool) = msvc_tool {
217 cmd.args(tool.args());
218 for &(ref k, ref v) in tool.env() {
220 new_path.extend(env::split_paths(v));
221 msvc_changed_path = true;
229 if !msvc_changed_path {
230 if let Some(path) = env::var_os("PATH") {
231 new_path.extend(env::split_paths(&path));
234 cmd.env("PATH", env::join_paths(new_path).unwrap());
236 (linker.to_path_buf(), cmd)
239 pub fn each_linked_rlib(
241 f: &mut dyn FnMut(CrateNum, &Path),
242 ) -> Result<(), String> {
243 let crates = info.used_crates_static.iter();
245 for (ty, list) in info.dependency_formats.iter() {
247 config::CrateType::Executable
248 | config::CrateType::Staticlib
249 | config::CrateType::Cdylib
250 | config::CrateType::ProcMacro => {
257 let fmts = match fmts {
259 None => return Err("could not find formats for rlibs".to_string()),
261 for &(cnum, ref path) in crates {
262 match fmts.get(cnum.as_usize() - 1) {
263 Some(&Linkage::NotLinked) | Some(&Linkage::IncludedFromDylib) => continue,
265 None => return Err("could not find formats for rlibs".to_string()),
267 let name = &info.crate_name[&cnum];
268 let path = match *path {
269 LibSource::Some(ref p) => p,
270 LibSource::MetadataOnly => {
272 "could not find rlib for: `{}`, found rmeta (metadata) file",
276 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
283 /// We use a temp directory here to avoid races between concurrent rustc processes,
284 /// such as builds in the same directory using the same filename for metadata while
285 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
286 /// directory being searched for `extern crate` (observing an incomplete file).
287 /// The returned path is the temporary file containing the complete metadata.
288 pub fn emit_metadata<'a>(
290 metadata: &EncodedMetadata,
293 let out_filename = tmpdir.path().join(METADATA_FILENAME);
294 let result = fs::write(&out_filename, &metadata.raw_data);
296 if let Err(e) = result {
297 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
305 // An rlib in its current incarnation is essentially a renamed .a file. The
306 // rlib primarily contains the object file of the crate, but it also contains
307 // all of the object files from native libraries. This is done by unzipping
308 // native libraries and inserting all of the contents into this archive.
309 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
311 codegen_results: &CodegenResults,
316 info!("preparing rlib to {:?}", out_filename);
317 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
319 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
323 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
324 // we may not be configured to actually include a static library if we're
325 // adding it here. That's because later when we consume this rlib we'll
326 // decide whether we actually needed the static library or not.
328 // To do this "correctly" we'd need to keep track of which libraries added
329 // which object files to the archive. We don't do that here, however. The
330 // #[link(cfg(..))] feature is unstable, though, and only intended to get
331 // liblibc working. In that sense the check below just indicates that if
332 // there are any libraries we want to omit object files for at link time we
333 // just exclude all custom object files.
335 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
336 // feature then we'll need to figure out how to record what objects were
337 // loaded from the libraries found here and then encode that into the
338 // metadata of the rlib we're generating somehow.
339 for lib in codegen_results.crate_info.used_libraries.iter() {
341 NativeLibraryKind::NativeStatic => {}
342 NativeLibraryKind::NativeStaticNobundle
343 | NativeLibraryKind::NativeFramework
344 | NativeLibraryKind::NativeRawDylib
345 | NativeLibraryKind::NativeUnknown => continue,
347 if let Some(name) = lib.name {
348 ab.add_native_library(name);
352 // After adding all files to the archive, we need to update the
353 // symbol table of the archive.
356 // Note that it is important that we add all of our non-object "magical
357 // files" *after* all of the object files in the archive. The reason for
358 // this is as follows:
360 // * When performing LTO, this archive will be modified to remove
361 // objects from above. The reason for this is described below.
363 // * When the system linker looks at an archive, it will attempt to
364 // determine the architecture of the archive in order to see whether its
367 // The algorithm for this detection is: iterate over the files in the
368 // archive. Skip magical SYMDEF names. Interpret the first file as an
369 // object file. Read architecture from the object file.
371 // * As one can probably see, if "metadata" and "foo.bc" were placed
372 // before all of the objects, then the architecture of this archive would
373 // not be correctly inferred once 'foo.o' is removed.
375 // Basically, all this means is that this code should not move above the
378 RlibFlavor::Normal => {
379 // Instead of putting the metadata in an object file section, rlibs
380 // contain the metadata in a separate file.
381 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
383 // For LTO purposes, the bytecode of this library is also inserted
386 codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref())
388 ab.add_file(bytecode);
391 // After adding all files to the archive, we need to update the
392 // symbol table of the archive. This currently dies on macOS (see
393 // #11162), and isn't necessary there anyway
394 if !sess.target.target.options.is_like_osx {
399 RlibFlavor::StaticlibBase => {
400 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
401 if let Some(obj) = obj {
410 // Create a static archive
412 // This is essentially the same thing as an rlib, but it also involves adding
413 // all of the upstream crates' objects into the archive. This will slurp in
414 // all of the native libraries of upstream dependencies as well.
416 // Additionally, there's no way for us to link dynamic libraries, so we warn
417 // about all dynamic library dependencies that they're not linked in.
419 // There's no need to include metadata in a static archive, so ensure to not
420 // link in the metadata object file (and also don't prepare the archive with a
422 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
424 codegen_results: &CodegenResults,
429 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
430 let mut all_native_libs = vec![];
432 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
433 let name = &codegen_results.crate_info.crate_name[&cnum];
434 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
436 // Here when we include the rlib into our staticlib we need to make a
437 // decision whether to include the extra object files along the way.
438 // These extra object files come from statically included native
439 // libraries, but they may be cfg'd away with #[link(cfg(..))].
441 // This unstable feature, though, only needs liblibc to work. The only
442 // use case there is where musl is statically included in liblibc.rlib,
443 // so if we don't want the included version we just need to skip it. As
444 // a result the logic here is that if *any* linked library is cfg'd away
445 // we just skip all object files.
447 // Clearly this is not sufficient for a general purpose feature, and
448 // we'd want to read from the library's metadata to determine which
449 // object files come from where and selectively skip them.
450 let skip_object_files = native_libs
452 .any(|lib| lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib));
456 are_upstream_rust_objects_already_included(sess)
457 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
462 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
464 if let Err(e) = res {
471 if !all_native_libs.is_empty() {
472 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
473 print_native_static_libs(sess, &all_native_libs);
478 // Create a dynamic library or executable
480 // This will invoke the system linker/cc to create the resulting file. This
481 // links to all upstream files as well.
482 fn link_natively<'a, B: ArchiveBuilder<'a>>(
484 crate_type: config::CrateType,
486 codegen_results: &CodegenResults,
490 info!("preparing {:?} to {:?}", crate_type, out_filename);
491 let (linker, flavor) = linker_and_flavor(sess);
493 let any_dynamic_crate = crate_type == config::CrateType::Dylib
494 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
495 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
498 // The invocations of cc share some flags across platforms
499 let (pname, mut cmd) = get_linker(sess, &linker, flavor);
501 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
504 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
505 if sess.crt_static() {
509 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
512 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
514 if sess.target.target.options.is_like_fuchsia {
515 let prefix = match sess.opts.debugging_opts.sanitizer {
516 Some(Sanitizer::Address) => "asan/",
519 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
522 let pre_link_objects = if crate_type == config::CrateType::Executable {
523 &sess.target.target.options.pre_link_objects_exe
525 &sess.target.target.options.pre_link_objects_dll
527 for obj in pre_link_objects {
528 cmd.arg(get_file_path(sess, obj));
531 if crate_type == config::CrateType::Executable && sess.crt_static() {
532 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
533 cmd.arg(get_file_path(sess, obj));
537 if sess.target.target.options.is_like_emscripten {
539 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
540 "DISABLE_EXCEPTION_CATCHING=1"
542 "DISABLE_EXCEPTION_CATCHING=0"
547 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
548 link_sanitizer_runtime(sess, crate_type, &mut *linker);
558 cmd = linker.finalize();
560 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
563 if any_dynamic_crate {
564 if let Some(args) = sess.target.target.options.late_link_args_dynamic.get(&flavor) {
568 if let Some(args) = sess.target.target.options.late_link_args_static.get(&flavor) {
572 for obj in &sess.target.target.options.post_link_objects {
573 cmd.arg(get_file_path(sess, obj));
575 if sess.crt_static() {
576 for obj in &sess.target.target.options.post_link_objects_crt {
577 cmd.arg(get_file_path(sess, obj));
580 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
583 for &(ref k, ref v) in &sess.target.target.options.link_env {
586 for k in &sess.target.target.options.link_env_remove {
590 if sess.opts.debugging_opts.print_link_args {
591 println!("{:?}", &cmd);
594 // May have not found libraries in the right formats.
595 sess.abort_if_errors();
597 // Invoke the system linker
599 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
604 prog = sess.time("run_linker", || exec_linker(sess, &mut cmd, out_filename, tmpdir));
605 let output = match prog {
606 Ok(ref output) => output,
609 if output.status.success() {
612 let mut out = output.stderr.clone();
613 out.extend(&output.stdout);
614 let out = String::from_utf8_lossy(&out);
616 // Check to see if the link failed with "unrecognized command line option:
617 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
618 // reperform the link step without the -no-pie option. This is safe because
619 // if the linker doesn't support -no-pie then it should not default to
620 // linking executables as pie. Different versions of gcc seem to use
621 // different quotes in the error message so don't check for them.
622 if sess.target.target.options.linker_is_gnu
623 && flavor != LinkerFlavor::Ld
624 && (out.contains("unrecognized command line option")
625 || out.contains("unknown argument"))
626 && out.contains("-no-pie")
627 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
629 info!("linker output: {:?}", out);
630 warn!("Linker does not support -no-pie command line option. Retrying without.");
631 for arg in cmd.take_args() {
632 if arg.to_string_lossy() != "-no-pie" {
640 // Here's a terribly awful hack that really shouldn't be present in any
641 // compiler. Here an environment variable is supported to automatically
642 // retry the linker invocation if the linker looks like it segfaulted.
644 // Gee that seems odd, normally segfaults are things we want to know
645 // about! Unfortunately though in rust-lang/rust#38878 we're
646 // experiencing the linker segfaulting on Travis quite a bit which is
647 // causing quite a bit of pain to land PRs when they spuriously fail
648 // due to a segfault.
650 // The issue #38878 has some more debugging information on it as well,
651 // but this unfortunately looks like it's just a race condition in
652 // macOS's linker with some thread pool working in the background. It
653 // seems that no one currently knows a fix for this so in the meantime
654 // we're left with this...
655 if !retry_on_segfault || i > 3 {
658 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
659 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
660 if out.contains(msg_segv) || out.contains(msg_bus) {
662 "looks like the linker segfaulted when we tried to call it, \
663 automatically retrying again. cmd = {:?}, out = {}.",
669 if is_illegal_instruction(&output.status) {
671 "looks like the linker hit an illegal instruction when we \
672 tried to call it, automatically retrying again. cmd = {:?}, ]\
673 out = {}, status = {}.",
674 cmd, out, output.status,
680 fn is_illegal_instruction(status: &ExitStatus) -> bool {
681 use std::os::unix::prelude::*;
682 status.signal() == Some(libc::SIGILL)
686 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
693 fn escape_string(s: &[u8]) -> String {
694 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
695 let mut x = "Non-UTF-8 output: ".to_string();
696 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
700 if !prog.status.success() {
701 let mut output = prog.stderr.clone();
702 output.extend_from_slice(&prog.stdout);
703 sess.struct_err(&format!(
704 "linking with `{}` failed: {}",
708 .note(&format!("{:?}", &cmd))
709 .note(&escape_string(&output))
711 sess.abort_if_errors();
713 info!("linker stderr:\n{}", escape_string(&prog.stderr));
714 info!("linker stdout:\n{}", escape_string(&prog.stdout));
717 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
719 let mut linker_error = {
720 if linker_not_found {
721 sess.struct_err(&format!("linker `{}` not found", pname.display()))
723 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
727 linker_error.note(&e.to_string());
729 if !linker_not_found {
730 linker_error.note(&format!("{:?}", &cmd));
735 if sess.target.target.options.is_like_msvc && linker_not_found {
736 sess.note_without_error(
737 "the msvc targets depend on the msvc linker \
738 but `link.exe` was not found",
740 sess.note_without_error(
741 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
742 was installed with the Visual C++ option",
745 sess.abort_if_errors();
749 // On macOS, debuggers need this utility to get run to do some munging of
750 // the symbols. Note, though, that if the object files are being preserved
751 // for their debug information there's no need for us to run dsymutil.
752 if sess.target.target.options.is_like_osx
753 && sess.opts.debuginfo != DebugInfo::None
754 && !preserve_objects_for_their_debuginfo(sess)
756 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
757 sess.fatal(&format!("failed to run dsymutil: {}", e))
762 fn link_sanitizer_runtime(sess: &Session, crate_type: config::CrateType, linker: &mut dyn Linker) {
763 let sanitizer = match &sess.opts.debugging_opts.sanitizer {
768 if crate_type != config::CrateType::Executable {
772 let name = match sanitizer {
773 Sanitizer::Address => "asan",
774 Sanitizer::Leak => "lsan",
775 Sanitizer::Memory => "msan",
776 Sanitizer::Thread => "tsan",
779 let default_sysroot = filesearch::get_or_default_sysroot();
781 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
782 let channel = option_env!("CFG_RELEASE_CHANNEL")
783 .map(|channel| format!("-{}", channel))
784 .unwrap_or_default();
786 match sess.opts.target_triple.triple() {
787 "x86_64-apple-darwin" => {
788 // On Apple platforms, the sanitizer is always built as a dylib, and
789 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
790 // rpath to the library as well (the rpath should be absolute, see
791 // PR #41352 for details).
792 let libname = format!("rustc{}_rt.{}", channel, name);
793 let rpath = default_tlib.to_str().expect("non-utf8 component in path");
794 linker.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
795 linker.link_dylib(Symbol::intern(&libname));
797 "x86_64-unknown-linux-gnu" | "x86_64-fuchsia" | "aarch64-fuchsia" => {
798 let filename = format!("librustc{}_rt.{}.a", channel, name);
799 let path = default_tlib.join(&filename);
800 linker.link_whole_rlib(&path);
806 /// Returns a boolean indicating whether the specified crate should be ignored
809 /// Crates ignored during LTO are not lumped together in the "massive object
810 /// file" that we create and are linked in their normal rlib states. See
811 /// comments below for what crates do not participate in LTO.
813 /// It's unusual for a crate to not participate in LTO. Typically only
814 /// compiler-specific and unstable crates have a reason to not participate in
816 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
817 // If our target enables builtin function lowering in LLVM then the
818 // crates providing these functions don't participate in LTO (e.g.
819 // no_builtins or compiler builtins crates).
820 !sess.target.target.options.no_builtins
821 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
824 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
827 linker: Option<PathBuf>,
828 flavor: Option<LinkerFlavor>,
829 ) -> Option<(PathBuf, LinkerFlavor)> {
830 match (linker, flavor) {
831 (Some(linker), Some(flavor)) => Some((linker, flavor)),
832 // only the linker flavor is known; use the default linker for the selected flavor
833 (None, Some(flavor)) => Some((
834 PathBuf::from(match flavor {
835 LinkerFlavor::Em => {
842 LinkerFlavor::Gcc => "cc",
843 LinkerFlavor::Ld => "ld",
844 LinkerFlavor::Msvc => "link.exe",
845 LinkerFlavor::Lld(_) => "lld",
846 LinkerFlavor::PtxLinker => "rust-ptx-linker",
850 (Some(linker), None) => {
851 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
852 sess.fatal("couldn't extract file stem from specified linker")
855 let flavor = if stem == "emcc" {
857 } else if stem == "gcc"
858 || stem.ends_with("-gcc")
860 || stem.ends_with("-clang")
863 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
865 } else if stem == "link" || stem == "lld-link" {
867 } else if stem == "lld" || stem == "rust-lld" {
868 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
870 // fall back to the value in the target spec
871 sess.target.target.linker_flavor
874 Some((linker, flavor))
876 (None, None) => None,
880 // linker and linker flavor specified via command line have precedence over what the target
881 // specification specifies
882 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
886 if let Some(ret) = infer_from(
888 sess.target.target.options.linker.clone().map(PathBuf::from),
889 Some(sess.target.target.linker_flavor),
894 bug!("Not enough information provided to determine how to invoke the linker");
897 /// Returns a boolean indicating whether we should preserve the object files on
898 /// the filesystem for their debug information. This is often useful with
899 /// split-dwarf like schemes.
900 pub fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
901 // If the objects don't have debuginfo there's nothing to preserve.
902 if sess.opts.debuginfo == config::DebugInfo::None {
906 // If we're only producing artifacts that are archives, no need to preserve
907 // the objects as they're losslessly contained inside the archives.
908 let output_linked = sess
912 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
917 // If we're on OSX then the equivalent of split dwarf is turned on by
918 // default. The final executable won't actually have any debug information
919 // except it'll have pointers to elsewhere. Historically we've always run
920 // `dsymutil` to "link all the dwarf together" but this is actually sort of
921 // a bummer for incremental compilation! (the whole point of split dwarf is
922 // that you don't do this sort of dwarf link).
924 // Basically as a result this just means that if we're on OSX and we're
925 // *not* running dsymutil then the object files are the only source of truth
926 // for debug information, so we must preserve them.
927 if sess.target.target.options.is_like_osx {
928 match sess.opts.debugging_opts.run_dsymutil {
929 // dsymutil is not being run, preserve objects
930 Some(false) => return true,
932 // dsymutil is being run, no need to preserve the objects
933 Some(true) => return false,
935 // The default historical behavior was to always run dsymutil, so
936 // we're preserving that temporarily, but we're likely to switch the
938 None => return false,
945 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
946 sess.target_filesearch(PathKind::Native).search_path_dirs()
954 pub fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
955 let lib_args: Vec<_> = all_native_libs
957 .filter(|l| relevant_lib(sess, l))
959 let name = lib.name?;
961 NativeLibraryKind::NativeStaticNobundle | NativeLibraryKind::NativeUnknown => {
962 if sess.target.target.options.is_like_msvc {
963 Some(format!("{}.lib", name))
965 Some(format!("-l{}", name))
968 NativeLibraryKind::NativeFramework => {
969 // ld-only syntax, since there are no frameworks in MSVC
970 Some(format!("-framework {}", name))
972 // These are included, no need to print them
973 NativeLibraryKind::NativeStatic | NativeLibraryKind::NativeRawDylib => None,
977 if !lib_args.is_empty() {
978 sess.note_without_error(
979 "Link against the following native artifacts when linking \
980 against this static library. The order and any duplication \
981 can be significant on some platforms.",
983 // Prefix for greppability
984 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
988 // Because windows-gnu target is meant to be self-contained for pure Rust code it bundles
989 // own mingw-w64 libraries. These libraries are usually not compatible with mingw-w64
990 // installed in the system. This breaks many cases where Rust is mixed with other languages
991 // (e.g. *-sys crates).
992 // We prefer system mingw-w64 libraries if they are available to avoid this issue.
993 fn get_crt_libs_path(sess: &Session) -> Option<PathBuf> {
994 fn find_exe_in_path<P>(exe_name: P) -> Option<PathBuf>
998 for dir in env::split_paths(&env::var_os("PATH")?) {
999 let full_path = dir.join(&exe_name);
1000 if full_path.is_file() {
1001 return Some(fix_windows_verbatim_for_gcc(&full_path));
1007 fn probe(sess: &Session) -> Option<PathBuf> {
1008 if let (linker, LinkerFlavor::Gcc) = linker_and_flavor(&sess) {
1009 let linker_path = if cfg!(windows) && linker.extension().is_none() {
1010 linker.with_extension("exe")
1014 if let Some(linker_path) = find_exe_in_path(linker_path) {
1015 let mingw_arch = match &sess.target.target.arch {
1016 x if x == "x86" => "i686",
1019 let mingw_bits = &sess.target.target.target_pointer_width;
1020 let mingw_dir = format!("{}-w64-mingw32", mingw_arch);
1021 // Here we have path/bin/gcc but we need path/
1022 let mut path = linker_path;
1025 // Loosely based on Clang MinGW driver
1026 let probe_paths = vec![
1027 path.join(&mingw_dir).join("lib"), // Typical path
1028 path.join(&mingw_dir).join("sys-root/mingw/lib"), // Rare path
1030 "lib/mingw/tools/install/mingw{}/{}/lib",
1031 &mingw_bits, &mingw_dir
1032 )), // Chocolatey is creative
1034 for probe_path in probe_paths {
1035 if probe_path.join("crt2.o").exists() {
1036 return Some(probe_path);
1044 let mut system_library_path = sess.system_library_path.borrow_mut();
1045 match &*system_library_path {
1046 Some(Some(compiler_libs_path)) => Some(compiler_libs_path.clone()),
1049 let path = probe(sess);
1050 *system_library_path = Some(path.clone());
1056 pub fn get_file_path(sess: &Session, name: &str) -> PathBuf {
1057 // prefer system {,dll}crt2.o libs, see get_crt_libs_path comment for more details
1058 if sess.target.target.llvm_target.contains("windows-gnu") {
1059 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1060 let file_path = compiler_libs_path.join(name);
1061 if file_path.exists() {
1066 let fs = sess.target_filesearch(PathKind::Native);
1067 let file_path = fs.get_lib_path().join(name);
1068 if file_path.exists() {
1071 for search_path in fs.search_paths() {
1072 let file_path = search_path.dir.join(name);
1073 if file_path.exists() {
1083 out_filename: &Path,
1085 ) -> io::Result<Output> {
1086 // When attempting to spawn the linker we run a risk of blowing out the
1087 // size limits for spawning a new process with respect to the arguments
1088 // we pass on the command line.
1090 // Here we attempt to handle errors from the OS saying "your list of
1091 // arguments is too big" by reinvoking the linker again with an `@`-file
1092 // that contains all the arguments. The theory is that this is then
1093 // accepted on all linkers and the linker will read all its options out of
1094 // there instead of looking at the command line.
1095 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1096 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1098 let output = child.wait_with_output();
1099 flush_linked_file(&output, out_filename)?;
1102 Err(ref e) if command_line_too_big(e) => {
1103 info!("command line to linker was too big: {}", e);
1105 Err(e) => return Err(e),
1109 info!("falling back to passing arguments to linker via an @-file");
1110 let mut cmd2 = cmd.clone();
1111 let mut args = String::new();
1112 for arg in cmd2.take_args() {
1115 arg: arg.to_str().unwrap(),
1116 is_like_msvc: sess.target.target.options.is_like_msvc,
1120 args.push_str("\n");
1122 let file = tmpdir.join("linker-arguments");
1123 let bytes = if sess.target.target.options.is_like_msvc {
1124 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1125 // start the stream with a UTF-16 BOM
1126 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1127 // encode in little endian
1129 out.push((c >> 8) as u8);
1135 fs::write(&file, &bytes)?;
1136 cmd2.arg(format!("@{}", file.display()));
1137 info!("invoking linker {:?}", cmd2);
1138 let output = cmd2.output();
1139 flush_linked_file(&output, out_filename)?;
1143 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1148 fn flush_linked_file(
1149 command_output: &io::Result<Output>,
1150 out_filename: &Path,
1151 ) -> io::Result<()> {
1152 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1153 // even long after process exit, causing nasty, non-reproducible output bugs.
1155 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1157 // А full writeup of the original Chrome bug can be found at
1158 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1160 if let &Ok(ref out) = command_output {
1161 if out.status.success() {
1162 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1172 fn command_line_too_big(err: &io::Error) -> bool {
1173 err.raw_os_error() == Some(::libc::E2BIG)
1177 fn command_line_too_big(err: &io::Error) -> bool {
1178 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1179 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1187 impl<'a> fmt::Display for Escape<'a> {
1188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 if self.is_like_msvc {
1190 // This is "documented" at
1191 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1193 // Unfortunately there's not a great specification of the
1194 // syntax I could find online (at least) but some local
1195 // testing showed that this seemed sufficient-ish to catch
1196 // at least a few edge cases.
1198 for c in self.arg.chars() {
1200 '"' => write!(f, "\\{}", c)?,
1201 c => write!(f, "{}", c)?,
1206 // This is documented at https://linux.die.net/man/1/ld, namely:
1208 // > Options in file are separated by whitespace. A whitespace
1209 // > character may be included in an option by surrounding the
1210 // > entire option in either single or double quotes. Any
1211 // > character (including a backslash) may be included by
1212 // > prefixing the character to be included with a backslash.
1214 // We put an argument on each line, so all we need to do is
1215 // ensure the line is interpreted as one whole argument.
1216 for c in self.arg.chars() {
1218 '\\' | ' ' => write!(f, "\\{}", c)?,
1219 c => write!(f, "{}", c)?,
1228 fn link_args<'a, B: ArchiveBuilder<'a>>(
1229 cmd: &mut dyn Linker,
1230 flavor: LinkerFlavor,
1232 crate_type: config::CrateType,
1234 out_filename: &Path,
1235 codegen_results: &CodegenResults,
1237 // Linker plugins should be specified early in the list of arguments
1238 cmd.linker_plugin_lto();
1240 // The default library location, we need this to find the runtime.
1241 // The location of crates will be determined as needed.
1242 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1244 // target descriptor
1245 let t = &sess.target.target;
1247 // prefer system mingw-w64 libs, see get_crt_libs_path comment for more details
1248 if cfg!(windows) && sess.target.target.llvm_target.contains("windows-gnu") {
1249 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1250 cmd.include_path(&compiler_libs_path);
1254 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1256 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1257 cmd.add_object(obj);
1259 cmd.output_filename(out_filename);
1261 if crate_type == config::CrateType::Executable && sess.target.target.options.is_like_windows {
1262 if let Some(ref s) = codegen_results.windows_subsystem {
1267 // If we're building something like a dynamic library then some platforms
1268 // need to make sure that all symbols are exported correctly from the
1270 cmd.export_symbols(tmpdir, crate_type);
1272 // When linking a dynamic library, we put the metadata into a section of the
1273 // executable. This metadata is in a separate object file from the main
1274 // object file, so we link that in here.
1275 if crate_type == config::CrateType::Dylib || crate_type == config::CrateType::ProcMacro {
1276 let obj = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref());
1277 if let Some(obj) = obj {
1278 cmd.add_object(obj);
1282 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
1283 if let Some(obj) = obj {
1284 cmd.add_object(obj);
1287 // Try to strip as much out of the generated object by removing unused
1288 // sections if possible. See more comments in linker.rs
1289 if !sess.opts.cg.link_dead_code {
1290 let keep_metadata = crate_type == config::CrateType::Dylib;
1291 cmd.gc_sections(keep_metadata);
1294 let used_link_args = &codegen_results.crate_info.link_args;
1296 if crate_type == config::CrateType::Executable {
1297 let mut position_independent_executable = false;
1299 if t.options.position_independent_executables {
1300 let empty_vec = Vec::new();
1301 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1302 let more_args = &sess.opts.cg.link_arg;
1303 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1305 if is_pic(sess) && !sess.crt_static() && !args.any(|x| *x == "-static") {
1306 position_independent_executable = true;
1310 if position_independent_executable {
1311 cmd.position_independent_executable();
1313 // recent versions of gcc can be configured to generate position
1314 // independent executables by default. We have to pass -no-pie to
1315 // explicitly turn that off. Not applicable to ld.
1316 if sess.target.target.options.linker_is_gnu && flavor != LinkerFlavor::Ld {
1317 cmd.no_position_independent_executable();
1322 let relro_level = match sess.opts.debugging_opts.relro_level {
1323 Some(level) => level,
1324 None => t.options.relro_level,
1327 RelroLevel::Full => {
1330 RelroLevel::Partial => {
1331 cmd.partial_relro();
1333 RelroLevel::Off => {
1336 RelroLevel::None => {}
1339 // Pass optimization flags down to the linker.
1342 // Pass debuginfo flags down to the linker.
1345 // We want to, by default, prevent the compiler from accidentally leaking in
1346 // any system libraries, so we may explicitly ask linkers to not link to any
1347 // libraries by default. Note that this does not happen for windows because
1348 // windows pulls in some large number of libraries and I couldn't quite
1349 // figure out which subset we wanted.
1351 // This is all naturally configurable via the standard methods as well.
1352 if !sess.opts.cg.default_linker_libraries.unwrap_or(false) && t.options.no_default_libraries {
1353 cmd.no_default_libraries();
1356 // Take careful note of the ordering of the arguments we pass to the linker
1357 // here. Linkers will assume that things on the left depend on things to the
1358 // right. Things on the right cannot depend on things on the left. This is
1359 // all formally implemented in terms of resolving symbols (libs on the right
1360 // resolve unknown symbols of libs on the left, but not vice versa).
1362 // For this reason, we have organized the arguments we pass to the linker as
1365 // 1. The local object that LLVM just generated
1366 // 2. Local native libraries
1367 // 3. Upstream rust libraries
1368 // 4. Upstream native libraries
1370 // The rationale behind this ordering is that those items lower down in the
1371 // list can't depend on items higher up in the list. For example nothing can
1372 // depend on what we just generated (e.g., that'd be a circular dependency).
1373 // Upstream rust libraries are not allowed to depend on our local native
1374 // libraries as that would violate the structure of the DAG, in that
1375 // scenario they are required to link to them as well in a shared fashion.
1377 // Note that upstream rust libraries may contain native dependencies as
1378 // well, but they also can't depend on what we just started to add to the
1379 // link line. And finally upstream native libraries can't depend on anything
1380 // in this DAG so far because they're only dylibs and dylibs can only depend
1381 // on other dylibs (e.g., other native deps).
1382 add_local_native_libraries(cmd, sess, codegen_results);
1383 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1384 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1386 // Tell the linker what we're doing.
1387 if crate_type != config::CrateType::Executable {
1388 cmd.build_dylib(out_filename);
1390 if crate_type == config::CrateType::Executable && sess.crt_static() {
1391 cmd.build_static_executable();
1394 if sess.opts.cg.profile_generate.enabled() {
1398 if sess.opts.debugging_opts.control_flow_guard != CFGuard::Disabled {
1399 cmd.control_flow_guard();
1402 // FIXME (#2397): At some point we want to rpath our guesses as to
1403 // where extern libraries might live, based on the
1404 // addl_lib_search_paths
1405 if sess.opts.cg.rpath {
1406 let target_triple = sess.opts.target_triple.triple();
1407 let mut get_install_prefix_lib_path = || {
1408 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1409 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1410 let mut path = PathBuf::from(install_prefix);
1415 let mut rpath_config = RPathConfig {
1416 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1417 out_filename: out_filename.to_path_buf(),
1418 has_rpath: sess.target.target.options.has_rpath,
1419 is_like_osx: sess.target.target.options.is_like_osx,
1420 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1421 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1423 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1426 // Finally add all the linker arguments provided on the command line along
1427 // with any #[link_args] attributes found inside the crate
1428 if let Some(ref args) = sess.opts.cg.link_args {
1431 cmd.args(&sess.opts.cg.link_arg);
1432 cmd.args(&used_link_args);
1435 // # Native library linking
1437 // User-supplied library search paths (-L on the command line). These are
1438 // the same paths used to find Rust crates, so some of them may have been
1439 // added already by the previous crate linking code. This only allows them
1440 // to be found at compile time so it is still entirely up to outside
1441 // forces to make sure that library can be found at runtime.
1443 // Also note that the native libraries linked here are only the ones located
1444 // in the current crate. Upstream crates with native library dependencies
1445 // may have their native library pulled in above.
1446 pub fn add_local_native_libraries(
1447 cmd: &mut dyn Linker,
1449 codegen_results: &CodegenResults,
1451 let filesearch = sess.target_filesearch(PathKind::All);
1452 for search_path in filesearch.search_paths() {
1453 match search_path.kind {
1454 PathKind::Framework => {
1455 cmd.framework_path(&search_path.dir);
1458 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1464 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1466 let search_path = archive_search_paths(sess);
1467 for lib in relevant_libs {
1468 let name = match lib.name {
1473 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1474 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1475 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(name),
1476 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(name, &search_path),
1477 NativeLibraryKind::NativeRawDylib => {
1478 // FIXME(#58713): Proper handling for raw dylibs.
1479 bug!("raw_dylib feature not yet implemented");
1485 // # Rust Crate linking
1487 // Rust crates are not considered at all when creating an rlib output. All
1488 // dependencies will be linked when producing the final output (instead of
1489 // the intermediate rlib version)
1490 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1491 cmd: &mut dyn Linker,
1493 codegen_results: &CodegenResults,
1494 crate_type: config::CrateType,
1497 // All of the heavy lifting has previously been accomplished by the
1498 // dependency_format module of the compiler. This is just crawling the
1499 // output of that module, adding crates as necessary.
1501 // Linking to a rlib involves just passing it to the linker (the linker
1502 // will slurp up the object files inside), and linking to a dynamic library
1503 // involves just passing the right -l flag.
1505 let (_, data) = codegen_results
1509 .find(|(ty, _)| *ty == crate_type)
1510 .expect("failed to find crate type in dependency format list");
1512 // Invoke get_used_crates to ensure that we get a topological sorting of
1514 let deps = &codegen_results.crate_info.used_crates_dynamic;
1516 // There's a few internal crates in the standard library (aka libcore and
1517 // libstd) which actually have a circular dependence upon one another. This
1518 // currently arises through "weak lang items" where libcore requires things
1519 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1520 // circular dependence to work correctly in all situations we'll need to be
1521 // sure to correctly apply the `--start-group` and `--end-group` options to
1522 // GNU linkers, otherwise if we don't use any other symbol from the standard
1523 // library it'll get discarded and the whole application won't link.
1525 // In this loop we're calculating the `group_end`, after which crate to
1526 // pass `--end-group` and `group_start`, before which crate to pass
1527 // `--start-group`. We currently do this by passing `--end-group` after
1528 // the first crate (when iterating backwards) that requires a lang item
1529 // defined somewhere else. Once that's set then when we've defined all the
1530 // necessary lang items we'll pass `--start-group`.
1532 // Note that this isn't amazing logic for now but it should do the trick
1533 // for the current implementation of the standard library.
1534 let mut group_end = None;
1535 let mut group_start = None;
1536 // Crates available for linking thus far.
1537 let mut available = FxHashSet::default();
1538 // Crates required to satisfy dependencies discovered so far.
1539 let mut required = FxHashSet::default();
1541 let info = &codegen_results.crate_info;
1542 for &(cnum, _) in deps.iter().rev() {
1543 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1544 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1545 required.extend(missing_crates);
1548 required.insert(Some(cnum));
1549 available.insert(Some(cnum));
1551 if required.len() > available.len() && group_end.is_none() {
1552 group_end = Some(cnum);
1554 if required.len() == available.len() && group_end.is_some() {
1555 group_start = Some(cnum);
1560 // If we didn't end up filling in all lang items from upstream crates then
1561 // we'll be filling it in with our crate. This probably means we're the
1562 // standard library itself, so skip this for now.
1563 if group_end.is_some() && group_start.is_none() {
1567 let mut compiler_builtins = None;
1569 for &(cnum, _) in deps.iter() {
1570 if group_start == Some(cnum) {
1574 // We may not pass all crates through to the linker. Some crates may
1575 // appear statically in an existing dylib, meaning we'll pick up all the
1576 // symbols from the dylib.
1577 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1578 match data[cnum.as_usize() - 1] {
1579 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1580 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1582 // compiler-builtins are always placed last to ensure that they're
1583 // linked correctly.
1584 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1585 assert!(compiler_builtins.is_none());
1586 compiler_builtins = Some(cnum);
1588 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1589 Linkage::Static => {
1590 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1592 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1595 if group_end == Some(cnum) {
1600 // compiler-builtins are always placed last to ensure that they're
1601 // linked correctly.
1602 // We must always link the `compiler_builtins` crate statically. Even if it
1603 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1605 if let Some(cnum) = compiler_builtins {
1606 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1609 // Converts a library file-stem into a cc -l argument
1610 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1611 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1618 // Adds the static "rlib" versions of all crates to the command line.
1619 // There's a bit of magic which happens here specifically related to LTO and
1620 // dynamic libraries. Specifically:
1622 // * For LTO, we remove upstream object files.
1623 // * For dylibs we remove metadata and bytecode from upstream rlibs
1625 // When performing LTO, almost(*) all of the bytecode from the upstream
1626 // libraries has already been included in our object file output. As a
1627 // result we need to remove the object files in the upstream libraries so
1628 // the linker doesn't try to include them twice (or whine about duplicate
1629 // symbols). We must continue to include the rest of the rlib, however, as
1630 // it may contain static native libraries which must be linked in.
1632 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1633 // their bytecode wasn't included. The object files in those libraries must
1634 // still be passed to the linker.
1636 // When making a dynamic library, linkers by default don't include any
1637 // object files in an archive if they're not necessary to resolve the link.
1638 // We basically want to convert the archive (rlib) to a dylib, though, so we
1639 // *do* want everything included in the output, regardless of whether the
1640 // linker thinks it's needed or not. As a result we must use the
1641 // --whole-archive option (or the platform equivalent). When using this
1642 // option the linker will fail if there are non-objects in the archive (such
1643 // as our own metadata and/or bytecode). All in all, for rlibs to be
1644 // entirely included in dylibs, we need to remove all non-object files.
1646 // Note, however, that if we're not doing LTO or we're not producing a dylib
1647 // (aka we're making an executable), we can just pass the rlib blindly to
1648 // the linker (fast) because it's fine if it's not actually included as
1649 // we're at the end of the dependency chain.
1650 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1651 cmd: &mut dyn Linker,
1653 codegen_results: &CodegenResults,
1655 crate_type: config::CrateType,
1658 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1659 let cratepath = &src.rlib.as_ref().unwrap().0;
1661 // See the comment above in `link_staticlib` and `link_rlib` for why if
1662 // there's a static library that's not relevant we skip all object
1664 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1665 let skip_native = native_libs
1667 .any(|lib| lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib));
1669 if (!are_upstream_rust_objects_already_included(sess)
1670 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1671 && crate_type != config::CrateType::Dylib
1674 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1678 let dst = tmpdir.join(cratepath.file_name().unwrap());
1679 let name = cratepath.file_name().unwrap().to_str().unwrap();
1680 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1682 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1683 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1684 archive.update_symbols();
1686 let mut any_objects = false;
1687 for f in archive.src_files() {
1688 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1689 archive.remove_file(&f);
1693 let canonical = f.replace("-", "_");
1694 let canonical_name = name.replace("-", "_");
1696 let is_rust_object =
1697 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
1699 // If we've been requested to skip all native object files
1700 // (those not generated by the rust compiler) then we can skip
1701 // this file. See above for why we may want to do this.
1702 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1704 // If we're performing LTO and this is a rust-generated object
1705 // file, then we don't need the object file as it's part of the
1706 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1707 // though, so we let that object file slide.
1708 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
1710 && (sess.target.target.options.no_builtins
1711 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1713 if skip_because_cfg_say_so || skip_because_lto {
1714 archive.remove_file(&f);
1725 // If we're creating a dylib, then we need to include the
1726 // whole of each object in our archive into that artifact. This is
1727 // because a `dylib` can be reused as an intermediate artifact.
1729 // Note, though, that we don't want to include the whole of a
1730 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1731 // repeatedly linked anyway.
1732 if crate_type == config::CrateType::Dylib
1733 && codegen_results.crate_info.compiler_builtins != Some(cnum)
1735 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1737 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1742 // Same thing as above, but for dynamic crates instead of static crates.
1743 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1744 // Just need to tell the linker about where the library lives and
1746 let parent = cratepath.parent();
1747 if let Some(dir) = parent {
1748 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1750 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1751 cmd.link_rust_dylib(
1752 Symbol::intern(&unlib(&sess.target, filestem)),
1753 parent.unwrap_or(Path::new("")),
1758 // Link in all of our upstream crates' native dependencies. Remember that
1759 // all of these upstream native dependencies are all non-static
1760 // dependencies. We've got two cases then:
1762 // 1. The upstream crate is an rlib. In this case we *must* link in the
1763 // native dependency because the rlib is just an archive.
1765 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1766 // have the dependency present on the system somewhere. Thus, we don't
1767 // gain a whole lot from not linking in the dynamic dependency to this
1770 // The use case for this is a little subtle. In theory the native
1771 // dependencies of a crate are purely an implementation detail of the crate
1772 // itself, but the problem arises with generic and inlined functions. If a
1773 // generic function calls a native function, then the generic function must
1774 // be instantiated in the target crate, meaning that the native symbol must
1775 // also be resolved in the target crate.
1776 pub fn add_upstream_native_libraries(
1777 cmd: &mut dyn Linker,
1779 codegen_results: &CodegenResults,
1780 crate_type: config::CrateType,
1782 // Be sure to use a topological sorting of crates because there may be
1783 // interdependencies between native libraries. When passing -nodefaultlibs,
1784 // for example, almost all native libraries depend on libc, so we have to
1785 // make sure that's all the way at the right (liblibc is near the base of
1786 // the dependency chain).
1788 // This passes RequireStatic, but the actual requirement doesn't matter,
1789 // we're just getting an ordering of crate numbers, we're not worried about
1791 let (_, data) = codegen_results
1795 .find(|(ty, _)| *ty == crate_type)
1796 .expect("failed to find crate type in dependency format list");
1798 let crates = &codegen_results.crate_info.used_crates_static;
1799 for &(cnum, _) in crates {
1800 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1801 let name = match lib.name {
1805 if !relevant_lib(sess, &lib) {
1809 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1810 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1811 NativeLibraryKind::NativeStaticNobundle => {
1812 // Link "static-nobundle" native libs only if the crate they originate from
1813 // is being linked statically to the current crate. If it's linked dynamically
1814 // or is an rlib already included via some other dylib crate, the symbols from
1815 // native libs will have already been included in that dylib.
1816 if data[cnum.as_usize() - 1] == Linkage::Static {
1817 cmd.link_staticlib(name)
1820 // ignore statically included native libraries here as we've
1821 // already included them when we included the rust library
1823 NativeLibraryKind::NativeStatic => {}
1824 NativeLibraryKind::NativeRawDylib => {
1825 // FIXME(#58713): Proper handling for raw dylibs.
1826 bug!("raw_dylib feature not yet implemented");
1833 pub fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1835 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
1840 pub fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1842 config::Lto::Fat => true,
1843 config::Lto::Thin => {
1844 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1845 // any upstream object files have not been copied yet.
1846 !sess.opts.cg.linker_plugin_lto.enabled()
1848 config::Lto::No | config::Lto::ThinLocal => false,
1852 fn is_pic(sess: &Session) -> bool {
1853 let reloc_model_arg = match sess.opts.cg.relocation_model {
1854 Some(ref s) => &s[..],
1855 None => &sess.target.target.options.relocation_model[..],
1858 reloc_model_arg == "pic"