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 {CodegenResults, CrateInfo};
28 use rustc::util::common::time;
29 use rustc::util::fs::fix_windows_verbatim_for_gcc;
30 use rustc::hir::def_id::CrateNum;
31 use tempfile::{Builder as TempFileBuilder, TempDir};
32 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor};
33 use rustc_data_structures::fx::FxHashSet;
34 use context::get_reloc_model;
44 use std::path::{Path, PathBuf};
45 use std::process::{Output, Stdio};
49 /// The LLVM module name containing crate-metadata. This includes a `.` on
50 /// purpose, so it cannot clash with the name of a user-defined module.
51 pub const METADATA_MODULE_NAME: &'static str = "crate.metadata";
53 // same as for metadata above, but for allocator shim
54 pub const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator";
56 pub use rustc_codegen_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
57 invalid_output_for_target, build_link_meta, out_filename,
58 check_file_is_writeable};
60 // The third parameter is for env vars, used on windows to set up the
61 // path for MSVC to find its DLLs, and gcc to find its bundled
63 pub fn get_linker(sess: &Session) -> (PathBuf, Command) {
64 // If our linker looks like a batch script on Windows then to execute this
65 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
66 // emscripten where the linker is `emcc.bat` and needs to be spawned as
67 // `cmd /c emcc.bat ...`.
69 // This worked historically but is needed manually since #42436 (regression
70 // was tagged as #42791) and some more info can be found on #44443 for
72 let cmd = |linker: &Path| {
73 if let Some(linker) = linker.to_str() {
74 if cfg!(windows) && linker.ends_with(".bat") {
75 return Command::bat_script(linker)
78 match sess.linker_flavor() {
79 LinkerFlavor::Lld(f) => Command::lld(linker, f),
80 _ => Command::new(linker),
85 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
87 let linker_path = sess.opts.cg.linker.as_ref().map(|s| &**s)
88 .or(sess.target.target.options.linker.as_ref().map(|s| s.as_ref()))
89 .unwrap_or(match sess.linker_flavor() {
90 LinkerFlavor::Msvc => {
91 msvc_tool.as_ref().map(|t| t.path()).unwrap_or("link.exe".as_ref())
93 LinkerFlavor::Em if cfg!(windows) => "emcc.bat".as_ref(),
94 LinkerFlavor::Em => "emcc".as_ref(),
95 LinkerFlavor::Gcc => "cc".as_ref(),
96 LinkerFlavor::Ld => "ld".as_ref(),
97 LinkerFlavor::Lld(_) => "lld".as_ref(),
100 let mut cmd = cmd(linker_path);
102 // The compiler's sysroot often has some bundled tools, so add it to the
103 // PATH for the child.
104 let mut new_path = sess.host_filesearch(PathKind::All)
105 .get_tools_search_paths();
106 let mut msvc_changed_path = false;
107 if sess.target.target.options.is_like_msvc {
108 if let Some(ref tool) = msvc_tool {
109 cmd.args(tool.args());
110 for &(ref k, ref v) in tool.env() {
112 new_path.extend(env::split_paths(v));
113 msvc_changed_path = true;
121 if !msvc_changed_path {
122 if let Some(path) = env::var_os("PATH") {
123 new_path.extend(env::split_paths(&path));
126 cmd.env("PATH", env::join_paths(new_path).unwrap());
128 (linker_path.to_path_buf(), cmd)
131 pub fn remove(sess: &Session, path: &Path) {
132 match fs::remove_file(path) {
135 sess.err(&format!("failed to remove {}: {}",
142 /// Perform the linkage portion of the compilation phase. This will generate all
143 /// of the requested outputs for this compilation session.
144 pub(crate) fn link_binary(sess: &Session,
145 codegen_results: &CodegenResults,
146 outputs: &OutputFilenames,
147 crate_name: &str) -> Vec<PathBuf> {
148 let mut out_filenames = Vec::new();
149 for &crate_type in sess.crate_types.borrow().iter() {
150 // Ignore executable crates if we have -Z no-codegen, as they will error.
151 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
152 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen()) &&
154 crate_type == config::CrateType::Executable {
158 if invalid_output_for_target(sess, crate_type) {
159 bug!("invalid output type `{:?}` for target os `{}`",
160 crate_type, sess.opts.target_triple);
162 let mut out_files = link_binary_output(sess,
167 out_filenames.append(&mut out_files);
170 // Remove the temporary object file and metadata if we aren't saving temps
171 if !sess.opts.cg.save_temps {
172 if sess.opts.output_types.should_codegen() &&
173 !preserve_objects_for_their_debuginfo(sess)
175 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
179 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
182 if let Some(ref obj) = codegen_results.metadata_module.object {
185 if let Some(ref allocator) = codegen_results.allocator_module {
186 if let Some(ref obj) = allocator.object {
189 if let Some(ref bc) = allocator.bytecode_compressed {
198 /// Returns a boolean indicating whether we should preserve the object files on
199 /// the filesystem for their debug information. This is often useful with
200 /// split-dwarf like schemes.
201 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
202 // If the objects don't have debuginfo there's nothing to preserve.
203 if sess.opts.debuginfo == NoDebugInfo {
207 // If we're only producing artifacts that are archives, no need to preserve
208 // the objects as they're losslessly contained inside the archives.
209 let output_linked = sess.crate_types.borrow()
211 .any(|x| *x != config::CrateType::Rlib && *x != config::CrateType::Staticlib);
216 // If we're on OSX then the equivalent of split dwarf is turned on by
217 // default. The final executable won't actually have any debug information
218 // except it'll have pointers to elsewhere. Historically we've always run
219 // `dsymutil` to "link all the dwarf together" but this is actually sort of
220 // a bummer for incremental compilation! (the whole point of split dwarf is
221 // that you don't do this sort of dwarf link).
223 // Basically as a result this just means that if we're on OSX and we're
224 // *not* running dsymutil then the object files are the only source of truth
225 // for debug information, so we must preserve them.
226 if sess.target.target.options.is_like_osx {
227 match sess.opts.debugging_opts.run_dsymutil {
228 // dsymutil is not being run, preserve objects
229 Some(false) => return true,
231 // dsymutil is being run, no need to preserve the objects
232 Some(true) => return false,
234 // The default historical behavior was to always run dsymutil, so
235 // we're preserving that temporarily, but we're likely to switch the
237 None => return false,
244 fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilenames) -> PathBuf {
245 let out_filename = outputs.single_output_file.clone()
248 .join(&format!("lib{}{}.rmeta", crate_name, sess.opts.cg.extra_filename)));
249 check_file_is_writeable(&out_filename, sess);
253 pub(crate) fn each_linked_rlib(sess: &Session,
255 f: &mut dyn FnMut(CrateNum, &Path)) -> Result<(), String> {
256 let crates = info.used_crates_static.iter();
257 let fmts = sess.dependency_formats.borrow();
258 let fmts = fmts.get(&config::CrateType::Executable)
259 .or_else(|| fmts.get(&config::CrateType::Staticlib))
260 .or_else(|| fmts.get(&config::CrateType::Cdylib))
261 .or_else(|| fmts.get(&config::CrateType::ProcMacro));
262 let fmts = match fmts {
264 None => return Err("could not find formats for rlibs".to_string())
266 for &(cnum, ref path) in crates {
267 match fmts.get(cnum.as_usize() - 1) {
268 Some(&Linkage::NotLinked) |
269 Some(&Linkage::IncludedFromDylib) => continue,
271 None => return Err("could not find formats for rlibs".to_string())
273 let name = &info.crate_name[&cnum];
274 let path = match *path {
275 LibSource::Some(ref p) => p,
276 LibSource::MetadataOnly => {
277 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
281 return Err(format!("could not find rlib for: `{}`", name))
289 /// Returns a boolean indicating whether the specified crate should be ignored
292 /// Crates ignored during LTO are not lumped together in the "massive object
293 /// file" that we create and are linked in their normal rlib states. See
294 /// comments below for what crates do not participate in LTO.
296 /// It's unusual for a crate to not participate in LTO. Typically only
297 /// compiler-specific and unstable crates have a reason to not participate in
299 pub(crate) fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
300 // If our target enables builtin function lowering in LLVM then the
301 // crates providing these functions don't participate in LTO (e.g.
302 // no_builtins or compiler builtins crates).
303 !sess.target.target.options.no_builtins &&
304 (info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum))
307 fn link_binary_output(sess: &Session,
308 codegen_results: &CodegenResults,
309 crate_type: config::CrateType,
310 outputs: &OutputFilenames,
311 crate_name: &str) -> Vec<PathBuf> {
312 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
313 check_file_is_writeable(obj, sess);
316 let mut out_filenames = vec![];
318 if outputs.outputs.contains_key(&OutputType::Metadata) {
319 let out_filename = filename_for_metadata(sess, crate_name, outputs);
320 // To avoid races with another rustc process scanning the output directory,
321 // we need to write the file somewhere else and atomically move it to its
322 // final destination, with a `fs::rename` call. In order for the rename to
323 // always succeed, the temporary file needs to be on the same filesystem,
324 // which is why we create it inside the output directory specifically.
325 let metadata_tmpdir = match TempFileBuilder::new()
327 .tempdir_in(out_filename.parent().unwrap())
329 Ok(tmpdir) => tmpdir,
330 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
332 let metadata = emit_metadata(sess, codegen_results, &metadata_tmpdir);
333 if let Err(e) = fs::rename(metadata, &out_filename) {
334 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
336 out_filenames.push(out_filename);
339 let tmpdir = match TempFileBuilder::new().prefix("rustc").tempdir() {
340 Ok(tmpdir) => tmpdir,
341 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
344 if outputs.outputs.should_codegen() {
345 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
347 config::CrateType::Rlib => {
354 config::CrateType::Staticlib => {
355 link_staticlib(sess, codegen_results, &out_filename, &tmpdir);
358 link_natively(sess, crate_type, &out_filename, codegen_results, tmpdir.path());
361 out_filenames.push(out_filename);
364 if sess.opts.cg.save_temps {
365 let _ = tmpdir.into_path();
371 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
372 let mut search = Vec::new();
373 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
374 search.push(path.to_path_buf());
379 fn archive_config<'a>(sess: &'a Session,
381 input: Option<&Path>) -> ArchiveConfig<'a> {
384 dst: output.to_path_buf(),
385 src: input.map(|p| p.to_path_buf()),
386 lib_search_paths: archive_search_paths(sess),
390 /// We use a temp directory here to avoid races between concurrent rustc processes,
391 /// such as builds in the same directory using the same filename for metadata while
392 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
393 /// directory being searched for `extern crate` (observing an incomplete file).
394 /// The returned path is the temporary file containing the complete metadata.
395 fn emit_metadata<'a>(sess: &'a Session, codegen_results: &CodegenResults, tmpdir: &TempDir)
397 let out_filename = tmpdir.path().join(METADATA_FILENAME);
398 let result = fs::write(&out_filename, &codegen_results.metadata.raw_data);
400 if let Err(e) = result {
401 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
414 // An rlib in its current incarnation is essentially a renamed .a file. The
415 // rlib primarily contains the object file of the crate, but it also contains
416 // all of the object files from native libraries. This is done by unzipping
417 // native libraries and inserting all of the contents into this archive.
418 fn link_rlib<'a>(sess: &'a Session,
419 codegen_results: &CodegenResults,
422 tmpdir: &TempDir) -> ArchiveBuilder<'a> {
423 info!("preparing rlib to {:?}", out_filename);
424 let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
426 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
430 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
431 // we may not be configured to actually include a static library if we're
432 // adding it here. That's because later when we consume this rlib we'll
433 // decide whether we actually needed the static library or not.
435 // To do this "correctly" we'd need to keep track of which libraries added
436 // which object files to the archive. We don't do that here, however. The
437 // #[link(cfg(..))] feature is unstable, though, and only intended to get
438 // liblibc working. In that sense the check below just indicates that if
439 // there are any libraries we want to omit object files for at link time we
440 // just exclude all custom object files.
442 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
443 // feature then we'll need to figure out how to record what objects were
444 // loaded from the libraries found here and then encode that into the
445 // metadata of the rlib we're generating somehow.
446 for lib in codegen_results.crate_info.used_libraries.iter() {
448 NativeLibraryKind::NativeStatic => {}
449 NativeLibraryKind::NativeStaticNobundle |
450 NativeLibraryKind::NativeFramework |
451 NativeLibraryKind::NativeUnknown => continue,
453 if let Some(name) = lib.name {
454 ab.add_native_library(&name.as_str());
458 // After adding all files to the archive, we need to update the
459 // symbol table of the archive.
462 // Note that it is important that we add all of our non-object "magical
463 // files" *after* all of the object files in the archive. The reason for
464 // this is as follows:
466 // * When performing LTO, this archive will be modified to remove
467 // objects from above. The reason for this is described below.
469 // * When the system linker looks at an archive, it will attempt to
470 // determine the architecture of the archive in order to see whether its
473 // The algorithm for this detection is: iterate over the files in the
474 // archive. Skip magical SYMDEF names. Interpret the first file as an
475 // object file. Read architecture from the object file.
477 // * As one can probably see, if "metadata" and "foo.bc" were placed
478 // before all of the objects, then the architecture of this archive would
479 // not be correctly inferred once 'foo.o' is removed.
481 // Basically, all this means is that this code should not move above the
484 RlibFlavor::Normal => {
485 // Instead of putting the metadata in an object file section, rlibs
486 // contain the metadata in a separate file.
487 ab.add_file(&emit_metadata(sess, codegen_results, tmpdir));
489 // For LTO purposes, the bytecode of this library is also inserted
491 for bytecode in codegen_results
494 .filter_map(|m| m.bytecode_compressed.as_ref())
496 ab.add_file(bytecode);
499 // After adding all files to the archive, we need to update the
500 // symbol table of the archive. This currently dies on macOS (see
501 // #11162), and isn't necessary there anyway
502 if !sess.target.target.options.is_like_osx {
507 RlibFlavor::StaticlibBase => {
508 let obj = codegen_results.allocator_module
510 .and_then(|m| m.object.as_ref());
511 if let Some(obj) = obj {
520 // Create a static archive
522 // This is essentially the same thing as an rlib, but it also involves adding
523 // all of the upstream crates' objects into the archive. This will slurp in
524 // all of the native libraries of upstream dependencies as well.
526 // Additionally, there's no way for us to link dynamic libraries, so we warn
527 // about all dynamic library dependencies that they're not linked in.
529 // There's no need to include metadata in a static archive, so ensure to not
530 // link in the metadata object file (and also don't prepare the archive with a
532 fn link_staticlib(sess: &Session,
533 codegen_results: &CodegenResults,
536 let mut ab = link_rlib(sess,
538 RlibFlavor::StaticlibBase,
541 let mut all_native_libs = vec![];
543 let res = each_linked_rlib(sess, &codegen_results.crate_info, &mut |cnum, path| {
544 let name = &codegen_results.crate_info.crate_name[&cnum];
545 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
547 // Here when we include the rlib into our staticlib we need to make a
548 // decision whether to include the extra object files along the way.
549 // These extra object files come from statically included native
550 // libraries, but they may be cfg'd away with #[link(cfg(..))].
552 // This unstable feature, though, only needs liblibc to work. The only
553 // use case there is where musl is statically included in liblibc.rlib,
554 // so if we don't want the included version we just need to skip it. As
555 // a result the logic here is that if *any* linked library is cfg'd away
556 // we just skip all object files.
558 // Clearly this is not sufficient for a general purpose feature, and
559 // we'd want to read from the library's metadata to determine which
560 // object files come from where and selectively skip them.
561 let skip_object_files = native_libs.iter().any(|lib| {
562 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
566 is_full_lto_enabled(sess) &&
567 !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
568 skip_object_files).unwrap();
570 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
572 if let Err(e) = res {
579 if !all_native_libs.is_empty() {
580 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
581 print_native_static_libs(sess, &all_native_libs);
586 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
587 let lib_args: Vec<_> = all_native_libs.iter()
588 .filter(|l| relevant_lib(sess, l))
590 let name = lib.name?;
592 NativeLibraryKind::NativeStaticNobundle |
593 NativeLibraryKind::NativeUnknown => {
594 if sess.target.target.options.is_like_msvc {
595 Some(format!("{}.lib", name))
597 Some(format!("-l{}", name))
600 NativeLibraryKind::NativeFramework => {
601 // ld-only syntax, since there are no frameworks in MSVC
602 Some(format!("-framework {}", name))
604 // These are included, no need to print them
605 NativeLibraryKind::NativeStatic => None,
609 if !lib_args.is_empty() {
610 sess.note_without_error("Link against the following native artifacts when linking \
611 against this static library. The order and any duplication \
612 can be significant on some platforms.");
613 // Prefix for greppability
614 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
618 // Create a dynamic library or executable
620 // This will invoke the system linker/cc to create the resulting file. This
621 // links to all upstream files as well.
622 fn link_natively(sess: &Session,
623 crate_type: config::CrateType,
625 codegen_results: &CodegenResults,
627 info!("preparing {:?} to {:?}", crate_type, out_filename);
628 let flavor = sess.linker_flavor();
630 // The invocations of cc share some flags across platforms
631 let (pname, mut cmd) = get_linker(sess);
633 let root = sess.target_filesearch(PathKind::Native).get_lib_path();
634 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
637 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
638 if sess.crt_static() {
642 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
645 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
647 let pre_link_objects = if crate_type == config::CrateType::Executable {
648 &sess.target.target.options.pre_link_objects_exe
650 &sess.target.target.options.pre_link_objects_dll
652 for obj in pre_link_objects {
653 cmd.arg(root.join(obj));
656 if crate_type == config::CrateType::Executable && sess.crt_static() {
657 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
658 cmd.arg(root.join(obj));
662 if sess.target.target.options.is_like_emscripten {
664 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
665 "DISABLE_EXCEPTION_CATCHING=1"
667 "DISABLE_EXCEPTION_CATCHING=0"
672 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess);
673 link_args(&mut *linker, sess, crate_type, tmpdir,
674 out_filename, codegen_results);
675 cmd = linker.finalize();
677 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
680 for obj in &sess.target.target.options.post_link_objects {
681 cmd.arg(root.join(obj));
683 if sess.crt_static() {
684 for obj in &sess.target.target.options.post_link_objects_crt {
685 cmd.arg(root.join(obj));
688 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
691 for &(ref k, ref v) in &sess.target.target.options.link_env {
695 if sess.opts.debugging_opts.print_link_args {
696 println!("{:?}", &cmd);
699 // May have not found libraries in the right formats.
700 sess.abort_if_errors();
702 // Invoke the system linker
704 // Note that there's a terribly awful hack that really shouldn't be present
705 // in any compiler. Here an environment variable is supported to
706 // automatically retry the linker invocation if the linker looks like it
709 // Gee that seems odd, normally segfaults are things we want to know about!
710 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
711 // linker segfaulting on Travis quite a bit which is causing quite a bit of
712 // pain to land PRs when they spuriously fail due to a segfault.
714 // The issue #38878 has some more debugging information on it as well, but
715 // this unfortunately looks like it's just a race condition in macOS's linker
716 // with some thread pool working in the background. It seems that no one
717 // currently knows a fix for this so in the meantime we're left with this...
719 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
724 prog = time(sess, "running linker", || {
725 exec_linker(sess, &mut cmd, out_filename, tmpdir)
727 let output = match prog {
728 Ok(ref output) => output,
731 if output.status.success() {
734 let mut out = output.stderr.clone();
735 out.extend(&output.stdout);
736 let out = String::from_utf8_lossy(&out);
738 // Check to see if the link failed with "unrecognized command line option:
739 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
740 // reperform the link step without the -no-pie option. This is safe because
741 // if the linker doesn't support -no-pie then it should not default to
742 // linking executables as pie. Different versions of gcc seem to use
743 // different quotes in the error message so don't check for them.
744 if sess.target.target.options.linker_is_gnu &&
745 sess.linker_flavor() != LinkerFlavor::Ld &&
746 (out.contains("unrecognized command line option") ||
747 out.contains("unknown argument")) &&
748 out.contains("-no-pie") &&
749 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
750 info!("linker output: {:?}", out);
751 warn!("Linker does not support -no-pie command line option. Retrying without.");
752 for arg in cmd.take_args() {
753 if arg.to_string_lossy() != "-no-pie" {
760 if !retry_on_segfault || i > 3 {
763 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
764 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
765 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
770 "looks like the linker segfaulted when we tried to call it, \
771 automatically retrying again. cmd = {:?}, out = {}.",
779 fn escape_string(s: &[u8]) -> String {
780 str::from_utf8(s).map(|s| s.to_owned())
781 .unwrap_or_else(|_| {
782 let mut x = "Non-UTF-8 output: ".to_string();
784 .flat_map(|&b| ascii::escape_default(b))
785 .map(|b| char::from_u32(b as u32).unwrap()));
789 if !prog.status.success() {
790 let mut output = prog.stderr.clone();
791 output.extend_from_slice(&prog.stdout);
792 sess.struct_err(&format!("linking with `{}` failed: {}",
795 .note(&format!("{:?}", &cmd))
796 .note(&escape_string(&output))
798 sess.abort_if_errors();
800 info!("linker stderr:\n{}", escape_string(&prog.stderr));
801 info!("linker stdout:\n{}", escape_string(&prog.stdout));
804 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
806 let mut linker_error = {
807 if linker_not_found {
808 sess.struct_err(&format!("linker `{}` not found", pname.display()))
810 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
814 linker_error.note(&e.to_string());
816 if !linker_not_found {
817 linker_error.note(&format!("{:?}", &cmd));
822 if sess.target.target.options.is_like_msvc && linker_not_found {
823 sess.note_without_error("the msvc targets depend on the msvc linker \
824 but `link.exe` was not found");
825 sess.note_without_error("please ensure that VS 2013, VS 2015 or VS 2017 \
826 was installed with the Visual C++ option");
828 sess.abort_if_errors();
833 // On macOS, debuggers need this utility to get run to do some munging of
834 // the symbols. Note, though, that if the object files are being preserved
835 // for their debug information there's no need for us to run dsymutil.
836 if sess.target.target.options.is_like_osx &&
837 sess.opts.debuginfo != NoDebugInfo &&
838 !preserve_objects_for_their_debuginfo(sess)
840 match Command::new("dsymutil").arg(out_filename).output() {
842 Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
846 if sess.opts.target_triple.triple() == "wasm32-unknown-unknown" {
847 wasm::rewrite_imports(&out_filename, &codegen_results.crate_info.wasm_imports);
851 fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
852 -> io::Result<Output>
854 // When attempting to spawn the linker we run a risk of blowing out the
855 // size limits for spawning a new process with respect to the arguments
856 // we pass on the command line.
858 // Here we attempt to handle errors from the OS saying "your list of
859 // arguments is too big" by reinvoking the linker again with an `@`-file
860 // that contains all the arguments. The theory is that this is then
861 // accepted on all linkers and the linker will read all its options out of
862 // there instead of looking at the command line.
863 if !cmd.very_likely_to_exceed_some_spawn_limit() {
864 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
866 let output = child.wait_with_output();
867 flush_linked_file(&output, out_filename)?;
870 Err(ref e) if command_line_too_big(e) => {
871 info!("command line to linker was too big: {}", e);
873 Err(e) => return Err(e)
877 info!("falling back to passing arguments to linker via an @-file");
878 let mut cmd2 = cmd.clone();
879 let mut args = String::new();
880 for arg in cmd2.take_args() {
881 args.push_str(&Escape {
882 arg: arg.to_str().unwrap(),
883 is_like_msvc: sess.target.target.options.is_like_msvc,
887 let file = tmpdir.join("linker-arguments");
888 let bytes = if sess.target.target.options.is_like_msvc {
889 let mut out = Vec::with_capacity((1 + args.len()) * 2);
890 // start the stream with a UTF-16 BOM
891 for c in iter::once(0xFEFF).chain(args.encode_utf16()) {
892 // encode in little endian
894 out.push((c >> 8) as u8);
900 fs::write(&file, &bytes)?;
901 cmd2.arg(format!("@{}", file.display()));
902 info!("invoking linker {:?}", cmd2);
903 let output = cmd2.output();
904 flush_linked_file(&output, out_filename)?;
908 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
913 fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
916 // On Windows, under high I/O load, output buffers are sometimes not flushed,
917 // even long after process exit, causing nasty, non-reproducible output bugs.
919 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
921 // А full writeup of the original Chrome bug can be found at
922 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
924 if let &Ok(ref out) = command_output {
925 if out.status.success() {
926 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
936 fn command_line_too_big(err: &io::Error) -> bool {
937 err.raw_os_error() == Some(::libc::E2BIG)
941 fn command_line_too_big(err: &io::Error) -> bool {
942 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
943 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
951 impl<'a> fmt::Display for Escape<'a> {
952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 if self.is_like_msvc {
954 // This is "documented" at
955 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
957 // Unfortunately there's not a great specification of the
958 // syntax I could find online (at least) but some local
959 // testing showed that this seemed sufficient-ish to catch
960 // at least a few edge cases.
962 for c in self.arg.chars() {
964 '"' => write!(f, "\\{}", c)?,
965 c => write!(f, "{}", c)?,
970 // This is documented at https://linux.die.net/man/1/ld, namely:
972 // > Options in file are separated by whitespace. A whitespace
973 // > character may be included in an option by surrounding the
974 // > entire option in either single or double quotes. Any
975 // > character (including a backslash) may be included by
976 // > prefixing the character to be included with a backslash.
978 // We put an argument on each line, so all we need to do is
979 // ensure the line is interpreted as one whole argument.
980 for c in self.arg.chars() {
983 ' ' => write!(f, "\\{}", c)?,
984 c => write!(f, "{}", c)?,
993 fn link_args(cmd: &mut dyn Linker,
995 crate_type: config::CrateType,
998 codegen_results: &CodegenResults) {
1000 // Linker plugins should be specified early in the list of arguments
1001 cmd.cross_lang_lto();
1003 // The default library location, we need this to find the runtime.
1004 // The location of crates will be determined as needed.
1005 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1007 // target descriptor
1008 let t = &sess.target.target;
1010 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1011 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1012 cmd.add_object(obj);
1014 cmd.output_filename(out_filename);
1016 if crate_type == config::CrateType::Executable &&
1017 sess.target.target.options.is_like_windows {
1018 if let Some(ref s) = codegen_results.windows_subsystem {
1023 // If we're building a dynamic library then some platforms need to make sure
1024 // that all symbols are exported correctly from the dynamic library.
1025 if crate_type != config::CrateType::Executable ||
1026 sess.target.target.options.is_like_emscripten {
1027 cmd.export_symbols(tmpdir, crate_type);
1030 // When linking a dynamic library, we put the metadata into a section of the
1031 // executable. This metadata is in a separate object file from the main
1032 // object file, so we link that in here.
1033 if crate_type == config::CrateType::Dylib ||
1034 crate_type == config::CrateType::ProcMacro {
1035 if let Some(obj) = codegen_results.metadata_module.object.as_ref() {
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 get_reloc_model(sess) == llvm::RelocMode::PIC
1066 && !sess.crt_static() && !args.any(|x| *x == "-static") {
1067 position_independent_executable = true;
1071 if position_independent_executable {
1072 cmd.position_independent_executable();
1074 // recent versions of gcc can be configured to generate position
1075 // independent executables by default. We have to pass -no-pie to
1076 // explicitly turn that off. Not applicable to ld.
1077 if sess.target.target.options.linker_is_gnu
1078 && sess.linker_flavor() != LinkerFlavor::Ld {
1079 cmd.no_position_independent_executable();
1084 let relro_level = match sess.opts.debugging_opts.relro_level {
1085 Some(level) => level,
1086 None => t.options.relro_level,
1089 RelroLevel::Full => {
1092 RelroLevel::Partial => {
1093 cmd.partial_relro();
1095 RelroLevel::Off => {
1098 RelroLevel::None => {
1102 // Pass optimization flags down to the linker.
1105 // Pass debuginfo flags down to the linker.
1108 // We want to prevent the compiler from accidentally leaking in any system
1109 // libraries, so we explicitly ask gcc to not link to any libraries by
1110 // default. Note that this does not happen for windows because windows pulls
1111 // in some large number of libraries and I couldn't quite figure out which
1112 // subset we wanted.
1113 if t.options.no_default_libraries {
1114 cmd.no_default_libraries();
1117 // Take careful note of the ordering of the arguments we pass to the linker
1118 // here. Linkers will assume that things on the left depend on things to the
1119 // right. Things on the right cannot depend on things on the left. This is
1120 // all formally implemented in terms of resolving symbols (libs on the right
1121 // resolve unknown symbols of libs on the left, but not vice versa).
1123 // For this reason, we have organized the arguments we pass to the linker as
1126 // 1. The local object that LLVM just generated
1127 // 2. Local native libraries
1128 // 3. Upstream rust libraries
1129 // 4. Upstream native libraries
1131 // The rationale behind this ordering is that those items lower down in the
1132 // list can't depend on items higher up in the list. For example nothing can
1133 // depend on what we just generated (e.g. that'd be a circular dependency).
1134 // Upstream rust libraries are not allowed to depend on our local native
1135 // libraries as that would violate the structure of the DAG, in that
1136 // scenario they are required to link to them as well in a shared fashion.
1138 // Note that upstream rust libraries may contain native dependencies as
1139 // well, but they also can't depend on what we just started to add to the
1140 // link line. And finally upstream native libraries can't depend on anything
1141 // in this DAG so far because they're only dylibs and dylibs can only depend
1142 // on other dylibs (e.g. other native deps).
1143 add_local_native_libraries(cmd, sess, codegen_results);
1144 add_upstream_rust_crates(cmd, sess, codegen_results, crate_type, tmpdir);
1145 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1147 // Tell the linker what we're doing.
1148 if crate_type != config::CrateType::Executable {
1149 cmd.build_dylib(out_filename);
1151 if crate_type == config::CrateType::Executable && sess.crt_static() {
1152 cmd.build_static_executable();
1155 if sess.opts.debugging_opts.pgo_gen.is_some() {
1159 // FIXME (#2397): At some point we want to rpath our guesses as to
1160 // where extern libraries might live, based on the
1161 // addl_lib_search_paths
1162 if sess.opts.cg.rpath {
1163 let sysroot = sess.sysroot();
1164 let target_triple = sess.opts.target_triple.triple();
1165 let mut get_install_prefix_lib_path = || {
1166 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1167 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1168 let mut path = PathBuf::from(install_prefix);
1173 let mut rpath_config = RPathConfig {
1174 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1175 out_filename: out_filename.to_path_buf(),
1176 has_rpath: sess.target.target.options.has_rpath,
1177 is_like_osx: sess.target.target.options.is_like_osx,
1178 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1179 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1181 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1184 // Finally add all the linker arguments provided on the command line along
1185 // with any #[link_args] attributes found inside the crate
1186 if let Some(ref args) = sess.opts.cg.link_args {
1189 cmd.args(&sess.opts.cg.link_arg);
1190 cmd.args(&used_link_args);
1193 // # Native library linking
1195 // User-supplied library search paths (-L on the command line). These are
1196 // the same paths used to find Rust crates, so some of them may have been
1197 // added already by the previous crate linking code. This only allows them
1198 // to be found at compile time so it is still entirely up to outside
1199 // forces to make sure that library can be found at runtime.
1201 // Also note that the native libraries linked here are only the ones located
1202 // in the current crate. Upstream crates with native library dependencies
1203 // may have their native library pulled in above.
1204 fn add_local_native_libraries(cmd: &mut dyn Linker,
1206 codegen_results: &CodegenResults) {
1207 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1209 PathKind::Framework => { cmd.framework_path(path); }
1210 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1214 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1215 relevant_lib(sess, l)
1218 let search_path = archive_search_paths(sess);
1219 for lib in relevant_libs {
1220 let name = match lib.name {
1225 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1226 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1227 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&name.as_str()),
1228 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&name.as_str(),
1234 // # Rust Crate linking
1236 // Rust crates are not considered at all when creating an rlib output. All
1237 // dependencies will be linked when producing the final output (instead of
1238 // the intermediate rlib version)
1239 fn add_upstream_rust_crates(cmd: &mut dyn Linker,
1241 codegen_results: &CodegenResults,
1242 crate_type: config::CrateType,
1244 // All of the heavy lifting has previously been accomplished by the
1245 // dependency_format module of the compiler. This is just crawling the
1246 // output of that module, adding crates as necessary.
1248 // Linking to a rlib involves just passing it to the linker (the linker
1249 // will slurp up the object files inside), and linking to a dynamic library
1250 // involves just passing the right -l flag.
1252 let formats = sess.dependency_formats.borrow();
1253 let data = formats.get(&crate_type).unwrap();
1255 // Invoke get_used_crates to ensure that we get a topological sorting of
1257 let deps = &codegen_results.crate_info.used_crates_dynamic;
1259 // There's a few internal crates in the standard library (aka libcore and
1260 // libstd) which actually have a circular dependence upon one another. This
1261 // currently arises through "weak lang items" where libcore requires things
1262 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1263 // circular dependence to work correctly in all situations we'll need to be
1264 // sure to correctly apply the `--start-group` and `--end-group` options to
1265 // GNU linkers, otherwise if we don't use any other symbol from the standard
1266 // library it'll get discarded and the whole application won't link.
1268 // In this loop we're calculating the `group_end`, after which crate to
1269 // pass `--end-group` and `group_start`, before which crate to pass
1270 // `--start-group`. We currently do this by passing `--end-group` after
1271 // the first crate (when iterating backwards) that requires a lang item
1272 // defined somewhere else. Once that's set then when we've defined all the
1273 // necessary lang items we'll pass `--start-group`.
1275 // Note that this isn't amazing logic for now but it should do the trick
1276 // for the current implementation of the standard library.
1277 let mut group_end = None;
1278 let mut group_start = None;
1279 let mut end_with = FxHashSet();
1280 let info = &codegen_results.crate_info;
1281 for &(cnum, _) in deps.iter().rev() {
1282 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1283 end_with.extend(missing.iter().cloned());
1284 if end_with.len() > 0 && group_end.is_none() {
1285 group_end = Some(cnum);
1288 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1289 if end_with.len() == 0 && group_end.is_some() {
1290 group_start = Some(cnum);
1295 // If we didn't end up filling in all lang items from upstream crates then
1296 // we'll be filling it in with our crate. This probably means we're the
1297 // standard library itself, so skip this for now.
1298 if group_end.is_some() && group_start.is_none() {
1302 let mut compiler_builtins = None;
1304 for &(cnum, _) in deps.iter() {
1305 if group_start == Some(cnum) {
1309 // We may not pass all crates through to the linker. Some crates may
1310 // appear statically in an existing dylib, meaning we'll pick up all the
1311 // symbols from the dylib.
1312 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1313 match data[cnum.as_usize() - 1] {
1314 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1315 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1317 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) => {
1318 link_sanitizer_runtime(cmd, sess, codegen_results, tmpdir, cnum);
1320 // compiler-builtins are always placed last to ensure that they're
1321 // linked correctly.
1322 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1323 assert!(compiler_builtins.is_none());
1324 compiler_builtins = Some(cnum);
1326 Linkage::NotLinked |
1327 Linkage::IncludedFromDylib => {}
1328 Linkage::Static => {
1329 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1331 Linkage::Dynamic => {
1332 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1336 if group_end == Some(cnum) {
1341 // compiler-builtins are always placed last to ensure that they're
1342 // linked correctly.
1343 // We must always link the `compiler_builtins` crate statically. Even if it
1344 // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1346 if let Some(cnum) = compiler_builtins {
1347 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1350 // Converts a library file-stem into a cc -l argument
1351 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1352 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1359 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1360 // it's packed in a .rlib, it contains stuff that are not objects that will
1361 // make the linker error. So we must remove those bits from the .rlib before
1363 fn link_sanitizer_runtime(cmd: &mut dyn Linker,
1365 codegen_results: &CodegenResults,
1368 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1369 let cratepath = &src.rlib.as_ref().unwrap().0;
1371 if sess.target.target.options.is_like_osx {
1372 // On Apple platforms, the sanitizer is always built as a dylib, and
1373 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1374 // rpath to the library as well (the rpath should be absolute, see
1375 // PR #41352 for details).
1377 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1378 let rpath = cratepath.parent().unwrap();
1379 let rpath = rpath.to_str().expect("non-utf8 component in path");
1380 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1383 let dst = tmpdir.join(cratepath.file_name().unwrap());
1384 let cfg = archive_config(sess, &dst, Some(cratepath));
1385 let mut archive = ArchiveBuilder::new(cfg);
1386 archive.update_symbols();
1388 for f in archive.src_files() {
1389 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1390 archive.remove_file(&f);
1397 cmd.link_whole_rlib(&dst);
1400 // Adds the static "rlib" versions of all crates to the command line.
1401 // There's a bit of magic which happens here specifically related to LTO and
1402 // dynamic libraries. Specifically:
1404 // * For LTO, we remove upstream object files.
1405 // * For dylibs we remove metadata and bytecode from upstream rlibs
1407 // When performing LTO, almost(*) all of the bytecode from the upstream
1408 // libraries has already been included in our object file output. As a
1409 // result we need to remove the object files in the upstream libraries so
1410 // the linker doesn't try to include them twice (or whine about duplicate
1411 // symbols). We must continue to include the rest of the rlib, however, as
1412 // it may contain static native libraries which must be linked in.
1414 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1415 // their bytecode wasn't included. The object files in those libraries must
1416 // still be passed to the linker.
1418 // When making a dynamic library, linkers by default don't include any
1419 // object files in an archive if they're not necessary to resolve the link.
1420 // We basically want to convert the archive (rlib) to a dylib, though, so we
1421 // *do* want everything included in the output, regardless of whether the
1422 // linker thinks it's needed or not. As a result we must use the
1423 // --whole-archive option (or the platform equivalent). When using this
1424 // option the linker will fail if there are non-objects in the archive (such
1425 // as our own metadata and/or bytecode). All in all, for rlibs to be
1426 // entirely included in dylibs, we need to remove all non-object files.
1428 // Note, however, that if we're not doing LTO or we're not producing a dylib
1429 // (aka we're making an executable), we can just pass the rlib blindly to
1430 // the linker (fast) because it's fine if it's not actually included as
1431 // we're at the end of the dependency chain.
1432 fn add_static_crate(cmd: &mut dyn Linker,
1434 codegen_results: &CodegenResults,
1436 crate_type: config::CrateType,
1438 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1439 let cratepath = &src.rlib.as_ref().unwrap().0;
1441 // See the comment above in `link_staticlib` and `link_rlib` for why if
1442 // there's a static library that's not relevant we skip all object
1444 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1445 let skip_native = native_libs.iter().any(|lib| {
1446 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1449 if (!is_full_lto_enabled(sess) ||
1450 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1451 crate_type != config::CrateType::Dylib &&
1453 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1457 let dst = tmpdir.join(cratepath.file_name().unwrap());
1458 let name = cratepath.file_name().unwrap().to_str().unwrap();
1459 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1461 time(sess, &format!("altering {}.rlib", name), || {
1462 let cfg = archive_config(sess, &dst, Some(cratepath));
1463 let mut archive = ArchiveBuilder::new(cfg);
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 = is_full_lto_enabled(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 // If we're performing LTO, then it should have been previously required
1539 // that all upstream rust dependencies were available in an rlib format.
1540 assert!(!is_full_lto_enabled(sess));
1542 // Just need to tell the linker about where the library lives and
1544 let parent = cratepath.parent();
1545 if let Some(dir) = parent {
1546 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1548 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1549 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1550 parent.unwrap_or(Path::new("")));
1554 // Link in all of our upstream crates' native dependencies. Remember that
1555 // all of these upstream native dependencies are all non-static
1556 // dependencies. We've got two cases then:
1558 // 1. The upstream crate is an rlib. In this case we *must* link in the
1559 // native dependency because the rlib is just an archive.
1561 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1562 // have the dependency present on the system somewhere. Thus, we don't
1563 // gain a whole lot from not linking in the dynamic dependency to this
1566 // The use case for this is a little subtle. In theory the native
1567 // dependencies of a crate are purely an implementation detail of the crate
1568 // itself, but the problem arises with generic and inlined functions. If a
1569 // generic function calls a native function, then the generic function must
1570 // be instantiated in the target crate, meaning that the native symbol must
1571 // also be resolved in the target crate.
1572 fn add_upstream_native_libraries(cmd: &mut dyn Linker,
1574 codegen_results: &CodegenResults,
1575 crate_type: config::CrateType) {
1576 // Be sure to use a topological sorting of crates because there may be
1577 // interdependencies between native libraries. When passing -nodefaultlibs,
1578 // for example, almost all native libraries depend on libc, so we have to
1579 // make sure that's all the way at the right (liblibc is near the base of
1580 // the dependency chain).
1582 // This passes RequireStatic, but the actual requirement doesn't matter,
1583 // we're just getting an ordering of crate numbers, we're not worried about
1585 let formats = sess.dependency_formats.borrow();
1586 let data = formats.get(&crate_type).unwrap();
1588 let crates = &codegen_results.crate_info.used_crates_static;
1589 for &(cnum, _) in crates {
1590 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1591 let name = match lib.name {
1595 if !relevant_lib(sess, &lib) {
1599 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1600 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1601 NativeLibraryKind::NativeStaticNobundle => {
1602 // Link "static-nobundle" native libs only if the crate they originate from
1603 // is being linked statically to the current crate. If it's linked dynamically
1604 // or is an rlib already included via some other dylib crate, the symbols from
1605 // native libs will have already been included in that dylib.
1606 if data[cnum.as_usize() - 1] == Linkage::Static {
1607 cmd.link_staticlib(&name.as_str())
1610 // ignore statically included native libraries here as we've
1611 // already included them when we included the rust library
1613 NativeLibraryKind::NativeStatic => {}
1619 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1621 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1626 fn is_full_lto_enabled(sess: &Session) -> bool {
1632 Lto::ThinLocal => false,