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, RUST_CGU_EXT, 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};
17 use crate::{METADATA_FILENAME, RLIB_BYTECODE_EXTENSION, CrateInfo, CodegenResults};
18 use super::archive::ArchiveBuilder;
19 use super::command::Command;
20 use super::linker::Linker;
21 use super::rpath::{self, RPathConfig};
23 use cc::windows_registry;
24 use tempfile::{Builder as TempFileBuilder, TempDir};
31 use std::path::{Path, PathBuf};
32 use std::process::{Output, Stdio};
36 pub use rustc_codegen_utils::link::*;
38 pub fn remove(sess: &Session, path: &Path) {
39 if let Err(e) = fs::remove_file(path) {
40 sess.err(&format!("failed to remove {}: {}",
46 /// Performs the linkage portion of the compilation phase. This will generate all
47 /// of the requested outputs for this compilation session.
48 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
49 codegen_results: &CodegenResults,
50 outputs: &OutputFilenames,
53 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
54 for &crate_type in sess.crate_types.borrow().iter() {
55 // Ignore executable crates if we have -Z no-codegen, as they will error.
56 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen()) &&
58 crate_type == config::CrateType::Executable {
62 if invalid_output_for_target(sess, crate_type) {
63 bug!("invalid output type `{:?}` for target os `{}`",
64 crate_type, sess.opts.target_triple);
67 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
68 check_file_is_writeable(obj, sess);
71 let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err|
72 sess.fatal(&format!("couldn't create a temp dir: {}", err)));
74 if outputs.outputs.should_codegen() {
75 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
77 config::CrateType::Rlib => {
84 config::CrateType::Staticlib => {
85 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
100 if sess.opts.cg.save_temps {
101 let _ = tmpdir.into_path();
105 // Remove the temporary object file and metadata if we aren't saving temps
106 if !sess.opts.cg.save_temps {
107 if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) {
108 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
112 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
115 if let Some(ref metadata_module) = codegen_results.metadata_module {
116 if let Some(ref obj) = metadata_module.object {
120 if let Some(ref allocator_module) = codegen_results.allocator_module {
121 if let Some(ref obj) = allocator_module.object {
124 if let Some(ref bc) = allocator_module.bytecode_compressed {
131 // The third parameter is for env vars, used on windows to set up the
132 // path for MSVC to find its DLLs, and gcc to find its bundled
134 pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
135 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
137 // If our linker looks like a batch script on Windows then to execute this
138 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
139 // emscripten where the linker is `emcc.bat` and needs to be spawned as
140 // `cmd /c emcc.bat ...`.
142 // This worked historically but is needed manually since #42436 (regression
143 // was tagged as #42791) and some more info can be found on #44443 for
144 // emscripten itself.
145 let mut cmd = match linker.to_str() {
146 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
148 LinkerFlavor::Lld(f) => Command::lld(linker, f),
150 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
152 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
154 _ => Command::new(linker),
158 // The compiler's sysroot often has some bundled tools, so add it to the
159 // PATH for the child.
160 let mut new_path = sess.host_filesearch(PathKind::All)
161 .get_tools_search_paths();
162 let mut msvc_changed_path = false;
163 if sess.target.target.options.is_like_msvc {
164 if let Some(ref tool) = msvc_tool {
165 cmd.args(tool.args());
166 for &(ref k, ref v) in tool.env() {
168 new_path.extend(env::split_paths(v));
169 msvc_changed_path = true;
177 if !msvc_changed_path {
178 if let Some(path) = env::var_os("PATH") {
179 new_path.extend(env::split_paths(&path));
182 cmd.env("PATH", env::join_paths(new_path).unwrap());
184 (linker.to_path_buf(), cmd)
187 pub fn each_linked_rlib(sess: &Session,
189 f: &mut dyn FnMut(CrateNum, &Path)) -> Result<(), String> {
190 let crates = info.used_crates_static.iter();
191 let fmts = sess.dependency_formats.borrow();
192 let fmts = fmts.get(&config::CrateType::Executable)
193 .or_else(|| fmts.get(&config::CrateType::Staticlib))
194 .or_else(|| fmts.get(&config::CrateType::Cdylib))
195 .or_else(|| fmts.get(&config::CrateType::ProcMacro));
196 let fmts = match fmts {
198 None => return Err("could not find formats for rlibs".to_string())
200 for &(cnum, ref path) in crates {
201 match fmts.get(cnum.as_usize() - 1) {
202 Some(&Linkage::NotLinked) |
203 Some(&Linkage::IncludedFromDylib) => continue,
205 None => return Err("could not find formats for rlibs".to_string())
207 let name = &info.crate_name[&cnum];
208 let path = match *path {
209 LibSource::Some(ref p) => p,
210 LibSource::MetadataOnly => {
211 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
215 return Err(format!("could not find rlib for: `{}`", name))
223 /// We use a temp directory here to avoid races between concurrent rustc processes,
224 /// such as builds in the same directory using the same filename for metadata while
225 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
226 /// directory being searched for `extern crate` (observing an incomplete file).
227 /// The returned path is the temporary file containing the complete metadata.
228 pub fn emit_metadata<'a>(
230 metadata: &EncodedMetadata,
233 let out_filename = tmpdir.path().join(METADATA_FILENAME);
234 let result = fs::write(&out_filename, &metadata.raw_data);
236 if let Err(e) = result {
237 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
245 // An rlib in its current incarnation is essentially a renamed .a file. The
246 // rlib primarily contains the object file of the crate, but it also contains
247 // all of the object files from native libraries. This is done by unzipping
248 // native libraries and inserting all of the contents into this archive.
249 fn link_rlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
250 codegen_results: &CodegenResults,
253 tmpdir: &TempDir) -> B {
254 info!("preparing rlib to {:?}", out_filename);
255 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
257 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
261 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
262 // we may not be configured to actually include a static library if we're
263 // adding it here. That's because later when we consume this rlib we'll
264 // decide whether we actually needed the static library or not.
266 // To do this "correctly" we'd need to keep track of which libraries added
267 // which object files to the archive. We don't do that here, however. The
268 // #[link(cfg(..))] feature is unstable, though, and only intended to get
269 // liblibc working. In that sense the check below just indicates that if
270 // there are any libraries we want to omit object files for at link time we
271 // just exclude all custom object files.
273 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
274 // feature then we'll need to figure out how to record what objects were
275 // loaded from the libraries found here and then encode that into the
276 // metadata of the rlib we're generating somehow.
277 for lib in codegen_results.crate_info.used_libraries.iter() {
279 NativeLibraryKind::NativeStatic => {}
280 NativeLibraryKind::NativeStaticNobundle |
281 NativeLibraryKind::NativeFramework |
282 NativeLibraryKind::NativeUnknown => continue,
284 if let Some(name) = lib.name {
285 ab.add_native_library(&name.as_str());
289 // After adding all files to the archive, we need to update the
290 // symbol table of the archive.
293 // Note that it is important that we add all of our non-object "magical
294 // files" *after* all of the object files in the archive. The reason for
295 // this is as follows:
297 // * When performing LTO, this archive will be modified to remove
298 // objects from above. The reason for this is described below.
300 // * When the system linker looks at an archive, it will attempt to
301 // determine the architecture of the archive in order to see whether its
304 // The algorithm for this detection is: iterate over the files in the
305 // archive. Skip magical SYMDEF names. Interpret the first file as an
306 // object file. Read architecture from the object file.
308 // * As one can probably see, if "metadata" and "foo.bc" were placed
309 // before all of the objects, then the architecture of this archive would
310 // not be correctly inferred once 'foo.o' is removed.
312 // Basically, all this means is that this code should not move above the
315 RlibFlavor::Normal => {
316 // Instead of putting the metadata in an object file section, rlibs
317 // contain the metadata in a separate file.
318 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
320 // For LTO purposes, the bytecode of this library is also inserted
322 for bytecode in codegen_results
325 .filter_map(|m| m.bytecode_compressed.as_ref())
327 ab.add_file(bytecode);
330 // After adding all files to the archive, we need to update the
331 // symbol table of the archive. This currently dies on macOS (see
332 // #11162), and isn't necessary there anyway
333 if !sess.target.target.options.is_like_osx {
338 RlibFlavor::StaticlibBase => {
339 let obj = codegen_results.allocator_module
341 .and_then(|m| m.object.as_ref());
342 if let Some(obj) = obj {
351 // Create a static archive
353 // This is essentially the same thing as an rlib, but it also involves adding
354 // all of the upstream crates' objects into the archive. This will slurp in
355 // all of the native libraries of upstream dependencies as well.
357 // Additionally, there's no way for us to link dynamic libraries, so we warn
358 // about all dynamic library dependencies that they're not linked in.
360 // There's no need to include metadata in a static archive, so ensure to not
361 // link in the metadata object file (and also don't prepare the archive with a
363 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
364 codegen_results: &CodegenResults,
367 let mut ab = link_rlib::<B>(sess,
369 RlibFlavor::StaticlibBase,
372 let mut all_native_libs = vec![];
374 let res = each_linked_rlib(sess, &codegen_results.crate_info, &mut |cnum, path| {
375 let name = &codegen_results.crate_info.crate_name[&cnum];
376 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
378 // Here when we include the rlib into our staticlib we need to make a
379 // decision whether to include the extra object files along the way.
380 // These extra object files come from statically included native
381 // libraries, but they may be cfg'd away with #[link(cfg(..))].
383 // This unstable feature, though, only needs liblibc to work. The only
384 // use case there is where musl is statically included in liblibc.rlib,
385 // so if we don't want the included version we just need to skip it. As
386 // a result the logic here is that if *any* linked library is cfg'd away
387 // we just skip all object files.
389 // Clearly this is not sufficient for a general purpose feature, and
390 // we'd want to read from the library's metadata to determine which
391 // object files come from where and selectively skip them.
392 let skip_object_files = native_libs.iter().any(|lib| {
393 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
397 are_upstream_rust_objects_already_included(sess) &&
398 !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
399 skip_object_files).unwrap();
401 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
403 if let Err(e) = res {
410 if !all_native_libs.is_empty() {
411 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
412 print_native_static_libs(sess, &all_native_libs);
417 // Create a dynamic library or executable
419 // This will invoke the system linker/cc to create the resulting file. This
420 // links to all upstream files as well.
421 fn link_natively<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
422 crate_type: config::CrateType,
424 codegen_results: &CodegenResults,
427 info!("preparing {:?} to {:?}", crate_type, out_filename);
428 let (linker, flavor) = linker_and_flavor(sess);
430 // The invocations of cc share some flags across platforms
431 let (pname, mut cmd) = get_linker(sess, &linker, flavor);
433 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
436 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
437 if sess.crt_static() {
441 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
444 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
446 if sess.target.target.options.is_like_fuchsia {
447 let prefix = match sess.opts.debugging_opts.sanitizer {
448 Some(Sanitizer::Address) => "asan/",
451 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
454 let pre_link_objects = if crate_type == config::CrateType::Executable {
455 &sess.target.target.options.pre_link_objects_exe
457 &sess.target.target.options.pre_link_objects_dll
459 for obj in pre_link_objects {
460 cmd.arg(get_file_path(sess, obj));
463 if crate_type == config::CrateType::Executable && sess.crt_static() {
464 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
465 cmd.arg(get_file_path(sess, obj));
469 if sess.target.target.options.is_like_emscripten {
471 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
472 "DISABLE_EXCEPTION_CATCHING=1"
474 "DISABLE_EXCEPTION_CATCHING=0"
479 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
480 link_args::<B>(&mut *linker, flavor, sess, crate_type, tmpdir,
481 out_filename, codegen_results);
482 cmd = linker.finalize();
484 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
487 for obj in &sess.target.target.options.post_link_objects {
488 cmd.arg(get_file_path(sess, obj));
490 if sess.crt_static() {
491 for obj in &sess.target.target.options.post_link_objects_crt {
492 cmd.arg(get_file_path(sess, obj));
495 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
498 for &(ref k, ref v) in &sess.target.target.options.link_env {
502 if sess.opts.debugging_opts.print_link_args {
503 println!("{:?}", &cmd);
506 // May have not found libraries in the right formats.
507 sess.abort_if_errors();
509 // Invoke the system linker
511 // Note that there's a terribly awful hack that really shouldn't be present
512 // in any compiler. Here an environment variable is supported to
513 // automatically retry the linker invocation if the linker looks like it
516 // Gee that seems odd, normally segfaults are things we want to know about!
517 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
518 // linker segfaulting on Travis quite a bit which is causing quite a bit of
519 // pain to land PRs when they spuriously fail due to a segfault.
521 // The issue #38878 has some more debugging information on it as well, but
522 // this unfortunately looks like it's just a race condition in macOS's linker
523 // with some thread pool working in the background. It seems that no one
524 // currently knows a fix for this so in the meantime we're left with this...
526 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
531 prog = time(sess, "running linker", || {
532 exec_linker(sess, &mut cmd, out_filename, tmpdir)
534 let output = match prog {
535 Ok(ref output) => output,
538 if output.status.success() {
541 let mut out = output.stderr.clone();
542 out.extend(&output.stdout);
543 let out = String::from_utf8_lossy(&out);
545 // Check to see if the link failed with "unrecognized command line option:
546 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
547 // reperform the link step without the -no-pie option. This is safe because
548 // if the linker doesn't support -no-pie then it should not default to
549 // linking executables as pie. Different versions of gcc seem to use
550 // different quotes in the error message so don't check for them.
551 if sess.target.target.options.linker_is_gnu &&
552 flavor != LinkerFlavor::Ld &&
553 (out.contains("unrecognized command line option") ||
554 out.contains("unknown argument")) &&
555 out.contains("-no-pie") &&
556 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
557 info!("linker output: {:?}", out);
558 warn!("Linker does not support -no-pie command line option. Retrying without.");
559 for arg in cmd.take_args() {
560 if arg.to_string_lossy() != "-no-pie" {
567 if !retry_on_segfault || i > 3 {
570 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
571 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
572 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
577 "looks like the linker segfaulted when we tried to call it, \
578 automatically retrying again. cmd = {:?}, out = {}.",
586 fn escape_string(s: &[u8]) -> String {
587 str::from_utf8(s).map(|s| s.to_owned())
588 .unwrap_or_else(|_| {
589 let mut x = "Non-UTF-8 output: ".to_string();
591 .flat_map(|&b| ascii::escape_default(b))
596 if !prog.status.success() {
597 let mut output = prog.stderr.clone();
598 output.extend_from_slice(&prog.stdout);
599 sess.struct_err(&format!("linking with `{}` failed: {}",
602 .note(&format!("{:?}", &cmd))
603 .note(&escape_string(&output))
605 sess.abort_if_errors();
607 info!("linker stderr:\n{}", escape_string(&prog.stderr));
608 info!("linker stdout:\n{}", escape_string(&prog.stdout));
611 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
613 let mut linker_error = {
614 if linker_not_found {
615 sess.struct_err(&format!("linker `{}` not found", pname.display()))
617 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
621 linker_error.note(&e.to_string());
623 if !linker_not_found {
624 linker_error.note(&format!("{:?}", &cmd));
629 if sess.target.target.options.is_like_msvc && linker_not_found {
630 sess.note_without_error("the msvc targets depend on the msvc linker \
631 but `link.exe` was not found");
632 sess.note_without_error("please ensure that VS 2013, VS 2015 or VS 2017 \
633 was installed with the Visual C++ option");
635 sess.abort_if_errors();
640 // On macOS, debuggers need this utility to get run to do some munging of
641 // the symbols. Note, though, that if the object files are being preserved
642 // for their debug information there's no need for us to run dsymutil.
643 if sess.target.target.options.is_like_osx &&
644 sess.opts.debuginfo != DebugInfo::None &&
645 !preserve_objects_for_their_debuginfo(sess)
647 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
648 sess.fatal(&format!("failed to run dsymutil: {}", e))
652 if sess.opts.target_triple.triple() == "wasm32-unknown-unknown" {
653 super::wasm::add_producer_section(
655 &sess.edition().to_string(),
656 option_env!("CFG_VERSION").unwrap_or("unknown"),
661 /// Returns a boolean indicating whether the specified crate should be ignored
664 /// Crates ignored during LTO are not lumped together in the "massive object
665 /// file" that we create and are linked in their normal rlib states. See
666 /// comments below for what crates do not participate in LTO.
668 /// It's unusual for a crate to not participate in LTO. Typically only
669 /// compiler-specific and unstable crates have a reason to not participate in
671 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
672 // If our target enables builtin function lowering in LLVM then the
673 // crates providing these functions don't participate in LTO (e.g.
674 // no_builtins or compiler builtins crates).
675 !sess.target.target.options.no_builtins &&
676 (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
679 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
682 linker: Option<PathBuf>,
683 flavor: Option<LinkerFlavor>,
684 ) -> Option<(PathBuf, LinkerFlavor)> {
685 match (linker, flavor) {
686 (Some(linker), Some(flavor)) => Some((linker, flavor)),
687 // only the linker flavor is known; use the default linker for the selected flavor
688 (None, Some(flavor)) => Some((PathBuf::from(match flavor {
689 LinkerFlavor::Em => if cfg!(windows) { "emcc.bat" } else { "emcc" },
690 LinkerFlavor::Gcc => "cc",
691 LinkerFlavor::Ld => "ld",
692 LinkerFlavor::Msvc => "link.exe",
693 LinkerFlavor::Lld(_) => "lld",
694 LinkerFlavor::PtxLinker => "rust-ptx-linker",
696 (Some(linker), None) => {
699 .and_then(|stem| stem.to_str())
701 sess.fatal("couldn't extract file stem from specified linker")
704 let flavor = if stem == "emcc" {
706 } else if stem == "gcc"
707 || stem.ends_with("-gcc")
709 || stem.ends_with("-clang")
712 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
714 } else if stem == "link" || stem == "lld-link" {
716 } else if stem == "lld" || stem == "rust-lld" {
717 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
719 // fall back to the value in the target spec
720 sess.target.target.linker_flavor
723 Some((linker, flavor))
725 (None, None) => None,
729 // linker and linker flavor specified via command line have precedence over what the target
730 // specification specifies
731 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
735 if let Some(ret) = infer_from(
737 sess.target.target.options.linker.clone().map(PathBuf::from),
738 Some(sess.target.target.linker_flavor),
743 bug!("Not enough information provided to determine how to invoke the linker");
746 /// Returns a boolean indicating whether we should preserve the object files on
747 /// the filesystem for their debug information. This is often useful with
748 /// split-dwarf like schemes.
749 pub fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
750 // If the objects don't have debuginfo there's nothing to preserve.
751 if sess.opts.debuginfo == config::DebugInfo::None {
755 // If we're only producing artifacts that are archives, no need to preserve
756 // the objects as they're losslessly contained inside the archives.
757 let output_linked = sess.crate_types.borrow()
759 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
764 // If we're on OSX then the equivalent of split dwarf is turned on by
765 // default. The final executable won't actually have any debug information
766 // except it'll have pointers to elsewhere. Historically we've always run
767 // `dsymutil` to "link all the dwarf together" but this is actually sort of
768 // a bummer for incremental compilation! (the whole point of split dwarf is
769 // that you don't do this sort of dwarf link).
771 // Basically as a result this just means that if we're on OSX and we're
772 // *not* running dsymutil then the object files are the only source of truth
773 // for debug information, so we must preserve them.
774 if sess.target.target.options.is_like_osx {
775 match sess.opts.debugging_opts.run_dsymutil {
776 // dsymutil is not being run, preserve objects
777 Some(false) => return true,
779 // dsymutil is being run, no need to preserve the objects
780 Some(true) => return false,
782 // The default historical behavior was to always run dsymutil, so
783 // we're preserving that temporarily, but we're likely to switch the
785 None => return false,
792 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
793 sess.target_filesearch(PathKind::Native).search_path_dirs()
801 pub fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
802 let lib_args: Vec<_> = all_native_libs.iter()
803 .filter(|l| relevant_lib(sess, l))
805 let name = lib.name?;
807 NativeLibraryKind::NativeStaticNobundle |
808 NativeLibraryKind::NativeUnknown => {
809 if sess.target.target.options.is_like_msvc {
810 Some(format!("{}.lib", name))
812 Some(format!("-l{}", name))
815 NativeLibraryKind::NativeFramework => {
816 // ld-only syntax, since there are no frameworks in MSVC
817 Some(format!("-framework {}", name))
819 // These are included, no need to print them
820 NativeLibraryKind::NativeStatic => None,
824 if !lib_args.is_empty() {
825 sess.note_without_error("Link against the following native artifacts when linking \
826 against this static library. The order and any duplication \
827 can be significant on some platforms.");
828 // Prefix for greppability
829 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
833 pub fn get_file_path(sess: &Session, name: &str) -> PathBuf {
834 let fs = sess.target_filesearch(PathKind::Native);
835 let file_path = fs.get_lib_path().join(name);
836 if file_path.exists() {
839 for search_path in fs.search_paths() {
840 let file_path = search_path.dir.join(name);
841 if file_path.exists() {
848 pub fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
849 -> io::Result<Output>
851 // When attempting to spawn the linker we run a risk of blowing out the
852 // size limits for spawning a new process with respect to the arguments
853 // we pass on the command line.
855 // Here we attempt to handle errors from the OS saying "your list of
856 // arguments is too big" by reinvoking the linker again with an `@`-file
857 // that contains all the arguments. The theory is that this is then
858 // accepted on all linkers and the linker will read all its options out of
859 // there instead of looking at the command line.
860 if !cmd.very_likely_to_exceed_some_spawn_limit() {
861 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
863 let output = child.wait_with_output();
864 flush_linked_file(&output, out_filename)?;
867 Err(ref e) if command_line_too_big(e) => {
868 info!("command line to linker was too big: {}", e);
870 Err(e) => return Err(e)
874 info!("falling back to passing arguments to linker via an @-file");
875 let mut cmd2 = cmd.clone();
876 let mut args = String::new();
877 for arg in cmd2.take_args() {
878 args.push_str(&Escape {
879 arg: arg.to_str().unwrap(),
880 is_like_msvc: sess.target.target.options.is_like_msvc,
884 let file = tmpdir.join("linker-arguments");
885 let bytes = if sess.target.target.options.is_like_msvc {
886 let mut out = Vec::with_capacity((1 + args.len()) * 2);
887 // start the stream with a UTF-16 BOM
888 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
889 // encode in little endian
891 out.push((c >> 8) as u8);
897 fs::write(&file, &bytes)?;
898 cmd2.arg(format!("@{}", file.display()));
899 info!("invoking linker {:?}", cmd2);
900 let output = cmd2.output();
901 flush_linked_file(&output, out_filename)?;
905 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
910 fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
913 // On Windows, under high I/O load, output buffers are sometimes not flushed,
914 // even long after process exit, causing nasty, non-reproducible output bugs.
916 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
918 // А full writeup of the original Chrome bug can be found at
919 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
921 if let &Ok(ref out) = command_output {
922 if out.status.success() {
923 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
933 fn command_line_too_big(err: &io::Error) -> bool {
934 err.raw_os_error() == Some(::libc::E2BIG)
938 fn command_line_too_big(err: &io::Error) -> bool {
939 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
940 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
948 impl<'a> fmt::Display for Escape<'a> {
949 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950 if self.is_like_msvc {
951 // This is "documented" at
952 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
954 // Unfortunately there's not a great specification of the
955 // syntax I could find online (at least) but some local
956 // testing showed that this seemed sufficient-ish to catch
957 // at least a few edge cases.
959 for c in self.arg.chars() {
961 '"' => write!(f, "\\{}", c)?,
962 c => write!(f, "{}", c)?,
967 // This is documented at https://linux.die.net/man/1/ld, namely:
969 // > Options in file are separated by whitespace. A whitespace
970 // > character may be included in an option by surrounding the
971 // > entire option in either single or double quotes. Any
972 // > character (including a backslash) may be included by
973 // > prefixing the character to be included with a backslash.
975 // We put an argument on each line, so all we need to do is
976 // ensure the line is interpreted as one whole argument.
977 for c in self.arg.chars() {
979 '\\' | ' ' => write!(f, "\\{}", c)?,
980 c => write!(f, "{}", c)?,
989 fn link_args<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
990 flavor: LinkerFlavor,
992 crate_type: config::CrateType,
995 codegen_results: &CodegenResults) {
997 // Linker plugins should be specified early in the list of arguments
998 cmd.linker_plugin_lto();
1000 // The default library location, we need this to find the runtime.
1001 // The location of crates will be determined as needed.
1002 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1004 // target descriptor
1005 let t = &sess.target.target;
1007 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1008 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1009 cmd.add_object(obj);
1011 cmd.output_filename(out_filename);
1013 if crate_type == config::CrateType::Executable &&
1014 sess.target.target.options.is_like_windows {
1015 if let Some(ref s) = codegen_results.windows_subsystem {
1020 // If we're building a dynamic library then some platforms need to make sure
1021 // that all symbols are exported correctly from the dynamic library.
1022 if crate_type != config::CrateType::Executable ||
1023 sess.target.target.options.is_like_emscripten {
1024 cmd.export_symbols(tmpdir, crate_type);
1027 // When linking a dynamic library, we put the metadata into a section of the
1028 // executable. This metadata is in a separate object file from the main
1029 // object file, so we link that in here.
1030 if crate_type == config::CrateType::Dylib ||
1031 crate_type == config::CrateType::ProcMacro {
1032 let obj = codegen_results.metadata_module
1034 .and_then(|m| m.object.as_ref());
1035 if let Some(obj) = obj {
1036 cmd.add_object(obj);
1040 let obj = codegen_results.allocator_module
1042 .and_then(|m| m.object.as_ref());
1043 if let Some(obj) = obj {
1044 cmd.add_object(obj);
1047 // Try to strip as much out of the generated object by removing unused
1048 // sections if possible. See more comments in linker.rs
1049 if !sess.opts.cg.link_dead_code {
1050 let keep_metadata = crate_type == config::CrateType::Dylib;
1051 cmd.gc_sections(keep_metadata);
1054 let used_link_args = &codegen_results.crate_info.link_args;
1056 if crate_type == config::CrateType::Executable {
1057 let mut position_independent_executable = false;
1059 if t.options.position_independent_executables {
1060 let empty_vec = Vec::new();
1061 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1062 let more_args = &sess.opts.cg.link_arg;
1063 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1065 if is_pic(sess) && !sess.crt_static() && !args.any(|x| *x == "-static") {
1066 position_independent_executable = true;
1070 if position_independent_executable {
1071 cmd.position_independent_executable();
1073 // recent versions of gcc can be configured to generate position
1074 // independent executables by default. We have to pass -no-pie to
1075 // explicitly turn that off. Not applicable to ld.
1076 if sess.target.target.options.linker_is_gnu
1077 && flavor != LinkerFlavor::Ld {
1078 cmd.no_position_independent_executable();
1083 let relro_level = match sess.opts.debugging_opts.relro_level {
1084 Some(level) => level,
1085 None => t.options.relro_level,
1088 RelroLevel::Full => {
1091 RelroLevel::Partial => {
1092 cmd.partial_relro();
1094 RelroLevel::Off => {
1097 RelroLevel::None => {
1101 // Pass optimization flags down to the linker.
1104 // Pass debuginfo flags down to the linker.
1107 // We want to, by default, prevent the compiler from accidentally leaking in
1108 // any system libraries, so we may explicitly ask linkers to not link to any
1109 // libraries by default. Note that this does not happen for windows because
1110 // windows pulls in some large number of libraries and I couldn't quite
1111 // figure out which subset we wanted.
1113 // This is all naturally configurable via the standard methods as well.
1114 if !sess.opts.cg.default_linker_libraries.unwrap_or(false) &&
1115 t.options.no_default_libraries
1117 cmd.no_default_libraries();
1120 // Take careful note of the ordering of the arguments we pass to the linker
1121 // here. Linkers will assume that things on the left depend on things to the
1122 // right. Things on the right cannot depend on things on the left. This is
1123 // all formally implemented in terms of resolving symbols (libs on the right
1124 // resolve unknown symbols of libs on the left, but not vice versa).
1126 // For this reason, we have organized the arguments we pass to the linker as
1129 // 1. The local object that LLVM just generated
1130 // 2. Local native libraries
1131 // 3. Upstream rust libraries
1132 // 4. Upstream native libraries
1134 // The rationale behind this ordering is that those items lower down in the
1135 // list can't depend on items higher up in the list. For example nothing can
1136 // depend on what we just generated (e.g., that'd be a circular dependency).
1137 // Upstream rust libraries are not allowed to depend on our local native
1138 // libraries as that would violate the structure of the DAG, in that
1139 // scenario they are required to link to them as well in a shared fashion.
1141 // Note that upstream rust libraries may contain native dependencies as
1142 // well, but they also can't depend on what we just started to add to the
1143 // link line. And finally upstream native libraries can't depend on anything
1144 // in this DAG so far because they're only dylibs and dylibs can only depend
1145 // on other dylibs (e.g., other native deps).
1146 add_local_native_libraries(cmd, sess, codegen_results);
1147 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1148 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1150 // Tell the linker what we're doing.
1151 if crate_type != config::CrateType::Executable {
1152 cmd.build_dylib(out_filename);
1154 if crate_type == config::CrateType::Executable && sess.crt_static() {
1155 cmd.build_static_executable();
1158 if sess.opts.debugging_opts.pgo_gen.enabled() {
1162 // FIXME (#2397): At some point we want to rpath our guesses as to
1163 // where extern libraries might live, based on the
1164 // addl_lib_search_paths
1165 if sess.opts.cg.rpath {
1166 let target_triple = sess.opts.target_triple.triple();
1167 let mut get_install_prefix_lib_path = || {
1168 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1169 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1170 let mut path = PathBuf::from(install_prefix);
1175 let mut rpath_config = RPathConfig {
1176 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1177 out_filename: out_filename.to_path_buf(),
1178 has_rpath: sess.target.target.options.has_rpath,
1179 is_like_osx: sess.target.target.options.is_like_osx,
1180 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1181 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1183 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1186 // Finally add all the linker arguments provided on the command line along
1187 // with any #[link_args] attributes found inside the crate
1188 if let Some(ref args) = sess.opts.cg.link_args {
1191 cmd.args(&sess.opts.cg.link_arg);
1192 cmd.args(&used_link_args);
1195 // # Native library linking
1197 // User-supplied library search paths (-L on the command line). These are
1198 // the same paths used to find Rust crates, so some of them may have been
1199 // added already by the previous crate linking code. This only allows them
1200 // to be found at compile time so it is still entirely up to outside
1201 // forces to make sure that library can be found at runtime.
1203 // Also note that the native libraries linked here are only the ones located
1204 // in the current crate. Upstream crates with native library dependencies
1205 // may have their native library pulled in above.
1206 pub fn add_local_native_libraries(cmd: &mut dyn Linker,
1208 codegen_results: &CodegenResults) {
1209 let filesearch = sess.target_filesearch(PathKind::All);
1210 for search_path in filesearch.search_paths() {
1211 match search_path.kind {
1212 PathKind::Framework => { cmd.framework_path(&search_path.dir); }
1213 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)); }
1217 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1218 relevant_lib(sess, l)
1221 let search_path = archive_search_paths(sess);
1222 for lib in relevant_libs {
1223 let name = match lib.name {
1228 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1229 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1230 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&name.as_str()),
1231 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&name.as_str(),
1237 // # Rust Crate linking
1239 // Rust crates are not considered at all when creating an rlib output. All
1240 // dependencies will be linked when producing the final output (instead of
1241 // the intermediate rlib version)
1242 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1244 codegen_results: &CodegenResults,
1245 crate_type: config::CrateType,
1247 // All of the heavy lifting has previously been accomplished by the
1248 // dependency_format module of the compiler. This is just crawling the
1249 // output of that module, adding crates as necessary.
1251 // Linking to a rlib involves just passing it to the linker (the linker
1252 // will slurp up the object files inside), and linking to a dynamic library
1253 // involves just passing the right -l flag.
1255 let formats = sess.dependency_formats.borrow();
1256 let data = formats.get(&crate_type).unwrap();
1258 // Invoke get_used_crates to ensure that we get a topological sorting of
1260 let deps = &codegen_results.crate_info.used_crates_dynamic;
1262 // There's a few internal crates in the standard library (aka libcore and
1263 // libstd) which actually have a circular dependence upon one another. This
1264 // currently arises through "weak lang items" where libcore requires things
1265 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1266 // circular dependence to work correctly in all situations we'll need to be
1267 // sure to correctly apply the `--start-group` and `--end-group` options to
1268 // GNU linkers, otherwise if we don't use any other symbol from the standard
1269 // library it'll get discarded and the whole application won't link.
1271 // In this loop we're calculating the `group_end`, after which crate to
1272 // pass `--end-group` and `group_start`, before which crate to pass
1273 // `--start-group`. We currently do this by passing `--end-group` after
1274 // the first crate (when iterating backwards) that requires a lang item
1275 // defined somewhere else. Once that's set then when we've defined all the
1276 // necessary lang items we'll pass `--start-group`.
1278 // Note that this isn't amazing logic for now but it should do the trick
1279 // for the current implementation of the standard library.
1280 let mut group_end = None;
1281 let mut group_start = None;
1282 let mut end_with = FxHashSet::default();
1283 let info = &codegen_results.crate_info;
1284 for &(cnum, _) in deps.iter().rev() {
1285 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1286 end_with.extend(missing.iter().cloned());
1287 if end_with.len() > 0 && group_end.is_none() {
1288 group_end = Some(cnum);
1291 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1292 if end_with.len() == 0 && group_end.is_some() {
1293 group_start = Some(cnum);
1298 // If we didn't end up filling in all lang items from upstream crates then
1299 // we'll be filling it in with our crate. This probably means we're the
1300 // standard library itself, so skip this for now.
1301 if group_end.is_some() && group_start.is_none() {
1305 let mut compiler_builtins = None;
1307 for &(cnum, _) in deps.iter() {
1308 if group_start == Some(cnum) {
1312 // We may not pass all crates through to the linker. Some crates may
1313 // appear statically in an existing dylib, meaning we'll pick up all the
1314 // symbols from the dylib.
1315 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1316 match data[cnum.as_usize() - 1] {
1317 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1318 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1320 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) => {
1321 link_sanitizer_runtime::<B>(cmd, sess, codegen_results, tmpdir, cnum);
1323 // compiler-builtins are always placed last to ensure that they're
1324 // linked correctly.
1325 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1326 assert!(compiler_builtins.is_none());
1327 compiler_builtins = Some(cnum);
1329 Linkage::NotLinked |
1330 Linkage::IncludedFromDylib => {}
1331 Linkage::Static => {
1332 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1334 Linkage::Dynamic => {
1335 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1339 if group_end == Some(cnum) {
1344 // compiler-builtins are always placed last to ensure that they're
1345 // linked correctly.
1346 // We must always link the `compiler_builtins` crate statically. Even if it
1347 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1349 if let Some(cnum) = compiler_builtins {
1350 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1353 // Converts a library file-stem into a cc -l argument
1354 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1355 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1362 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1363 // it's packed in a .rlib, it contains stuff that are not objects that will
1364 // make the linker error. So we must remove those bits from the .rlib before
1366 fn link_sanitizer_runtime<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1368 codegen_results: &CodegenResults,
1371 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1372 let cratepath = &src.rlib.as_ref().unwrap().0;
1374 if sess.target.target.options.is_like_osx {
1375 // On Apple platforms, the sanitizer is always built as a dylib, and
1376 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1377 // rpath to the library as well (the rpath should be absolute, see
1378 // PR #41352 for details).
1380 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1381 let rpath = cratepath.parent().unwrap();
1382 let rpath = rpath.to_str().expect("non-utf8 component in path");
1383 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1386 let dst = tmpdir.join(cratepath.file_name().unwrap());
1387 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1388 archive.update_symbols();
1390 for f in archive.src_files() {
1391 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1392 archive.remove_file(&f);
1398 cmd.link_whole_rlib(&dst);
1401 // Adds the static "rlib" versions of all crates to the command line.
1402 // There's a bit of magic which happens here specifically related to LTO and
1403 // dynamic libraries. Specifically:
1405 // * For LTO, we remove upstream object files.
1406 // * For dylibs we remove metadata and bytecode from upstream rlibs
1408 // When performing LTO, almost(*) all of the bytecode from the upstream
1409 // libraries has already been included in our object file output. As a
1410 // result we need to remove the object files in the upstream libraries so
1411 // the linker doesn't try to include them twice (or whine about duplicate
1412 // symbols). We must continue to include the rest of the rlib, however, as
1413 // it may contain static native libraries which must be linked in.
1415 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1416 // their bytecode wasn't included. The object files in those libraries must
1417 // still be passed to the linker.
1419 // When making a dynamic library, linkers by default don't include any
1420 // object files in an archive if they're not necessary to resolve the link.
1421 // We basically want to convert the archive (rlib) to a dylib, though, so we
1422 // *do* want everything included in the output, regardless of whether the
1423 // linker thinks it's needed or not. As a result we must use the
1424 // --whole-archive option (or the platform equivalent). When using this
1425 // option the linker will fail if there are non-objects in the archive (such
1426 // as our own metadata and/or bytecode). All in all, for rlibs to be
1427 // entirely included in dylibs, we need to remove all non-object files.
1429 // Note, however, that if we're not doing LTO or we're not producing a dylib
1430 // (aka we're making an executable), we can just pass the rlib blindly to
1431 // the linker (fast) because it's fine if it's not actually included as
1432 // we're at the end of the dependency chain.
1433 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1435 codegen_results: &CodegenResults,
1437 crate_type: config::CrateType,
1439 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1440 let cratepath = &src.rlib.as_ref().unwrap().0;
1442 // See the comment above in `link_staticlib` and `link_rlib` for why if
1443 // there's a static library that's not relevant we skip all object
1445 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1446 let skip_native = native_libs.iter().any(|lib| {
1447 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1450 if (!are_upstream_rust_objects_already_included(sess) ||
1451 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1452 crate_type != config::CrateType::Dylib &&
1454 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1458 let dst = tmpdir.join(cratepath.file_name().unwrap());
1459 let name = cratepath.file_name().unwrap().to_str().unwrap();
1460 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1462 time_ext(sess.time_extended(), Some(sess), &format!("altering {}.rlib", name), || {
1463 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1464 archive.update_symbols();
1466 let mut any_objects = false;
1467 for f in archive.src_files() {
1468 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1469 archive.remove_file(&f);
1473 let canonical = f.replace("-", "_");
1474 let canonical_name = name.replace("-", "_");
1476 // Look for `.rcgu.o` at the end of the filename to conclude
1477 // that this is a Rust-related object file.
1478 fn looks_like_rust(s: &str) -> bool {
1479 let path = Path::new(s);
1480 let ext = path.extension().and_then(|s| s.to_str());
1481 if ext != Some(OutputType::Object.extension()) {
1484 let ext2 = path.file_stem()
1485 .and_then(|s| Path::new(s).extension())
1486 .and_then(|s| s.to_str());
1487 ext2 == Some(RUST_CGU_EXT)
1490 let is_rust_object =
1491 canonical.starts_with(&canonical_name) &&
1492 looks_like_rust(&f);
1494 // If we've been requested to skip all native object files
1495 // (those not generated by the rust compiler) then we can skip
1496 // this file. See above for why we may want to do this.
1497 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1499 // If we're performing LTO and this is a rust-generated object
1500 // file, then we don't need the object file as it's part of the
1501 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1502 // though, so we let that object file slide.
1503 let skip_because_lto = are_upstream_rust_objects_already_included(sess) &&
1505 (sess.target.target.options.no_builtins ||
1506 !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1508 if skip_because_cfg_say_so || skip_because_lto {
1509 archive.remove_file(&f);
1520 // If we're creating a dylib, then we need to include the
1521 // whole of each object in our archive into that artifact. This is
1522 // because a `dylib` can be reused as an intermediate artifact.
1524 // Note, though, that we don't want to include the whole of a
1525 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1526 // repeatedly linked anyway.
1527 if crate_type == config::CrateType::Dylib &&
1528 codegen_results.crate_info.compiler_builtins != Some(cnum) {
1529 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1531 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1536 // Same thing as above, but for dynamic crates instead of static crates.
1537 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1538 // Just need to tell the linker about where the library lives and
1540 let parent = cratepath.parent();
1541 if let Some(dir) = parent {
1542 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1544 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1545 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1546 parent.unwrap_or(Path::new("")));
1550 // Link in all of our upstream crates' native dependencies. Remember that
1551 // all of these upstream native dependencies are all non-static
1552 // dependencies. We've got two cases then:
1554 // 1. The upstream crate is an rlib. In this case we *must* link in the
1555 // native dependency because the rlib is just an archive.
1557 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1558 // have the dependency present on the system somewhere. Thus, we don't
1559 // gain a whole lot from not linking in the dynamic dependency to this
1562 // The use case for this is a little subtle. In theory the native
1563 // dependencies of a crate are purely an implementation detail of the crate
1564 // itself, but the problem arises with generic and inlined functions. If a
1565 // generic function calls a native function, then the generic function must
1566 // be instantiated in the target crate, meaning that the native symbol must
1567 // also be resolved in the target crate.
1568 pub fn add_upstream_native_libraries(cmd: &mut dyn Linker,
1570 codegen_results: &CodegenResults,
1571 crate_type: config::CrateType) {
1572 // Be sure to use a topological sorting of crates because there may be
1573 // interdependencies between native libraries. When passing -nodefaultlibs,
1574 // for example, almost all native libraries depend on libc, so we have to
1575 // make sure that's all the way at the right (liblibc is near the base of
1576 // the dependency chain).
1578 // This passes RequireStatic, but the actual requirement doesn't matter,
1579 // we're just getting an ordering of crate numbers, we're not worried about
1581 let formats = sess.dependency_formats.borrow();
1582 let data = formats.get(&crate_type).unwrap();
1584 let crates = &codegen_results.crate_info.used_crates_static;
1585 for &(cnum, _) in crates {
1586 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1587 let name = match lib.name {
1591 if !relevant_lib(sess, &lib) {
1595 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1596 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1597 NativeLibraryKind::NativeStaticNobundle => {
1598 // Link "static-nobundle" native libs only if the crate they originate from
1599 // is being linked statically to the current crate. If it's linked dynamically
1600 // or is an rlib already included via some other dylib crate, the symbols from
1601 // native libs will have already been included in that dylib.
1602 if data[cnum.as_usize() - 1] == Linkage::Static {
1603 cmd.link_staticlib(&name.as_str())
1606 // ignore statically included native libraries here as we've
1607 // already included them when we included the rust library
1609 NativeLibraryKind::NativeStatic => {}
1615 pub fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1617 Some(ref cfg) => syntax::attr::cfg_matches(cfg, &sess.parse_sess, None),
1622 pub fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1624 config::Lto::Fat => true,
1625 config::Lto::Thin => {
1626 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1627 // any upstream object files have not been copied yet.
1628 !sess.opts.cg.linker_plugin_lto.enabled()
1631 config::Lto::ThinLocal => false,
1635 fn is_pic(sess: &Session) -> bool {
1636 let reloc_model_arg = match sess.opts.cg.relocation_model {
1637 Some(ref s) => &s[..],
1638 None => &sess.target.target.options.relocation_model[..],
1641 reloc_model_arg == "pic"