1 /// For all the linkers we support, and information they might
2 /// need out of the shared crate context before we get rid of it.
4 use rustc::session::{Session, filesearch};
5 use rustc::session::config::{
6 self, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer
8 use rustc::session::search_paths::PathKind;
9 use rustc::middle::dependency_format::Linkage;
10 use rustc::middle::cstore::{EncodedMetadata, LibSource, NativeLibrary, NativeLibraryKind};
11 use rustc::util::common::{time, time_ext};
12 use rustc::hir::def_id::CrateNum;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_fs_util::fix_windows_verbatim_for_gcc;
15 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor};
16 use syntax::symbol::Symbol;
18 use crate::{METADATA_FILENAME, RLIB_BYTECODE_EXTENSION, CrateInfo,
19 looks_like_rust_object_file, CodegenResults};
20 use super::archive::ArchiveBuilder;
21 use super::command::Command;
22 use super::linker::Linker;
23 use super::rpath::{self, RPathConfig};
25 use cc::windows_registry;
26 use tempfile::{Builder as TempFileBuilder, TempDir};
33 use std::path::{Path, PathBuf};
34 use std::process::{Output, Stdio, ExitStatus};
37 use std::ffi::OsString;
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 {}: {}",
49 /// Performs the linkage portion of the compilation phase. This will generate all
50 /// of the requested outputs for this compilation session.
51 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
52 codegen_results: &CodegenResults,
53 outputs: &OutputFilenames,
56 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
57 for &crate_type in sess.crate_types.borrow().iter() {
58 // Ignore executable crates if we have -Z no-codegen, as they will error.
59 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen()) &&
61 crate_type == config::CrateType::Executable {
65 if invalid_output_for_target(sess, crate_type) {
66 bug!("invalid output type `{:?}` for target os `{}`",
67 crate_type, sess.opts.target_triple);
70 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
71 check_file_is_writeable(obj, sess);
74 let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err|
75 sess.fatal(&format!("couldn't create a temp dir: {}", err)));
77 if outputs.outputs.should_codegen() {
78 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
80 config::CrateType::Rlib => {
87 config::CrateType::Staticlib => {
88 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
101 if sess.opts.json_artifact_notifications {
102 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
106 if sess.opts.cg.save_temps {
107 let _ = tmpdir.into_path();
111 // Remove the temporary object file and metadata if we aren't saving temps
112 if !sess.opts.cg.save_temps {
113 if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) {
114 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
118 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
121 if let Some(ref metadata_module) = codegen_results.metadata_module {
122 if let Some(ref obj) = metadata_module.object {
126 if let Some(ref allocator_module) = codegen_results.allocator_module {
127 if let Some(ref obj) = allocator_module.object {
130 if let Some(ref bc) = allocator_module.bytecode_compressed {
137 // The third parameter is for env vars, used on windows to set up the
138 // path for MSVC to find its DLLs, and gcc to find its bundled
140 pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
141 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
143 // If our linker looks like a batch script on Windows then to execute this
144 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
145 // emscripten where the linker is `emcc.bat` and needs to be spawned as
146 // `cmd /c emcc.bat ...`.
148 // This worked historically but is needed manually since #42436 (regression
149 // was tagged as #42791) and some more info can be found on #44443 for
150 // emscripten itself.
151 let mut cmd = match linker.to_str() {
152 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
154 LinkerFlavor::Lld(f) => Command::lld(linker, f),
156 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
158 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
160 _ => Command::new(linker),
164 // UWP apps have API restrictions enforced during Store submissions.
165 // To comply with the Windows App Certification Kit,
166 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
167 let t = &sess.target.target;
168 if flavor == LinkerFlavor::Msvc && t.target_vendor == "uwp" {
169 if let Some(ref tool) = msvc_tool {
170 let original_path = tool.path();
171 if let Some(ref root_lib_path) = original_path.ancestors().skip(4).next() {
172 let arch = match t.arch.as_str() {
173 "x86_64" => Some("x64".to_string()),
174 "x86" => Some("x86".to_string()),
175 "aarch64" => Some("arm64".to_string()),
178 if let Some(ref a) = arch {
179 let mut arg = OsString::from("/LIBPATH:");
180 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
184 warn!("arch is not supported");
187 warn!("MSVC root path lib location not found");
190 warn!("link.exe not found");
194 // The compiler's sysroot often has some bundled tools, so add it to the
195 // PATH for the child.
196 let mut new_path = sess.host_filesearch(PathKind::All)
197 .get_tools_search_paths();
198 let mut msvc_changed_path = false;
199 if sess.target.target.options.is_like_msvc {
200 if let Some(ref tool) = msvc_tool {
201 cmd.args(tool.args());
202 for &(ref k, ref v) in tool.env() {
204 new_path.extend(env::split_paths(v));
205 msvc_changed_path = true;
213 if !msvc_changed_path {
214 if let Some(path) = env::var_os("PATH") {
215 new_path.extend(env::split_paths(&path));
218 cmd.env("PATH", env::join_paths(new_path).unwrap());
220 (linker.to_path_buf(), cmd)
223 pub fn each_linked_rlib(
225 f: &mut dyn FnMut(CrateNum, &Path),
226 ) -> Result<(), String> {
227 let crates = info.used_crates_static.iter();
229 for (ty, list) in info.dependency_formats.iter() {
231 config::CrateType::Executable |
232 config::CrateType::Staticlib |
233 config::CrateType::Cdylib |
234 config::CrateType::ProcMacro => {
241 let fmts = match fmts {
243 None => return Err("could not find formats for rlibs".to_string())
245 for &(cnum, ref path) in crates {
246 match fmts.get(cnum.as_usize() - 1) {
247 Some(&Linkage::NotLinked) |
248 Some(&Linkage::IncludedFromDylib) => continue,
250 None => return Err("could not find formats for rlibs".to_string())
252 let name = &info.crate_name[&cnum];
253 let path = match *path {
254 LibSource::Some(ref p) => p,
255 LibSource::MetadataOnly => {
256 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
260 return Err(format!("could not find rlib for: `{}`", name))
268 /// We use a temp directory here to avoid races between concurrent rustc processes,
269 /// such as builds in the same directory using the same filename for metadata while
270 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
271 /// directory being searched for `extern crate` (observing an incomplete file).
272 /// The returned path is the temporary file containing the complete metadata.
273 pub fn emit_metadata<'a>(
275 metadata: &EncodedMetadata,
278 let out_filename = tmpdir.path().join(METADATA_FILENAME);
279 let result = fs::write(&out_filename, &metadata.raw_data);
281 if let Err(e) = result {
282 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
290 // An rlib in its current incarnation is essentially a renamed .a file. The
291 // rlib primarily contains the object file of the crate, but it also contains
292 // all of the object files from native libraries. This is done by unzipping
293 // native libraries and inserting all of the contents into this archive.
294 fn link_rlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
295 codegen_results: &CodegenResults,
298 tmpdir: &TempDir) -> B {
299 info!("preparing rlib to {:?}", out_filename);
300 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
302 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
306 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
307 // we may not be configured to actually include a static library if we're
308 // adding it here. That's because later when we consume this rlib we'll
309 // decide whether we actually needed the static library or not.
311 // To do this "correctly" we'd need to keep track of which libraries added
312 // which object files to the archive. We don't do that here, however. The
313 // #[link(cfg(..))] feature is unstable, though, and only intended to get
314 // liblibc working. In that sense the check below just indicates that if
315 // there are any libraries we want to omit object files for at link time we
316 // just exclude all custom object files.
318 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
319 // feature then we'll need to figure out how to record what objects were
320 // loaded from the libraries found here and then encode that into the
321 // metadata of the rlib we're generating somehow.
322 for lib in codegen_results.crate_info.used_libraries.iter() {
324 NativeLibraryKind::NativeStatic => {}
325 NativeLibraryKind::NativeStaticNobundle |
326 NativeLibraryKind::NativeFramework |
327 NativeLibraryKind::NativeRawDylib |
328 NativeLibraryKind::NativeUnknown => continue,
330 if let Some(name) = lib.name {
331 ab.add_native_library(name);
335 // After adding all files to the archive, we need to update the
336 // symbol table of the archive.
339 // Note that it is important that we add all of our non-object "magical
340 // files" *after* all of the object files in the archive. The reason for
341 // this is as follows:
343 // * When performing LTO, this archive will be modified to remove
344 // objects from above. The reason for this is described below.
346 // * When the system linker looks at an archive, it will attempt to
347 // determine the architecture of the archive in order to see whether its
350 // The algorithm for this detection is: iterate over the files in the
351 // archive. Skip magical SYMDEF names. Interpret the first file as an
352 // object file. Read architecture from the object file.
354 // * As one can probably see, if "metadata" and "foo.bc" were placed
355 // before all of the objects, then the architecture of this archive would
356 // not be correctly inferred once 'foo.o' is removed.
358 // Basically, all this means is that this code should not move above the
361 RlibFlavor::Normal => {
362 // Instead of putting the metadata in an object file section, rlibs
363 // contain the metadata in a separate file.
364 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
366 // For LTO purposes, the bytecode of this library is also inserted
368 for bytecode in codegen_results
371 .filter_map(|m| m.bytecode_compressed.as_ref())
373 ab.add_file(bytecode);
376 // After adding all files to the archive, we need to update the
377 // symbol table of the archive. This currently dies on macOS (see
378 // #11162), and isn't necessary there anyway
379 if !sess.target.target.options.is_like_osx {
384 RlibFlavor::StaticlibBase => {
385 let obj = codegen_results.allocator_module
387 .and_then(|m| m.object.as_ref());
388 if let Some(obj) = obj {
397 // Create a static archive
399 // This is essentially the same thing as an rlib, but it also involves adding
400 // all of the upstream crates' objects into the archive. This will slurp in
401 // all of the native libraries of upstream dependencies as well.
403 // Additionally, there's no way for us to link dynamic libraries, so we warn
404 // about all dynamic library dependencies that they're not linked in.
406 // There's no need to include metadata in a static archive, so ensure to not
407 // link in the metadata object file (and also don't prepare the archive with a
409 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
410 codegen_results: &CodegenResults,
413 let mut ab = link_rlib::<B>(sess,
415 RlibFlavor::StaticlibBase,
418 let mut all_native_libs = vec![];
420 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
421 let name = &codegen_results.crate_info.crate_name[&cnum];
422 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
424 // Here when we include the rlib into our staticlib we need to make a
425 // decision whether to include the extra object files along the way.
426 // These extra object files come from statically included native
427 // libraries, but they may be cfg'd away with #[link(cfg(..))].
429 // This unstable feature, though, only needs liblibc to work. The only
430 // use case there is where musl is statically included in liblibc.rlib,
431 // so if we don't want the included version we just need to skip it. As
432 // a result the logic here is that if *any* linked library is cfg'd away
433 // we just skip all object files.
435 // Clearly this is not sufficient for a general purpose feature, and
436 // we'd want to read from the library's metadata to determine which
437 // object files come from where and selectively skip them.
438 let skip_object_files = native_libs.iter().any(|lib| {
439 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
443 are_upstream_rust_objects_already_included(sess) &&
444 !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
445 skip_object_files).unwrap();
447 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
449 if let Err(e) = res {
456 if !all_native_libs.is_empty() {
457 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
458 print_native_static_libs(sess, &all_native_libs);
463 // Create a dynamic library or executable
465 // This will invoke the system linker/cc to create the resulting file. This
466 // links to all upstream files as well.
467 fn link_natively<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
468 crate_type: config::CrateType,
470 codegen_results: &CodegenResults,
473 info!("preparing {:?} to {:?}", crate_type, out_filename);
474 let (linker, flavor) = linker_and_flavor(sess);
476 // The invocations of cc share some flags across platforms
477 let (pname, mut cmd) = get_linker(sess, &linker, flavor);
479 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
482 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
483 if sess.crt_static() {
487 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
490 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
492 if sess.target.target.options.is_like_fuchsia {
493 let prefix = match sess.opts.debugging_opts.sanitizer {
494 Some(Sanitizer::Address) => "asan/",
497 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
500 let pre_link_objects = if crate_type == config::CrateType::Executable {
501 &sess.target.target.options.pre_link_objects_exe
503 &sess.target.target.options.pre_link_objects_dll
505 for obj in pre_link_objects {
506 cmd.arg(get_file_path(sess, obj));
509 if crate_type == config::CrateType::Executable && sess.crt_static() {
510 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
511 cmd.arg(get_file_path(sess, obj));
515 if sess.target.target.options.is_like_emscripten {
517 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
518 "DISABLE_EXCEPTION_CATCHING=1"
520 "DISABLE_EXCEPTION_CATCHING=0"
525 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
526 link_args::<B>(&mut *linker, flavor, sess, crate_type, tmpdir,
527 out_filename, codegen_results);
528 cmd = linker.finalize();
530 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
533 for obj in &sess.target.target.options.post_link_objects {
534 cmd.arg(get_file_path(sess, obj));
536 if sess.crt_static() {
537 for obj in &sess.target.target.options.post_link_objects_crt {
538 cmd.arg(get_file_path(sess, obj));
541 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
544 for &(ref k, ref v) in &sess.target.target.options.link_env {
547 for k in &sess.target.target.options.link_env_remove {
551 if sess.opts.debugging_opts.print_link_args {
552 println!("{:?}", &cmd);
555 // May have not found libraries in the right formats.
556 sess.abort_if_errors();
558 // Invoke the system linker
560 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
565 prog = time(sess, "running linker", || {
566 exec_linker(sess, &mut cmd, out_filename, tmpdir)
568 let output = match prog {
569 Ok(ref output) => output,
572 if output.status.success() {
575 let mut out = output.stderr.clone();
576 out.extend(&output.stdout);
577 let out = String::from_utf8_lossy(&out);
579 // Check to see if the link failed with "unrecognized command line option:
580 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
581 // reperform the link step without the -no-pie option. This is safe because
582 // if the linker doesn't support -no-pie then it should not default to
583 // linking executables as pie. Different versions of gcc seem to use
584 // different quotes in the error message so don't check for them.
585 if sess.target.target.options.linker_is_gnu &&
586 flavor != LinkerFlavor::Ld &&
587 (out.contains("unrecognized command line option") ||
588 out.contains("unknown argument")) &&
589 out.contains("-no-pie") &&
590 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
591 info!("linker output: {:?}", out);
592 warn!("Linker does not support -no-pie command line option. Retrying without.");
593 for arg in cmd.take_args() {
594 if arg.to_string_lossy() != "-no-pie" {
602 // Here's a terribly awful hack that really shouldn't be present in any
603 // compiler. Here an environment variable is supported to automatically
604 // retry the linker invocation if the linker looks like it segfaulted.
606 // Gee that seems odd, normally segfaults are things we want to know
607 // about! Unfortunately though in rust-lang/rust#38878 we're
608 // experiencing the linker segfaulting on Travis quite a bit which is
609 // causing quite a bit of pain to land PRs when they spuriously fail
610 // due to a segfault.
612 // The issue #38878 has some more debugging information on it as well,
613 // but this unfortunately looks like it's just a race condition in
614 // macOS's linker with some thread pool working in the background. It
615 // seems that no one currently knows a fix for this so in the meantime
616 // we're left with this...
617 if !retry_on_segfault || i > 3 {
620 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
621 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
622 if out.contains(msg_segv) || out.contains(msg_bus) {
624 "looks like the linker segfaulted when we tried to call it, \
625 automatically retrying again. cmd = {:?}, out = {}.",
632 if is_illegal_instruction(&output.status) {
634 "looks like the linker hit an illegal instruction when we \
635 tried to call it, automatically retrying again. cmd = {:?}, ]\
636 out = {}, status = {}.",
645 fn is_illegal_instruction(status: &ExitStatus) -> bool {
646 use std::os::unix::prelude::*;
647 status.signal() == Some(libc::SIGILL)
651 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
658 fn escape_string(s: &[u8]) -> String {
659 str::from_utf8(s).map(|s| s.to_owned())
660 .unwrap_or_else(|_| {
661 let mut x = "Non-UTF-8 output: ".to_string();
663 .flat_map(|&b| ascii::escape_default(b))
668 if !prog.status.success() {
669 let mut output = prog.stderr.clone();
670 output.extend_from_slice(&prog.stdout);
671 sess.struct_err(&format!("linking with `{}` failed: {}",
674 .note(&format!("{:?}", &cmd))
675 .note(&escape_string(&output))
677 sess.abort_if_errors();
679 info!("linker stderr:\n{}", escape_string(&prog.stderr));
680 info!("linker stdout:\n{}", escape_string(&prog.stdout));
683 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
685 let mut linker_error = {
686 if linker_not_found {
687 sess.struct_err(&format!("linker `{}` not found", pname.display()))
689 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
693 linker_error.note(&e.to_string());
695 if !linker_not_found {
696 linker_error.note(&format!("{:?}", &cmd));
701 if sess.target.target.options.is_like_msvc && linker_not_found {
702 sess.note_without_error(
703 "the msvc targets depend on the msvc linker \
704 but `link.exe` was not found",
706 sess.note_without_error(
707 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
708 was installed with the Visual C++ option",
711 sess.abort_if_errors();
716 // On macOS, debuggers need this utility to get run to do some munging of
717 // the symbols. Note, though, that if the object files are being preserved
718 // for their debug information there's no need for us to run dsymutil.
719 if sess.target.target.options.is_like_osx &&
720 sess.opts.debuginfo != DebugInfo::None &&
721 !preserve_objects_for_their_debuginfo(sess)
723 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
724 sess.fatal(&format!("failed to run dsymutil: {}", e))
729 /// Returns a boolean indicating whether the specified crate should be ignored
732 /// Crates ignored during LTO are not lumped together in the "massive object
733 /// file" that we create and are linked in their normal rlib states. See
734 /// comments below for what crates do not participate in LTO.
736 /// It's unusual for a crate to not participate in LTO. Typically only
737 /// compiler-specific and unstable crates have a reason to not participate in
739 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
740 // If our target enables builtin function lowering in LLVM then the
741 // crates providing these functions don't participate in LTO (e.g.
742 // no_builtins or compiler builtins crates).
743 !sess.target.target.options.no_builtins &&
744 (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
747 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
750 linker: Option<PathBuf>,
751 flavor: Option<LinkerFlavor>,
752 ) -> Option<(PathBuf, LinkerFlavor)> {
753 match (linker, flavor) {
754 (Some(linker), Some(flavor)) => Some((linker, flavor)),
755 // only the linker flavor is known; use the default linker for the selected flavor
756 (None, Some(flavor)) => Some((PathBuf::from(match flavor {
757 LinkerFlavor::Em => if cfg!(windows) { "emcc.bat" } else { "emcc" },
758 LinkerFlavor::Gcc => "cc",
759 LinkerFlavor::Ld => "ld",
760 LinkerFlavor::Msvc => "link.exe",
761 LinkerFlavor::Lld(_) => "lld",
762 LinkerFlavor::PtxLinker => "rust-ptx-linker",
764 (Some(linker), None) => {
767 .and_then(|stem| stem.to_str())
769 sess.fatal("couldn't extract file stem from specified linker")
772 let flavor = if stem == "emcc" {
774 } else if stem == "gcc"
775 || stem.ends_with("-gcc")
777 || stem.ends_with("-clang")
780 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
782 } else if stem == "link" || stem == "lld-link" {
784 } else if stem == "lld" || stem == "rust-lld" {
785 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
787 // fall back to the value in the target spec
788 sess.target.target.linker_flavor
791 Some((linker, flavor))
793 (None, None) => None,
797 // linker and linker flavor specified via command line have precedence over what the target
798 // specification specifies
799 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
803 if let Some(ret) = infer_from(
805 sess.target.target.options.linker.clone().map(PathBuf::from),
806 Some(sess.target.target.linker_flavor),
811 bug!("Not enough information provided to determine how to invoke the linker");
814 /// Returns a boolean indicating whether we should preserve the object files on
815 /// the filesystem for their debug information. This is often useful with
816 /// split-dwarf like schemes.
817 pub fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
818 // If the objects don't have debuginfo there's nothing to preserve.
819 if sess.opts.debuginfo == config::DebugInfo::None {
823 // If we're only producing artifacts that are archives, no need to preserve
824 // the objects as they're losslessly contained inside the archives.
825 let output_linked = sess.crate_types.borrow()
827 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
832 // If we're on OSX then the equivalent of split dwarf is turned on by
833 // default. The final executable won't actually have any debug information
834 // except it'll have pointers to elsewhere. Historically we've always run
835 // `dsymutil` to "link all the dwarf together" but this is actually sort of
836 // a bummer for incremental compilation! (the whole point of split dwarf is
837 // that you don't do this sort of dwarf link).
839 // Basically as a result this just means that if we're on OSX and we're
840 // *not* running dsymutil then the object files are the only source of truth
841 // for debug information, so we must preserve them.
842 if sess.target.target.options.is_like_osx {
843 match sess.opts.debugging_opts.run_dsymutil {
844 // dsymutil is not being run, preserve objects
845 Some(false) => return true,
847 // dsymutil is being run, no need to preserve the objects
848 Some(true) => return false,
850 // The default historical behavior was to always run dsymutil, so
851 // we're preserving that temporarily, but we're likely to switch the
853 None => return false,
860 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
861 sess.target_filesearch(PathKind::Native).search_path_dirs()
869 pub fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
870 let lib_args: Vec<_> = all_native_libs.iter()
871 .filter(|l| relevant_lib(sess, l))
873 let name = lib.name?;
875 NativeLibraryKind::NativeStaticNobundle |
876 NativeLibraryKind::NativeUnknown => {
877 if sess.target.target.options.is_like_msvc {
878 Some(format!("{}.lib", name))
880 Some(format!("-l{}", name))
883 NativeLibraryKind::NativeFramework => {
884 // ld-only syntax, since there are no frameworks in MSVC
885 Some(format!("-framework {}", name))
887 // These are included, no need to print them
888 NativeLibraryKind::NativeStatic |
889 NativeLibraryKind::NativeRawDylib => None,
893 if !lib_args.is_empty() {
894 sess.note_without_error("Link against the following native artifacts when linking \
895 against this static library. The order and any duplication \
896 can be significant on some platforms.");
897 // Prefix for greppability
898 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
902 pub fn get_file_path(sess: &Session, name: &str) -> PathBuf {
903 let fs = sess.target_filesearch(PathKind::Native);
904 let file_path = fs.get_lib_path().join(name);
905 if file_path.exists() {
908 for search_path in fs.search_paths() {
909 let file_path = search_path.dir.join(name);
910 if file_path.exists() {
917 pub fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
918 -> io::Result<Output>
920 // When attempting to spawn the linker we run a risk of blowing out the
921 // size limits for spawning a new process with respect to the arguments
922 // we pass on the command line.
924 // Here we attempt to handle errors from the OS saying "your list of
925 // arguments is too big" by reinvoking the linker again with an `@`-file
926 // that contains all the arguments. The theory is that this is then
927 // accepted on all linkers and the linker will read all its options out of
928 // there instead of looking at the command line.
929 if !cmd.very_likely_to_exceed_some_spawn_limit() {
930 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
932 let output = child.wait_with_output();
933 flush_linked_file(&output, out_filename)?;
936 Err(ref e) if command_line_too_big(e) => {
937 info!("command line to linker was too big: {}", e);
939 Err(e) => return Err(e)
943 info!("falling back to passing arguments to linker via an @-file");
944 let mut cmd2 = cmd.clone();
945 let mut args = String::new();
946 for arg in cmd2.take_args() {
947 args.push_str(&Escape {
948 arg: arg.to_str().unwrap(),
949 is_like_msvc: sess.target.target.options.is_like_msvc,
953 let file = tmpdir.join("linker-arguments");
954 let bytes = if sess.target.target.options.is_like_msvc {
955 let mut out = Vec::with_capacity((1 + args.len()) * 2);
956 // start the stream with a UTF-16 BOM
957 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
958 // encode in little endian
960 out.push((c >> 8) as u8);
966 fs::write(&file, &bytes)?;
967 cmd2.arg(format!("@{}", file.display()));
968 info!("invoking linker {:?}", cmd2);
969 let output = cmd2.output();
970 flush_linked_file(&output, out_filename)?;
974 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
979 fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
982 // On Windows, under high I/O load, output buffers are sometimes not flushed,
983 // even long after process exit, causing nasty, non-reproducible output bugs.
985 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
987 // А full writeup of the original Chrome bug can be found at
988 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
990 if let &Ok(ref out) = command_output {
991 if out.status.success() {
992 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1002 fn command_line_too_big(err: &io::Error) -> bool {
1003 err.raw_os_error() == Some(::libc::E2BIG)
1007 fn command_line_too_big(err: &io::Error) -> bool {
1008 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1009 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1017 impl<'a> fmt::Display for Escape<'a> {
1018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 if self.is_like_msvc {
1020 // This is "documented" at
1021 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
1023 // Unfortunately there's not a great specification of the
1024 // syntax I could find online (at least) but some local
1025 // testing showed that this seemed sufficient-ish to catch
1026 // at least a few edge cases.
1028 for c in self.arg.chars() {
1030 '"' => write!(f, "\\{}", c)?,
1031 c => write!(f, "{}", c)?,
1036 // This is documented at https://linux.die.net/man/1/ld, namely:
1038 // > Options in file are separated by whitespace. A whitespace
1039 // > character may be included in an option by surrounding the
1040 // > entire option in either single or double quotes. Any
1041 // > character (including a backslash) may be included by
1042 // > prefixing the character to be included with a backslash.
1044 // We put an argument on each line, so all we need to do is
1045 // ensure the line is interpreted as one whole argument.
1046 for c in self.arg.chars() {
1048 '\\' | ' ' => write!(f, "\\{}", c)?,
1049 c => write!(f, "{}", c)?,
1058 fn link_args<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1059 flavor: LinkerFlavor,
1061 crate_type: config::CrateType,
1063 out_filename: &Path,
1064 codegen_results: &CodegenResults) {
1066 // Linker plugins should be specified early in the list of arguments
1067 cmd.linker_plugin_lto();
1069 // The default library location, we need this to find the runtime.
1070 // The location of crates will be determined as needed.
1071 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1073 // target descriptor
1074 let t = &sess.target.target;
1076 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1078 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1079 cmd.add_object(obj);
1081 cmd.output_filename(out_filename);
1083 if crate_type == config::CrateType::Executable &&
1084 sess.target.target.options.is_like_windows {
1085 if let Some(ref s) = codegen_results.windows_subsystem {
1090 // If we're building something like a dynamic library then some platforms
1091 // need to make sure that all symbols are exported correctly from the
1093 cmd.export_symbols(tmpdir, crate_type);
1095 // When linking a dynamic library, we put the metadata into a section of the
1096 // executable. This metadata is in a separate object file from the main
1097 // object file, so we link that in here.
1098 if crate_type == config::CrateType::Dylib ||
1099 crate_type == config::CrateType::ProcMacro {
1100 let obj = codegen_results.metadata_module
1102 .and_then(|m| m.object.as_ref());
1103 if let Some(obj) = obj {
1104 cmd.add_object(obj);
1108 let obj = codegen_results.allocator_module
1110 .and_then(|m| m.object.as_ref());
1111 if let Some(obj) = obj {
1112 cmd.add_object(obj);
1115 // Try to strip as much out of the generated object by removing unused
1116 // sections if possible. See more comments in linker.rs
1117 if !sess.opts.cg.link_dead_code {
1118 let keep_metadata = crate_type == config::CrateType::Dylib;
1119 cmd.gc_sections(keep_metadata);
1122 let used_link_args = &codegen_results.crate_info.link_args;
1124 if crate_type == config::CrateType::Executable {
1125 let mut position_independent_executable = false;
1127 if t.options.position_independent_executables {
1128 let empty_vec = Vec::new();
1129 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1130 let more_args = &sess.opts.cg.link_arg;
1131 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1133 if is_pic(sess) && !sess.crt_static() && !args.any(|x| *x == "-static") {
1134 position_independent_executable = true;
1138 if position_independent_executable {
1139 cmd.position_independent_executable();
1141 // recent versions of gcc can be configured to generate position
1142 // independent executables by default. We have to pass -no-pie to
1143 // explicitly turn that off. Not applicable to ld.
1144 if sess.target.target.options.linker_is_gnu
1145 && flavor != LinkerFlavor::Ld {
1146 cmd.no_position_independent_executable();
1151 let relro_level = match sess.opts.debugging_opts.relro_level {
1152 Some(level) => level,
1153 None => t.options.relro_level,
1156 RelroLevel::Full => {
1159 RelroLevel::Partial => {
1160 cmd.partial_relro();
1162 RelroLevel::Off => {
1165 RelroLevel::None => {
1169 // Pass optimization flags down to the linker.
1172 // Pass debuginfo flags down to the linker.
1175 // We want to, by default, prevent the compiler from accidentally leaking in
1176 // any system libraries, so we may explicitly ask linkers to not link to any
1177 // libraries by default. Note that this does not happen for windows because
1178 // windows pulls in some large number of libraries and I couldn't quite
1179 // figure out which subset we wanted.
1181 // This is all naturally configurable via the standard methods as well.
1182 if !sess.opts.cg.default_linker_libraries.unwrap_or(false) &&
1183 t.options.no_default_libraries
1185 cmd.no_default_libraries();
1188 // Take careful note of the ordering of the arguments we pass to the linker
1189 // here. Linkers will assume that things on the left depend on things to the
1190 // right. Things on the right cannot depend on things on the left. This is
1191 // all formally implemented in terms of resolving symbols (libs on the right
1192 // resolve unknown symbols of libs on the left, but not vice versa).
1194 // For this reason, we have organized the arguments we pass to the linker as
1197 // 1. The local object that LLVM just generated
1198 // 2. Local native libraries
1199 // 3. Upstream rust libraries
1200 // 4. Upstream native libraries
1202 // The rationale behind this ordering is that those items lower down in the
1203 // list can't depend on items higher up in the list. For example nothing can
1204 // depend on what we just generated (e.g., that'd be a circular dependency).
1205 // Upstream rust libraries are not allowed to depend on our local native
1206 // libraries as that would violate the structure of the DAG, in that
1207 // scenario they are required to link to them as well in a shared fashion.
1209 // Note that upstream rust libraries may contain native dependencies as
1210 // well, but they also can't depend on what we just started to add to the
1211 // link line. And finally upstream native libraries can't depend on anything
1212 // in this DAG so far because they're only dylibs and dylibs can only depend
1213 // on other dylibs (e.g., other native deps).
1214 add_local_native_libraries(cmd, sess, codegen_results);
1215 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1216 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1218 // Tell the linker what we're doing.
1219 if crate_type != config::CrateType::Executable {
1220 cmd.build_dylib(out_filename);
1222 if crate_type == config::CrateType::Executable && sess.crt_static() {
1223 cmd.build_static_executable();
1226 if sess.opts.cg.profile_generate.enabled() {
1230 // FIXME (#2397): At some point we want to rpath our guesses as to
1231 // where extern libraries might live, based on the
1232 // addl_lib_search_paths
1233 if sess.opts.cg.rpath {
1234 let target_triple = sess.opts.target_triple.triple();
1235 let mut get_install_prefix_lib_path = || {
1236 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1237 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1238 let mut path = PathBuf::from(install_prefix);
1243 let mut rpath_config = RPathConfig {
1244 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1245 out_filename: out_filename.to_path_buf(),
1246 has_rpath: sess.target.target.options.has_rpath,
1247 is_like_osx: sess.target.target.options.is_like_osx,
1248 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1249 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1251 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1254 // Finally add all the linker arguments provided on the command line along
1255 // with any #[link_args] attributes found inside the crate
1256 if let Some(ref args) = sess.opts.cg.link_args {
1259 cmd.args(&sess.opts.cg.link_arg);
1260 cmd.args(&used_link_args);
1263 // # Native library linking
1265 // User-supplied library search paths (-L on the command line). These are
1266 // the same paths used to find Rust crates, so some of them may have been
1267 // added already by the previous crate linking code. This only allows them
1268 // to be found at compile time so it is still entirely up to outside
1269 // forces to make sure that library can be found at runtime.
1271 // Also note that the native libraries linked here are only the ones located
1272 // in the current crate. Upstream crates with native library dependencies
1273 // may have their native library pulled in above.
1274 pub fn add_local_native_libraries(cmd: &mut dyn Linker,
1276 codegen_results: &CodegenResults) {
1277 let filesearch = sess.target_filesearch(PathKind::All);
1278 for search_path in filesearch.search_paths() {
1279 match search_path.kind {
1280 PathKind::Framework => { cmd.framework_path(&search_path.dir); }
1281 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)); }
1285 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1286 relevant_lib(sess, l)
1289 let search_path = archive_search_paths(sess);
1290 for lib in relevant_libs {
1291 let name = match lib.name {
1296 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1297 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1298 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(name),
1299 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(name, &search_path),
1300 NativeLibraryKind::NativeRawDylib => {
1301 // FIXME(#58713): Proper handling for raw dylibs.
1302 bug!("raw_dylib feature not yet implemented");
1308 // # Rust Crate linking
1310 // Rust crates are not considered at all when creating an rlib output. All
1311 // dependencies will be linked when producing the final output (instead of
1312 // the intermediate rlib version)
1313 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1314 cmd: &mut dyn Linker,
1316 codegen_results: &CodegenResults,
1317 crate_type: config::CrateType,
1320 // All of the heavy lifting has previously been accomplished by the
1321 // dependency_format module of the compiler. This is just crawling the
1322 // output of that module, adding crates as necessary.
1324 // Linking to a rlib involves just passing it to the linker (the linker
1325 // will slurp up the object files inside), and linking to a dynamic library
1326 // involves just passing the right -l flag.
1328 let (_, data) = codegen_results.crate_info.dependency_formats
1330 .find(|(ty, _)| *ty == crate_type)
1331 .expect("failed to find crate type in dependency format list");
1333 // Invoke get_used_crates to ensure that we get a topological sorting of
1335 let deps = &codegen_results.crate_info.used_crates_dynamic;
1337 // There's a few internal crates in the standard library (aka libcore and
1338 // libstd) which actually have a circular dependence upon one another. This
1339 // currently arises through "weak lang items" where libcore requires things
1340 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1341 // circular dependence to work correctly in all situations we'll need to be
1342 // sure to correctly apply the `--start-group` and `--end-group` options to
1343 // GNU linkers, otherwise if we don't use any other symbol from the standard
1344 // library it'll get discarded and the whole application won't link.
1346 // In this loop we're calculating the `group_end`, after which crate to
1347 // pass `--end-group` and `group_start`, before which crate to pass
1348 // `--start-group`. We currently do this by passing `--end-group` after
1349 // the first crate (when iterating backwards) that requires a lang item
1350 // defined somewhere else. Once that's set then when we've defined all the
1351 // necessary lang items we'll pass `--start-group`.
1353 // Note that this isn't amazing logic for now but it should do the trick
1354 // for the current implementation of the standard library.
1355 let mut group_end = None;
1356 let mut group_start = None;
1357 let mut end_with = FxHashSet::default();
1358 let info = &codegen_results.crate_info;
1359 for &(cnum, _) in deps.iter().rev() {
1360 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1361 end_with.extend(missing.iter().cloned());
1362 if end_with.len() > 0 && group_end.is_none() {
1363 group_end = Some(cnum);
1366 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1367 if end_with.len() == 0 && group_end.is_some() {
1368 group_start = Some(cnum);
1373 // If we didn't end up filling in all lang items from upstream crates then
1374 // we'll be filling it in with our crate. This probably means we're the
1375 // standard library itself, so skip this for now.
1376 if group_end.is_some() && group_start.is_none() {
1380 let mut compiler_builtins = None;
1382 for &(cnum, _) in deps.iter() {
1383 if group_start == Some(cnum) {
1387 // We may not pass all crates through to the linker. Some crates may
1388 // appear statically in an existing dylib, meaning we'll pick up all the
1389 // symbols from the dylib.
1390 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1391 match data[cnum.as_usize() - 1] {
1392 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1393 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1395 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) &&
1396 crate_type == config::CrateType::Executable => {
1397 // Link the sanitizer runtimes only if we are actually producing an executable
1398 link_sanitizer_runtime::<B>(cmd, sess, codegen_results, tmpdir, cnum);
1400 // compiler-builtins are always placed last to ensure that they're
1401 // linked correctly.
1402 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1403 assert!(compiler_builtins.is_none());
1404 compiler_builtins = Some(cnum);
1406 Linkage::NotLinked |
1407 Linkage::IncludedFromDylib => {}
1408 Linkage::Static => {
1409 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1411 Linkage::Dynamic => {
1412 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1416 if group_end == Some(cnum) {
1421 // compiler-builtins are always placed last to ensure that they're
1422 // linked correctly.
1423 // We must always link the `compiler_builtins` crate statically. Even if it
1424 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1426 if let Some(cnum) = compiler_builtins {
1427 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1430 // Converts a library file-stem into a cc -l argument
1431 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1432 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1439 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1440 // it's packed in a .rlib, it contains stuff that are not objects that will
1441 // make the linker error. So we must remove those bits from the .rlib before
1443 fn link_sanitizer_runtime<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1445 codegen_results: &CodegenResults,
1448 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1449 let cratepath = &src.rlib.as_ref().unwrap().0;
1451 if sess.target.target.options.is_like_osx {
1452 // On Apple platforms, the sanitizer is always built as a dylib, and
1453 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1454 // rpath to the library as well (the rpath should be absolute, see
1455 // PR #41352 for details).
1457 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1458 let rpath = cratepath.parent().unwrap();
1459 let rpath = rpath.to_str().expect("non-utf8 component in path");
1460 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1463 let dst = tmpdir.join(cratepath.file_name().unwrap());
1464 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1465 archive.update_symbols();
1467 for f in archive.src_files() {
1468 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1469 archive.remove_file(&f);
1475 cmd.link_whole_rlib(&dst);
1478 // Adds the static "rlib" versions of all crates to the command line.
1479 // There's a bit of magic which happens here specifically related to LTO and
1480 // dynamic libraries. Specifically:
1482 // * For LTO, we remove upstream object files.
1483 // * For dylibs we remove metadata and bytecode from upstream rlibs
1485 // When performing LTO, almost(*) all of the bytecode from the upstream
1486 // libraries has already been included in our object file output. As a
1487 // result we need to remove the object files in the upstream libraries so
1488 // the linker doesn't try to include them twice (or whine about duplicate
1489 // symbols). We must continue to include the rest of the rlib, however, as
1490 // it may contain static native libraries which must be linked in.
1492 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1493 // their bytecode wasn't included. The object files in those libraries must
1494 // still be passed to the linker.
1496 // When making a dynamic library, linkers by default don't include any
1497 // object files in an archive if they're not necessary to resolve the link.
1498 // We basically want to convert the archive (rlib) to a dylib, though, so we
1499 // *do* want everything included in the output, regardless of whether the
1500 // linker thinks it's needed or not. As a result we must use the
1501 // --whole-archive option (or the platform equivalent). When using this
1502 // option the linker will fail if there are non-objects in the archive (such
1503 // as our own metadata and/or bytecode). All in all, for rlibs to be
1504 // entirely included in dylibs, we need to remove all non-object files.
1506 // Note, however, that if we're not doing LTO or we're not producing a dylib
1507 // (aka we're making an executable), we can just pass the rlib blindly to
1508 // the linker (fast) because it's fine if it's not actually included as
1509 // we're at the end of the dependency chain.
1510 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1512 codegen_results: &CodegenResults,
1514 crate_type: config::CrateType,
1516 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1517 let cratepath = &src.rlib.as_ref().unwrap().0;
1519 // See the comment above in `link_staticlib` and `link_rlib` for why if
1520 // there's a static library that's not relevant we skip all object
1522 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1523 let skip_native = native_libs.iter().any(|lib| {
1524 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1527 if (!are_upstream_rust_objects_already_included(sess) ||
1528 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1529 crate_type != config::CrateType::Dylib &&
1531 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1535 let dst = tmpdir.join(cratepath.file_name().unwrap());
1536 let name = cratepath.file_name().unwrap().to_str().unwrap();
1537 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1539 time_ext(sess.time_extended(), &format!("altering {}.rlib", name), || {
1540 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1541 archive.update_symbols();
1543 let mut any_objects = false;
1544 for f in archive.src_files() {
1545 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1546 archive.remove_file(&f);
1550 let canonical = f.replace("-", "_");
1551 let canonical_name = name.replace("-", "_");
1553 let is_rust_object =
1554 canonical.starts_with(&canonical_name) &&
1555 looks_like_rust_object_file(&f);
1557 // If we've been requested to skip all native object files
1558 // (those not generated by the rust compiler) then we can skip
1559 // this file. See above for why we may want to do this.
1560 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1562 // If we're performing LTO and this is a rust-generated object
1563 // file, then we don't need the object file as it's part of the
1564 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1565 // though, so we let that object file slide.
1566 let skip_because_lto = are_upstream_rust_objects_already_included(sess) &&
1568 (sess.target.target.options.no_builtins ||
1569 !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1571 if skip_because_cfg_say_so || skip_because_lto {
1572 archive.remove_file(&f);
1583 // If we're creating a dylib, then we need to include the
1584 // whole of each object in our archive into that artifact. This is
1585 // because a `dylib` can be reused as an intermediate artifact.
1587 // Note, though, that we don't want to include the whole of a
1588 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1589 // repeatedly linked anyway.
1590 if crate_type == config::CrateType::Dylib &&
1591 codegen_results.crate_info.compiler_builtins != Some(cnum) {
1592 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1594 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1599 // Same thing as above, but for dynamic crates instead of static crates.
1600 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1601 // Just need to tell the linker about where the library lives and
1603 let parent = cratepath.parent();
1604 if let Some(dir) = parent {
1605 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1607 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1608 cmd.link_rust_dylib(Symbol::intern(&unlib(&sess.target, filestem)),
1609 parent.unwrap_or(Path::new("")));
1613 // Link in all of our upstream crates' native dependencies. Remember that
1614 // all of these upstream native dependencies are all non-static
1615 // dependencies. We've got two cases then:
1617 // 1. The upstream crate is an rlib. In this case we *must* link in the
1618 // native dependency because the rlib is just an archive.
1620 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1621 // have the dependency present on the system somewhere. Thus, we don't
1622 // gain a whole lot from not linking in the dynamic dependency to this
1625 // The use case for this is a little subtle. In theory the native
1626 // dependencies of a crate are purely an implementation detail of the crate
1627 // itself, but the problem arises with generic and inlined functions. If a
1628 // generic function calls a native function, then the generic function must
1629 // be instantiated in the target crate, meaning that the native symbol must
1630 // also be resolved in the target crate.
1631 pub fn add_upstream_native_libraries(
1632 cmd: &mut dyn Linker,
1634 codegen_results: &CodegenResults,
1635 crate_type: config::CrateType,
1637 // Be sure to use a topological sorting of crates because there may be
1638 // interdependencies between native libraries. When passing -nodefaultlibs,
1639 // for example, almost all native libraries depend on libc, so we have to
1640 // make sure that's all the way at the right (liblibc is near the base of
1641 // the dependency chain).
1643 // This passes RequireStatic, but the actual requirement doesn't matter,
1644 // we're just getting an ordering of crate numbers, we're not worried about
1646 let (_, data) = codegen_results.crate_info.dependency_formats
1648 .find(|(ty, _)| *ty == crate_type)
1649 .expect("failed to find crate type in dependency format list");
1651 let crates = &codegen_results.crate_info.used_crates_static;
1652 for &(cnum, _) in crates {
1653 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1654 let name = match lib.name {
1658 if !relevant_lib(sess, &lib) {
1662 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1663 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1664 NativeLibraryKind::NativeStaticNobundle => {
1665 // Link "static-nobundle" native libs only if the crate they originate from
1666 // is being linked statically to the current crate. If it's linked dynamically
1667 // or is an rlib already included via some other dylib crate, the symbols from
1668 // native libs will have already been included in that dylib.
1669 if data[cnum.as_usize() - 1] == Linkage::Static {
1670 cmd.link_staticlib(name)
1673 // ignore statically included native libraries here as we've
1674 // already included them when we included the rust library
1676 NativeLibraryKind::NativeStatic => {},
1677 NativeLibraryKind::NativeRawDylib => {
1678 // FIXME(#58713): Proper handling for raw dylibs.
1679 bug!("raw_dylib feature not yet implemented");
1686 pub fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1688 Some(ref cfg) => syntax::attr::cfg_matches(cfg, &sess.parse_sess, None),
1693 pub fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1695 config::Lto::Fat => true,
1696 config::Lto::Thin => {
1697 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1698 // any upstream object files have not been copied yet.
1699 !sess.opts.cg.linker_plugin_lto.enabled()
1702 config::Lto::ThinLocal => false,
1706 fn is_pic(sess: &Session) -> bool {
1707 let reloc_model_arg = match sess.opts.cg.relocation_model {
1708 Some(ref s) => &s[..],
1709 None => &sess.target.target.options.relocation_model[..],
1712 reloc_model_arg == "pic"