1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use cc::windows_registry;
13 use super::archive::{ArchiveBuilder, ArchiveConfig};
14 use super::bytecode::RLIB_BYTECODE_EXTENSION;
15 use super::linker::Linker;
16 use super::command::Command;
17 use super::rpath::RPathConfig;
19 use metadata::METADATA_FILENAME;
20 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType, PrintRequest};
21 use rustc::session::config::{RUST_CGU_EXT, Lto};
22 use rustc::session::filesearch;
23 use rustc::session::search_paths::PathKind;
24 use rustc::session::Session;
25 use rustc::middle::cstore::{NativeLibrary, LibSource, NativeLibraryKind};
26 use rustc::middle::dependency_format::Linkage;
27 use {CrateTranslation, CrateInfo};
28 use rustc::util::common::time;
29 use rustc::util::fs::fix_windows_verbatim_for_gcc;
30 use rustc::hir::def_id::CrateNum;
32 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor, TargetTriple};
33 use rustc_data_structures::fx::FxHashSet;
34 use context::get_reloc_model;
43 use std::path::{Path, PathBuf};
44 use std::process::{Output, Stdio};
48 /// The LLVM module name containing crate-metadata. This includes a `.` on
49 /// purpose, so it cannot clash with the name of a user-defined module.
50 pub const METADATA_MODULE_NAME: &'static str = "crate.metadata";
52 // same as for metadata above, but for allocator shim
53 pub const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator";
55 pub use rustc_trans_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
56 invalid_output_for_target, build_link_meta, out_filename,
57 check_file_is_writeable};
59 // The third parameter is for env vars, used on windows to set up the
60 // path for MSVC to find its DLLs, and gcc to find its bundled
62 pub fn get_linker(sess: &Session) -> (PathBuf, Command) {
63 // If our linker looks like a batch script on Windows then to execute this
64 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
65 // emscripten where the linker is `emcc.bat` and needs to be spawned as
66 // `cmd /c emcc.bat ...`.
68 // This worked historically but is needed manually since #42436 (regression
69 // was tagged as #42791) and some more info can be found on #44443 for
71 let cmd = |linker: &Path| {
72 if let Some(linker) = linker.to_str() {
73 if cfg!(windows) && linker.ends_with(".bat") {
74 return Command::bat_script(linker)
77 match sess.linker_flavor() {
78 LinkerFlavor::Lld(f) => Command::lld(linker, f),
79 _ => Command::new(linker),
84 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
86 let linker_path = sess.opts.cg.linker.as_ref().map(|s| &**s)
87 .or(sess.target.target.options.linker.as_ref().map(|s| s.as_ref()))
88 .unwrap_or(match sess.linker_flavor() {
89 LinkerFlavor::Msvc => {
90 msvc_tool.as_ref().map(|t| t.path()).unwrap_or("link.exe".as_ref())
92 LinkerFlavor::Em if cfg!(windows) => "emcc.bat".as_ref(),
93 LinkerFlavor::Em => "emcc".as_ref(),
94 LinkerFlavor::Gcc => "cc".as_ref(),
95 LinkerFlavor::Ld => "ld".as_ref(),
96 LinkerFlavor::Lld(_) => "lld".as_ref(),
99 let mut cmd = cmd(linker_path);
101 // The compiler's sysroot often has some bundled tools, so add it to the
102 // PATH for the child.
103 let mut new_path = sess.host_filesearch(PathKind::All)
104 .get_tools_search_paths();
105 let mut msvc_changed_path = false;
106 if sess.target.target.options.is_like_msvc {
107 if let Some(ref tool) = msvc_tool {
108 cmd.args(tool.args());
109 for &(ref k, ref v) in tool.env() {
111 new_path.extend(env::split_paths(v));
112 msvc_changed_path = true;
120 if !msvc_changed_path {
121 if let Some(path) = env::var_os("PATH") {
122 new_path.extend(env::split_paths(&path));
125 cmd.env("PATH", env::join_paths(new_path).unwrap());
127 (linker_path.to_path_buf(), cmd)
130 pub fn remove(sess: &Session, path: &Path) {
131 match fs::remove_file(path) {
134 sess.err(&format!("failed to remove {}: {}",
141 /// Perform the linkage portion of the compilation phase. This will generate all
142 /// of the requested outputs for this compilation session.
143 pub(crate) fn link_binary(sess: &Session,
144 trans: &CrateTranslation,
145 outputs: &OutputFilenames,
146 crate_name: &str) -> Vec<PathBuf> {
147 let mut out_filenames = Vec::new();
148 for &crate_type in sess.crate_types.borrow().iter() {
149 // Ignore executable crates if we have -Z no-trans, as they will error.
150 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
151 if (sess.opts.debugging_opts.no_trans || !sess.opts.output_types.should_trans()) &&
153 crate_type == config::CrateTypeExecutable {
157 if invalid_output_for_target(sess, crate_type) {
158 bug!("invalid output type `{:?}` for target os `{}`",
159 crate_type, sess.opts.target_triple);
161 let mut out_files = link_binary_output(sess,
166 out_filenames.append(&mut out_files);
169 // Remove the temporary object file and metadata if we aren't saving temps
170 if !sess.opts.cg.save_temps {
171 if sess.opts.output_types.should_trans() &&
172 !preserve_objects_for_their_debuginfo(sess)
174 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
178 for obj in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
181 if let Some(ref obj) = trans.metadata_module.object {
184 if let Some(ref allocator) = trans.allocator_module {
185 if let Some(ref obj) = allocator.object {
188 if let Some(ref bc) = allocator.bytecode_compressed {
197 /// Returns a boolean indicating whether we should preserve the object files on
198 /// the filesystem for their debug information. This is often useful with
199 /// split-dwarf like schemes.
200 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
201 // If the objects don't have debuginfo there's nothing to preserve.
202 if sess.opts.debuginfo == NoDebugInfo {
206 // If we're only producing artifacts that are archives, no need to preserve
207 // the objects as they're losslessly contained inside the archives.
208 let output_linked = sess.crate_types.borrow()
210 .any(|x| *x != config::CrateTypeRlib && *x != config::CrateTypeStaticlib);
215 // If we're on OSX then the equivalent of split dwarf is turned on by
216 // default. The final executable won't actually have any debug information
217 // except it'll have pointers to elsewhere. Historically we've always run
218 // `dsymutil` to "link all the dwarf together" but this is actually sort of
219 // a bummer for incremental compilation! (the whole point of split dwarf is
220 // that you don't do this sort of dwarf link).
222 // Basically as a result this just means that if we're on OSX and we're
223 // *not* running dsymutil then the object files are the only source of truth
224 // for debug information, so we must preserve them.
225 if sess.target.target.options.is_like_osx {
226 match sess.opts.debugging_opts.run_dsymutil {
227 // dsymutil is not being run, preserve objects
228 Some(false) => return true,
230 // dsymutil is being run, no need to preserve the objects
231 Some(true) => return false,
233 // The default historical behavior was to always run dsymutil, so
234 // we're preserving that temporarily, but we're likely to switch the
236 None => return false,
243 fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilenames) -> PathBuf {
244 let out_filename = outputs.single_output_file.clone()
247 .join(&format!("lib{}{}.rmeta", crate_name, sess.opts.cg.extra_filename)));
248 check_file_is_writeable(&out_filename, sess);
252 pub(crate) fn each_linked_rlib(sess: &Session,
254 f: &mut FnMut(CrateNum, &Path)) -> Result<(), String> {
255 let crates = info.used_crates_static.iter();
256 let fmts = sess.dependency_formats.borrow();
257 let fmts = fmts.get(&config::CrateTypeExecutable)
258 .or_else(|| fmts.get(&config::CrateTypeStaticlib))
259 .or_else(|| fmts.get(&config::CrateTypeCdylib))
260 .or_else(|| fmts.get(&config::CrateTypeProcMacro));
261 let fmts = match fmts {
263 None => return Err(format!("could not find formats for rlibs"))
265 for &(cnum, ref path) in crates {
266 match fmts.get(cnum.as_usize() - 1) {
267 Some(&Linkage::NotLinked) |
268 Some(&Linkage::IncludedFromDylib) => continue,
270 None => return Err(format!("could not find formats for rlibs"))
272 let name = &info.crate_name[&cnum];
273 let path = match *path {
274 LibSource::Some(ref p) => p,
275 LibSource::MetadataOnly => {
276 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
280 return Err(format!("could not find rlib for: `{}`", name))
288 /// Returns a boolean indicating whether the specified crate should be ignored
291 /// Crates ignored during LTO are not lumped together in the "massive object
292 /// file" that we create and are linked in their normal rlib states. See
293 /// comments below for what crates do not participate in LTO.
295 /// It's unusual for a crate to not participate in LTO. Typically only
296 /// compiler-specific and unstable crates have a reason to not participate in
298 pub(crate) fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
299 // If our target enables builtin function lowering in LLVM then the
300 // crates providing these functions don't participate in LTO (e.g.
301 // no_builtins or compiler builtins crates).
302 !sess.target.target.options.no_builtins &&
303 (info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum))
306 fn link_binary_output(sess: &Session,
307 trans: &CrateTranslation,
308 crate_type: config::CrateType,
309 outputs: &OutputFilenames,
310 crate_name: &str) -> Vec<PathBuf> {
311 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
312 check_file_is_writeable(obj, sess);
315 let mut out_filenames = vec![];
317 if outputs.outputs.contains_key(&OutputType::Metadata) {
318 let out_filename = filename_for_metadata(sess, crate_name, outputs);
319 // To avoid races with another rustc process scanning the output directory,
320 // we need to write the file somewhere else and atomically move it to its
321 // final destination, with a `fs::rename` call. In order for the rename to
322 // always succeed, the temporary file needs to be on the same filesystem,
323 // which is why we create it inside the output directory specifically.
324 let metadata_tmpdir = match TempDir::new_in(out_filename.parent().unwrap(), "rmeta") {
325 Ok(tmpdir) => tmpdir,
326 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
328 let metadata = emit_metadata(sess, trans, &metadata_tmpdir);
329 if let Err(e) = fs::rename(metadata, &out_filename) {
330 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
332 out_filenames.push(out_filename);
335 let tmpdir = match TempDir::new("rustc") {
336 Ok(tmpdir) => tmpdir,
337 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
340 if outputs.outputs.should_trans() {
341 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
343 config::CrateTypeRlib => {
350 config::CrateTypeStaticlib => {
351 link_staticlib(sess, trans, &out_filename, &tmpdir);
354 link_natively(sess, crate_type, &out_filename, trans, tmpdir.path());
357 out_filenames.push(out_filename);
360 if sess.opts.cg.save_temps {
361 let _ = tmpdir.into_path();
367 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
368 let mut search = Vec::new();
369 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
370 search.push(path.to_path_buf());
375 fn archive_config<'a>(sess: &'a Session,
377 input: Option<&Path>) -> ArchiveConfig<'a> {
380 dst: output.to_path_buf(),
381 src: input.map(|p| p.to_path_buf()),
382 lib_search_paths: archive_search_paths(sess),
386 /// We use a temp directory here to avoid races between concurrent rustc processes,
387 /// such as builds in the same directory using the same filename for metadata while
388 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
389 /// directory being searched for `extern crate` (observing an incomplete file).
390 /// The returned path is the temporary file containing the complete metadata.
391 fn emit_metadata<'a>(sess: &'a Session, trans: &CrateTranslation, tmpdir: &TempDir)
393 let out_filename = tmpdir.path().join(METADATA_FILENAME);
394 let result = fs::write(&out_filename, &trans.metadata.raw_data);
396 if let Err(e) = result {
397 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
410 // An rlib in its current incarnation is essentially a renamed .a file. The
411 // rlib primarily contains the object file of the crate, but it also contains
412 // all of the object files from native libraries. This is done by unzipping
413 // native libraries and inserting all of the contents into this archive.
414 fn link_rlib<'a>(sess: &'a Session,
415 trans: &CrateTranslation,
418 tmpdir: &TempDir) -> ArchiveBuilder<'a> {
419 info!("preparing rlib to {:?}", out_filename);
420 let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
422 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
426 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
427 // we may not be configured to actually include a static library if we're
428 // adding it here. That's because later when we consume this rlib we'll
429 // decide whether we actually needed the static library or not.
431 // To do this "correctly" we'd need to keep track of which libraries added
432 // which object files to the archive. We don't do that here, however. The
433 // #[link(cfg(..))] feature is unstable, though, and only intended to get
434 // liblibc working. In that sense the check below just indicates that if
435 // there are any libraries we want to omit object files for at link time we
436 // just exclude all custom object files.
438 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
439 // feature then we'll need to figure out how to record what objects were
440 // loaded from the libraries found here and then encode that into the
441 // metadata of the rlib we're generating somehow.
442 for lib in trans.crate_info.used_libraries.iter() {
444 NativeLibraryKind::NativeStatic => {}
445 NativeLibraryKind::NativeStaticNobundle |
446 NativeLibraryKind::NativeFramework |
447 NativeLibraryKind::NativeUnknown => continue,
449 ab.add_native_library(&lib.name.as_str());
452 // After adding all files to the archive, we need to update the
453 // symbol table of the archive.
456 // Note that it is important that we add all of our non-object "magical
457 // files" *after* all of the object files in the archive. The reason for
458 // this is as follows:
460 // * When performing LTO, this archive will be modified to remove
461 // objects from above. The reason for this is described below.
463 // * When the system linker looks at an archive, it will attempt to
464 // determine the architecture of the archive in order to see whether its
467 // The algorithm for this detection is: iterate over the files in the
468 // archive. Skip magical SYMDEF names. Interpret the first file as an
469 // object file. Read architecture from the object file.
471 // * As one can probably see, if "metadata" and "foo.bc" were placed
472 // before all of the objects, then the architecture of this archive would
473 // not be correctly inferred once 'foo.o' is removed.
475 // Basically, all this means is that this code should not move above the
478 RlibFlavor::Normal => {
479 // Instead of putting the metadata in an object file section, rlibs
480 // contain the metadata in a separate file.
481 ab.add_file(&emit_metadata(sess, trans, tmpdir));
483 // For LTO purposes, the bytecode of this library is also inserted
485 for bytecode in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
486 ab.add_file(bytecode);
489 // After adding all files to the archive, we need to update the
490 // symbol table of the archive. This currently dies on macOS (see
491 // #11162), and isn't necessary there anyway
492 if !sess.target.target.options.is_like_osx {
497 RlibFlavor::StaticlibBase => {
498 let obj = trans.allocator_module
500 .and_then(|m| m.object.as_ref());
501 if let Some(obj) = obj {
510 // Create a static archive
512 // This is essentially the same thing as an rlib, but it also involves adding
513 // all of the upstream crates' objects into the archive. This will slurp in
514 // all of the native libraries of upstream dependencies as well.
516 // Additionally, there's no way for us to link dynamic libraries, so we warn
517 // about all dynamic library dependencies that they're not linked in.
519 // There's no need to include metadata in a static archive, so ensure to not
520 // link in the metadata object file (and also don't prepare the archive with a
522 fn link_staticlib(sess: &Session,
523 trans: &CrateTranslation,
526 let mut ab = link_rlib(sess,
528 RlibFlavor::StaticlibBase,
531 let mut all_native_libs = vec![];
533 let res = each_linked_rlib(sess, &trans.crate_info, &mut |cnum, path| {
534 let name = &trans.crate_info.crate_name[&cnum];
535 let native_libs = &trans.crate_info.native_libraries[&cnum];
537 // Here when we include the rlib into our staticlib we need to make a
538 // decision whether to include the extra object files along the way.
539 // These extra object files come from statically included native
540 // libraries, but they may be cfg'd away with #[link(cfg(..))].
542 // This unstable feature, though, only needs liblibc to work. The only
543 // use case there is where musl is statically included in liblibc.rlib,
544 // so if we don't want the included version we just need to skip it. As
545 // a result the logic here is that if *any* linked library is cfg'd away
546 // we just skip all object files.
548 // Clearly this is not sufficient for a general purpose feature, and
549 // we'd want to read from the library's metadata to determine which
550 // object files come from where and selectively skip them.
551 let skip_object_files = native_libs.iter().any(|lib| {
552 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
556 is_full_lto_enabled(sess) &&
557 !ignored_for_lto(sess, &trans.crate_info, cnum),
558 skip_object_files).unwrap();
560 all_native_libs.extend(trans.crate_info.native_libraries[&cnum].iter().cloned());
562 if let Err(e) = res {
569 if !all_native_libs.is_empty() {
570 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
571 print_native_static_libs(sess, &all_native_libs);
576 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
577 let lib_args: Vec<_> = all_native_libs.iter()
578 .filter(|l| relevant_lib(sess, l))
579 .filter_map(|lib| match lib.kind {
580 NativeLibraryKind::NativeStaticNobundle |
581 NativeLibraryKind::NativeUnknown => {
582 if sess.target.target.options.is_like_msvc {
583 Some(format!("{}.lib", lib.name))
585 Some(format!("-l{}", lib.name))
588 NativeLibraryKind::NativeFramework => {
589 // ld-only syntax, since there are no frameworks in MSVC
590 Some(format!("-framework {}", lib.name))
592 // These are included, no need to print them
593 NativeLibraryKind::NativeStatic => None,
596 if !lib_args.is_empty() {
597 sess.note_without_error("Link against the following native artifacts when linking \
598 against this static library. The order and any duplication \
599 can be significant on some platforms.");
600 // Prefix for greppability
601 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
605 // Create a dynamic library or executable
607 // This will invoke the system linker/cc to create the resulting file. This
608 // links to all upstream files as well.
609 fn link_natively(sess: &Session,
610 crate_type: config::CrateType,
612 trans: &CrateTranslation,
614 info!("preparing {:?} to {:?}", crate_type, out_filename);
615 let flavor = sess.linker_flavor();
617 // The invocations of cc share some flags across platforms
618 let (pname, mut cmd) = get_linker(sess);
620 let root = sess.target_filesearch(PathKind::Native).get_lib_path();
621 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
624 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
625 if sess.crt_static() {
629 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
632 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
634 let pre_link_objects = if crate_type == config::CrateTypeExecutable {
635 &sess.target.target.options.pre_link_objects_exe
637 &sess.target.target.options.pre_link_objects_dll
639 for obj in pre_link_objects {
640 cmd.arg(root.join(obj));
643 if crate_type == config::CrateTypeExecutable && sess.crt_static() {
644 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
645 cmd.arg(root.join(obj));
649 if sess.target.target.options.is_like_emscripten {
651 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
652 "DISABLE_EXCEPTION_CATCHING=1"
654 "DISABLE_EXCEPTION_CATCHING=0"
659 let mut linker = trans.linker_info.to_linker(cmd, &sess);
660 link_args(&mut *linker, sess, crate_type, tmpdir,
661 out_filename, trans);
662 cmd = linker.finalize();
664 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
667 for obj in &sess.target.target.options.post_link_objects {
668 cmd.arg(root.join(obj));
670 if sess.crt_static() {
671 for obj in &sess.target.target.options.post_link_objects_crt {
672 cmd.arg(root.join(obj));
675 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
678 for &(ref k, ref v) in &sess.target.target.options.link_env {
682 if sess.opts.debugging_opts.print_link_args {
683 println!("{:?}", &cmd);
686 // May have not found libraries in the right formats.
687 sess.abort_if_errors();
689 // Invoke the system linker
691 // Note that there's a terribly awful hack that really shouldn't be present
692 // in any compiler. Here an environment variable is supported to
693 // automatically retry the linker invocation if the linker looks like it
696 // Gee that seems odd, normally segfaults are things we want to know about!
697 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
698 // linker segfaulting on Travis quite a bit which is causing quite a bit of
699 // pain to land PRs when they spuriously fail due to a segfault.
701 // The issue #38878 has some more debugging information on it as well, but
702 // this unfortunately looks like it's just a race condition in macOS's linker
703 // with some thread pool working in the background. It seems that no one
704 // currently knows a fix for this so in the meantime we're left with this...
706 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
711 prog = time(sess, "running linker", || {
712 exec_linker(sess, &mut cmd, out_filename, tmpdir)
714 let output = match prog {
715 Ok(ref output) => output,
718 if output.status.success() {
721 let mut out = output.stderr.clone();
722 out.extend(&output.stdout);
723 let out = String::from_utf8_lossy(&out);
725 // Check to see if the link failed with "unrecognized command line option:
726 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
727 // reperform the link step without the -no-pie option. This is safe because
728 // if the linker doesn't support -no-pie then it should not default to
729 // linking executables as pie. Different versions of gcc seem to use
730 // different quotes in the error message so don't check for them.
731 if sess.target.target.options.linker_is_gnu &&
732 sess.linker_flavor() != LinkerFlavor::Ld &&
733 (out.contains("unrecognized command line option") ||
734 out.contains("unknown argument")) &&
735 out.contains("-no-pie") &&
736 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
737 info!("linker output: {:?}", out);
738 warn!("Linker does not support -no-pie command line option. Retrying without.");
739 for arg in cmd.take_args() {
740 if arg.to_string_lossy() != "-no-pie" {
747 if !retry_on_segfault || i > 3 {
750 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
751 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
752 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
757 "looks like the linker segfaulted when we tried to call it, \
758 automatically retrying again. cmd = {:?}, out = {}.",
766 fn escape_string(s: &[u8]) -> String {
767 str::from_utf8(s).map(|s| s.to_owned())
768 .unwrap_or_else(|_| {
769 let mut x = "Non-UTF-8 output: ".to_string();
771 .flat_map(|&b| ascii::escape_default(b))
772 .map(|b| char::from_u32(b as u32).unwrap()));
776 if !prog.status.success() {
777 let mut output = prog.stderr.clone();
778 output.extend_from_slice(&prog.stdout);
779 sess.struct_err(&format!("linking with `{}` failed: {}",
782 .note(&format!("{:?}", &cmd))
783 .note(&escape_string(&output))
785 sess.abort_if_errors();
787 info!("linker stderr:\n{}", escape_string(&prog.stderr));
788 info!("linker stdout:\n{}", escape_string(&prog.stdout));
791 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
793 let mut linker_error = {
794 if linker_not_found {
795 sess.struct_err(&format!("linker `{}` not found", pname.display()))
797 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
801 linker_error.note(&format!("{}", e));
803 if !linker_not_found {
804 linker_error.note(&format!("{:?}", &cmd));
809 if sess.target.target.options.is_like_msvc && linker_not_found {
810 sess.note_without_error("the msvc targets depend on the msvc linker \
811 but `link.exe` was not found");
812 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
813 with the Visual C++ option");
815 sess.abort_if_errors();
820 // On macOS, debuggers need this utility to get run to do some munging of
821 // the symbols. Note, though, that if the object files are being preserved
822 // for their debug information there's no need for us to run dsymutil.
823 if sess.target.target.options.is_like_osx &&
824 sess.opts.debuginfo != NoDebugInfo &&
825 !preserve_objects_for_their_debuginfo(sess)
827 match Command::new("dsymutil").arg(out_filename).output() {
829 Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
833 if sess.opts.target_triple == TargetTriple::from_triple("wasm32-unknown-unknown") {
834 wasm::rewrite_imports(&out_filename, &trans.crate_info.wasm_imports);
835 wasm::add_custom_sections(&out_filename,
836 &trans.crate_info.wasm_custom_sections);
840 fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
841 -> io::Result<Output>
843 // When attempting to spawn the linker we run a risk of blowing out the
844 // size limits for spawning a new process with respect to the arguments
845 // we pass on the command line.
847 // Here we attempt to handle errors from the OS saying "your list of
848 // arguments is too big" by reinvoking the linker again with an `@`-file
849 // that contains all the arguments. The theory is that this is then
850 // accepted on all linkers and the linker will read all its options out of
851 // there instead of looking at the command line.
852 if !cmd.very_likely_to_exceed_some_spawn_limit() {
853 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
855 let output = child.wait_with_output();
856 flush_linked_file(&output, out_filename)?;
859 Err(ref e) if command_line_too_big(e) => {
860 info!("command line to linker was too big: {}", e);
862 Err(e) => return Err(e)
866 info!("falling back to passing arguments to linker via an @-file");
867 let mut cmd2 = cmd.clone();
868 let mut args = String::new();
869 for arg in cmd2.take_args() {
870 args.push_str(&Escape {
871 arg: arg.to_str().unwrap(),
872 is_like_msvc: sess.target.target.options.is_like_msvc,
876 let file = tmpdir.join("linker-arguments");
877 let bytes = if sess.target.target.options.is_like_msvc {
878 let mut out = vec![];
879 // start the stream with a UTF-16 BOM
880 for c in vec![0xFEFF].into_iter().chain(args.encode_utf16()) {
881 // encode in little endian
883 out.push((c >> 8) as u8);
889 fs::write(&file, &bytes)?;
890 cmd2.arg(format!("@{}", file.display()));
891 info!("invoking linker {:?}", cmd2);
892 let output = cmd2.output();
893 flush_linked_file(&output, out_filename)?;
897 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
902 fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
905 // On Windows, under high I/O load, output buffers are sometimes not flushed,
906 // even long after process exit, causing nasty, non-reproducible output bugs.
908 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
910 // А full writeup of the original Chrome bug can be found at
911 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
913 if let &Ok(ref out) = command_output {
914 if out.status.success() {
915 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
925 fn command_line_too_big(err: &io::Error) -> bool {
926 err.raw_os_error() == Some(::libc::E2BIG)
930 fn command_line_too_big(err: &io::Error) -> bool {
931 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
932 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
940 impl<'a> fmt::Display for Escape<'a> {
941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
942 if self.is_like_msvc {
943 // This is "documented" at
944 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
946 // Unfortunately there's not a great specification of the
947 // syntax I could find online (at least) but some local
948 // testing showed that this seemed sufficient-ish to catch
949 // at least a few edge cases.
951 for c in self.arg.chars() {
953 '"' => write!(f, "\\{}", c)?,
954 c => write!(f, "{}", c)?,
959 // This is documented at https://linux.die.net/man/1/ld, namely:
961 // > Options in file are separated by whitespace. A whitespace
962 // > character may be included in an option by surrounding the
963 // > entire option in either single or double quotes. Any
964 // > character (including a backslash) may be included by
965 // > prefixing the character to be included with a backslash.
967 // We put an argument on each line, so all we need to do is
968 // ensure the line is interpreted as one whole argument.
969 for c in self.arg.chars() {
972 ' ' => write!(f, "\\{}", c)?,
973 c => write!(f, "{}", c)?,
982 fn link_args(cmd: &mut Linker,
984 crate_type: config::CrateType,
987 trans: &CrateTranslation) {
989 // The default library location, we need this to find the runtime.
990 // The location of crates will be determined as needed.
991 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
994 let t = &sess.target.target;
996 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
997 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
1000 cmd.output_filename(out_filename);
1002 if crate_type == config::CrateTypeExecutable &&
1003 sess.target.target.options.is_like_windows {
1004 if let Some(ref s) = trans.windows_subsystem {
1009 // If we're building a dynamic library then some platforms need to make sure
1010 // that all symbols are exported correctly from the dynamic library.
1011 if crate_type != config::CrateTypeExecutable ||
1012 sess.target.target.options.is_like_emscripten {
1013 cmd.export_symbols(tmpdir, crate_type);
1016 // When linking a dynamic library, we put the metadata into a section of the
1017 // executable. This metadata is in a separate object file from the main
1018 // object file, so we link that in here.
1019 if crate_type == config::CrateTypeDylib ||
1020 crate_type == config::CrateTypeProcMacro {
1021 if let Some(obj) = trans.metadata_module.object.as_ref() {
1022 cmd.add_object(obj);
1026 let obj = trans.allocator_module
1028 .and_then(|m| m.object.as_ref());
1029 if let Some(obj) = obj {
1030 cmd.add_object(obj);
1033 // Try to strip as much out of the generated object by removing unused
1034 // sections if possible. See more comments in linker.rs
1035 if !sess.opts.cg.link_dead_code {
1036 let keep_metadata = crate_type == config::CrateTypeDylib;
1037 cmd.gc_sections(keep_metadata);
1040 let used_link_args = &trans.crate_info.link_args;
1042 if crate_type == config::CrateTypeExecutable {
1043 let mut position_independent_executable = false;
1045 if t.options.position_independent_executables {
1046 let empty_vec = Vec::new();
1047 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1048 let more_args = &sess.opts.cg.link_arg;
1049 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1051 if get_reloc_model(sess) == llvm::RelocMode::PIC
1052 && !sess.crt_static() && !args.any(|x| *x == "-static") {
1053 position_independent_executable = true;
1057 if position_independent_executable {
1058 cmd.position_independent_executable();
1060 // recent versions of gcc can be configured to generate position
1061 // independent executables by default. We have to pass -no-pie to
1062 // explicitly turn that off. Not applicable to ld.
1063 if sess.target.target.options.linker_is_gnu
1064 && sess.linker_flavor() != LinkerFlavor::Ld {
1065 cmd.no_position_independent_executable();
1070 let relro_level = match sess.opts.debugging_opts.relro_level {
1071 Some(level) => level,
1072 None => t.options.relro_level,
1075 RelroLevel::Full => {
1078 RelroLevel::Partial => {
1079 cmd.partial_relro();
1081 RelroLevel::Off => {
1084 RelroLevel::None => {
1088 // Pass optimization flags down to the linker.
1091 // Pass debuginfo flags down to the linker.
1094 // We want to prevent the compiler from accidentally leaking in any system
1095 // libraries, so we explicitly ask gcc to not link to any libraries by
1096 // default. Note that this does not happen for windows because windows pulls
1097 // in some large number of libraries and I couldn't quite figure out which
1098 // subset we wanted.
1099 if t.options.no_default_libraries {
1100 cmd.no_default_libraries();
1103 // Take careful note of the ordering of the arguments we pass to the linker
1104 // here. Linkers will assume that things on the left depend on things to the
1105 // right. Things on the right cannot depend on things on the left. This is
1106 // all formally implemented in terms of resolving symbols (libs on the right
1107 // resolve unknown symbols of libs on the left, but not vice versa).
1109 // For this reason, we have organized the arguments we pass to the linker as
1112 // 1. The local object that LLVM just generated
1113 // 2. Local native libraries
1114 // 3. Upstream rust libraries
1115 // 4. Upstream native libraries
1117 // The rationale behind this ordering is that those items lower down in the
1118 // list can't depend on items higher up in the list. For example nothing can
1119 // depend on what we just generated (e.g. that'd be a circular dependency).
1120 // Upstream rust libraries are not allowed to depend on our local native
1121 // libraries as that would violate the structure of the DAG, in that
1122 // scenario they are required to link to them as well in a shared fashion.
1124 // Note that upstream rust libraries may contain native dependencies as
1125 // well, but they also can't depend on what we just started to add to the
1126 // link line. And finally upstream native libraries can't depend on anything
1127 // in this DAG so far because they're only dylibs and dylibs can only depend
1128 // on other dylibs (e.g. other native deps).
1129 add_local_native_libraries(cmd, sess, trans);
1130 add_upstream_rust_crates(cmd, sess, trans, crate_type, tmpdir);
1131 add_upstream_native_libraries(cmd, sess, trans, crate_type);
1133 // Tell the linker what we're doing.
1134 if crate_type != config::CrateTypeExecutable {
1135 cmd.build_dylib(out_filename);
1137 if crate_type == config::CrateTypeExecutable && sess.crt_static() {
1138 cmd.build_static_executable();
1141 if sess.opts.debugging_opts.pgo_gen.is_some() {
1145 // FIXME (#2397): At some point we want to rpath our guesses as to
1146 // where extern libraries might live, based on the
1147 // addl_lib_search_paths
1148 if sess.opts.cg.rpath {
1149 let sysroot = sess.sysroot();
1150 let target_triple = sess.opts.target_triple.triple();
1151 let mut get_install_prefix_lib_path = || {
1152 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1153 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1154 let mut path = PathBuf::from(install_prefix);
1159 let mut rpath_config = RPathConfig {
1160 used_crates: &trans.crate_info.used_crates_dynamic,
1161 out_filename: out_filename.to_path_buf(),
1162 has_rpath: sess.target.target.options.has_rpath,
1163 is_like_osx: sess.target.target.options.is_like_osx,
1164 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1165 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1167 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1170 // Finally add all the linker arguments provided on the command line along
1171 // with any #[link_args] attributes found inside the crate
1172 if let Some(ref args) = sess.opts.cg.link_args {
1175 cmd.args(&sess.opts.cg.link_arg);
1176 cmd.args(&used_link_args);
1179 // # Native library linking
1181 // User-supplied library search paths (-L on the command line). These are
1182 // the same paths used to find Rust crates, so some of them may have been
1183 // added already by the previous crate linking code. This only allows them
1184 // to be found at compile time so it is still entirely up to outside
1185 // forces to make sure that library can be found at runtime.
1187 // Also note that the native libraries linked here are only the ones located
1188 // in the current crate. Upstream crates with native library dependencies
1189 // may have their native library pulled in above.
1190 fn add_local_native_libraries(cmd: &mut Linker,
1192 trans: &CrateTranslation) {
1193 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1195 PathKind::Framework => { cmd.framework_path(path); }
1196 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1200 let relevant_libs = trans.crate_info.used_libraries.iter().filter(|l| {
1201 relevant_lib(sess, l)
1204 let search_path = archive_search_paths(sess);
1205 for lib in relevant_libs {
1207 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1208 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1209 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1210 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1216 // # Rust Crate linking
1218 // Rust crates are not considered at all when creating an rlib output. All
1219 // dependencies will be linked when producing the final output (instead of
1220 // the intermediate rlib version)
1221 fn add_upstream_rust_crates(cmd: &mut Linker,
1223 trans: &CrateTranslation,
1224 crate_type: config::CrateType,
1226 // All of the heavy lifting has previously been accomplished by the
1227 // dependency_format module of the compiler. This is just crawling the
1228 // output of that module, adding crates as necessary.
1230 // Linking to a rlib involves just passing it to the linker (the linker
1231 // will slurp up the object files inside), and linking to a dynamic library
1232 // involves just passing the right -l flag.
1234 let formats = sess.dependency_formats.borrow();
1235 let data = formats.get(&crate_type).unwrap();
1237 // Invoke get_used_crates to ensure that we get a topological sorting of
1239 let deps = &trans.crate_info.used_crates_dynamic;
1241 // There's a few internal crates in the standard library (aka libcore and
1242 // libstd) which actually have a circular dependence upon one another. This
1243 // currently arises through "weak lang items" where libcore requires things
1244 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1245 // circular dependence to work correctly in all situations we'll need to be
1246 // sure to correctly apply the `--start-group` and `--end-group` options to
1247 // GNU linkers, otherwise if we don't use any other symbol from the standard
1248 // library it'll get discarded and the whole application won't link.
1250 // In this loop we're calculating the `group_end`, after which crate to
1251 // pass `--end-group` and `group_start`, before which crate to pass
1252 // `--start-group`. We currently do this by passing `--end-group` after
1253 // the first crate (when iterating backwards) that requires a lang item
1254 // defined somewhere else. Once that's set then when we've defined all the
1255 // necessary lang items we'll pass `--start-group`.
1257 // Note that this isn't amazing logic for now but it should do the trick
1258 // for the current implementation of the standard library.
1259 let mut group_end = None;
1260 let mut group_start = None;
1261 let mut end_with = FxHashSet();
1262 let info = &trans.crate_info;
1263 for &(cnum, _) in deps.iter().rev() {
1264 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1265 end_with.extend(missing.iter().cloned());
1266 if end_with.len() > 0 && group_end.is_none() {
1267 group_end = Some(cnum);
1270 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1271 if end_with.len() == 0 && group_end.is_some() {
1272 group_start = Some(cnum);
1277 // If we didn't end up filling in all lang items from upstream crates then
1278 // we'll be filling it in with our crate. This probably means we're the
1279 // standard library itself, so skip this for now.
1280 if group_end.is_some() && group_start.is_none() {
1284 let mut compiler_builtins = None;
1286 for &(cnum, _) in deps.iter() {
1287 if group_start == Some(cnum) {
1291 // We may not pass all crates through to the linker. Some crates may
1292 // appear statically in an existing dylib, meaning we'll pick up all the
1293 // symbols from the dylib.
1294 let src = &trans.crate_info.used_crate_source[&cnum];
1295 match data[cnum.as_usize() - 1] {
1296 _ if trans.crate_info.profiler_runtime == Some(cnum) => {
1297 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1299 _ if trans.crate_info.sanitizer_runtime == Some(cnum) => {
1300 link_sanitizer_runtime(cmd, sess, trans, tmpdir, cnum);
1302 // compiler-builtins are always placed last to ensure that they're
1303 // linked correctly.
1304 _ if trans.crate_info.compiler_builtins == Some(cnum) => {
1305 assert!(compiler_builtins.is_none());
1306 compiler_builtins = Some(cnum);
1308 Linkage::NotLinked |
1309 Linkage::IncludedFromDylib => {}
1310 Linkage::Static => {
1311 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1313 Linkage::Dynamic => {
1314 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1318 if group_end == Some(cnum) {
1323 // compiler-builtins are always placed last to ensure that they're
1324 // linked correctly.
1325 // We must always link the `compiler_builtins` crate statically. Even if it
1326 // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1328 if let Some(cnum) = compiler_builtins {
1329 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1332 // Converts a library file-stem into a cc -l argument
1333 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1334 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1341 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1342 // it's packed in a .rlib, it contains stuff that are not objects that will
1343 // make the linker error. So we must remove those bits from the .rlib before
1345 fn link_sanitizer_runtime(cmd: &mut Linker,
1347 trans: &CrateTranslation,
1350 let src = &trans.crate_info.used_crate_source[&cnum];
1351 let cratepath = &src.rlib.as_ref().unwrap().0;
1353 if sess.target.target.options.is_like_osx {
1354 // On Apple platforms, the sanitizer is always built as a dylib, and
1355 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1356 // rpath to the library as well (the rpath should be absolute, see
1357 // PR #41352 for details).
1359 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1360 let rpath = cratepath.parent().unwrap();
1361 let rpath = rpath.to_str().expect("non-utf8 component in path");
1362 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1365 let dst = tmpdir.join(cratepath.file_name().unwrap());
1366 let cfg = archive_config(sess, &dst, Some(cratepath));
1367 let mut archive = ArchiveBuilder::new(cfg);
1368 archive.update_symbols();
1370 for f in archive.src_files() {
1371 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1372 archive.remove_file(&f);
1379 cmd.link_whole_rlib(&dst);
1382 // Adds the static "rlib" versions of all crates to the command line.
1383 // There's a bit of magic which happens here specifically related to LTO and
1384 // dynamic libraries. Specifically:
1386 // * For LTO, we remove upstream object files.
1387 // * For dylibs we remove metadata and bytecode from upstream rlibs
1389 // When performing LTO, almost(*) all of the bytecode from the upstream
1390 // libraries has already been included in our object file output. As a
1391 // result we need to remove the object files in the upstream libraries so
1392 // the linker doesn't try to include them twice (or whine about duplicate
1393 // symbols). We must continue to include the rest of the rlib, however, as
1394 // it may contain static native libraries which must be linked in.
1396 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1397 // their bytecode wasn't included. The object files in those libraries must
1398 // still be passed to the linker.
1400 // When making a dynamic library, linkers by default don't include any
1401 // object files in an archive if they're not necessary to resolve the link.
1402 // We basically want to convert the archive (rlib) to a dylib, though, so we
1403 // *do* want everything included in the output, regardless of whether the
1404 // linker thinks it's needed or not. As a result we must use the
1405 // --whole-archive option (or the platform equivalent). When using this
1406 // option the linker will fail if there are non-objects in the archive (such
1407 // as our own metadata and/or bytecode). All in all, for rlibs to be
1408 // entirely included in dylibs, we need to remove all non-object files.
1410 // Note, however, that if we're not doing LTO or we're not producing a dylib
1411 // (aka we're making an executable), we can just pass the rlib blindly to
1412 // the linker (fast) because it's fine if it's not actually included as
1413 // we're at the end of the dependency chain.
1414 fn add_static_crate(cmd: &mut Linker,
1416 trans: &CrateTranslation,
1418 crate_type: config::CrateType,
1420 let src = &trans.crate_info.used_crate_source[&cnum];
1421 let cratepath = &src.rlib.as_ref().unwrap().0;
1423 // See the comment above in `link_staticlib` and `link_rlib` for why if
1424 // there's a static library that's not relevant we skip all object
1426 let native_libs = &trans.crate_info.native_libraries[&cnum];
1427 let skip_native = native_libs.iter().any(|lib| {
1428 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1431 if (!is_full_lto_enabled(sess) ||
1432 ignored_for_lto(sess, &trans.crate_info, cnum)) &&
1433 crate_type != config::CrateTypeDylib &&
1435 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1439 let dst = tmpdir.join(cratepath.file_name().unwrap());
1440 let name = cratepath.file_name().unwrap().to_str().unwrap();
1441 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1443 time(sess, &format!("altering {}.rlib", name), || {
1444 let cfg = archive_config(sess, &dst, Some(cratepath));
1445 let mut archive = ArchiveBuilder::new(cfg);
1446 archive.update_symbols();
1448 let mut any_objects = false;
1449 for f in archive.src_files() {
1450 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1451 archive.remove_file(&f);
1455 let canonical = f.replace("-", "_");
1456 let canonical_name = name.replace("-", "_");
1458 // Look for `.rcgu.o` at the end of the filename to conclude
1459 // that this is a Rust-related object file.
1460 fn looks_like_rust(s: &str) -> bool {
1461 let path = Path::new(s);
1462 let ext = path.extension().and_then(|s| s.to_str());
1463 if ext != Some(OutputType::Object.extension()) {
1466 let ext2 = path.file_stem()
1467 .and_then(|s| Path::new(s).extension())
1468 .and_then(|s| s.to_str());
1469 ext2 == Some(RUST_CGU_EXT)
1472 let is_rust_object =
1473 canonical.starts_with(&canonical_name) &&
1474 looks_like_rust(&f);
1476 // If we've been requested to skip all native object files
1477 // (those not generated by the rust compiler) then we can skip
1478 // this file. See above for why we may want to do this.
1479 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1481 // If we're performing LTO and this is a rust-generated object
1482 // file, then we don't need the object file as it's part of the
1483 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1484 // though, so we let that object file slide.
1485 let skip_because_lto = is_full_lto_enabled(sess) &&
1487 (sess.target.target.options.no_builtins ||
1488 !trans.crate_info.is_no_builtins.contains(&cnum));
1490 if skip_because_cfg_say_so || skip_because_lto {
1491 archive.remove_file(&f);
1502 // If we're creating a dylib, then we need to include the
1503 // whole of each object in our archive into that artifact. This is
1504 // because a `dylib` can be reused as an intermediate artifact.
1506 // Note, though, that we don't want to include the whole of a
1507 // compiler-builtins crate (e.g. compiler-rt) because it'll get
1508 // repeatedly linked anyway.
1509 if crate_type == config::CrateTypeDylib &&
1510 trans.crate_info.compiler_builtins != Some(cnum) {
1511 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1513 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1518 // Same thing as above, but for dynamic crates instead of static crates.
1519 fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1520 // If we're performing LTO, then it should have been previously required
1521 // that all upstream rust dependencies were available in an rlib format.
1522 assert!(!is_full_lto_enabled(sess));
1524 // Just need to tell the linker about where the library lives and
1526 let parent = cratepath.parent();
1527 if let Some(dir) = parent {
1528 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1530 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1531 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1532 parent.unwrap_or(Path::new("")));
1536 // Link in all of our upstream crates' native dependencies. Remember that
1537 // all of these upstream native dependencies are all non-static
1538 // dependencies. We've got two cases then:
1540 // 1. The upstream crate is an rlib. In this case we *must* link in the
1541 // native dependency because the rlib is just an archive.
1543 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1544 // have the dependency present on the system somewhere. Thus, we don't
1545 // gain a whole lot from not linking in the dynamic dependency to this
1548 // The use case for this is a little subtle. In theory the native
1549 // dependencies of a crate are purely an implementation detail of the crate
1550 // itself, but the problem arises with generic and inlined functions. If a
1551 // generic function calls a native function, then the generic function must
1552 // be instantiated in the target crate, meaning that the native symbol must
1553 // also be resolved in the target crate.
1554 fn add_upstream_native_libraries(cmd: &mut Linker,
1556 trans: &CrateTranslation,
1557 crate_type: config::CrateType) {
1558 // Be sure to use a topological sorting of crates because there may be
1559 // interdependencies between native libraries. When passing -nodefaultlibs,
1560 // for example, almost all native libraries depend on libc, so we have to
1561 // make sure that's all the way at the right (liblibc is near the base of
1562 // the dependency chain).
1564 // This passes RequireStatic, but the actual requirement doesn't matter,
1565 // we're just getting an ordering of crate numbers, we're not worried about
1567 let formats = sess.dependency_formats.borrow();
1568 let data = formats.get(&crate_type).unwrap();
1570 let crates = &trans.crate_info.used_crates_static;
1571 for &(cnum, _) in crates {
1572 for lib in trans.crate_info.native_libraries[&cnum].iter() {
1573 if !relevant_lib(sess, &lib) {
1577 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1578 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1579 NativeLibraryKind::NativeStaticNobundle => {
1580 // Link "static-nobundle" native libs only if the crate they originate from
1581 // is being linked statically to the current crate. If it's linked dynamically
1582 // or is an rlib already included via some other dylib crate, the symbols from
1583 // native libs will have already been included in that dylib.
1584 if data[cnum.as_usize() - 1] == Linkage::Static {
1585 cmd.link_staticlib(&lib.name.as_str())
1588 // ignore statically included native libraries here as we've
1589 // already included them when we included the rust library
1591 NativeLibraryKind::NativeStatic => {}
1597 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1599 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1604 fn is_full_lto_enabled(sess: &Session) -> bool {
1610 Lto::ThinLocal => false,