1 /// For all the linkers we support, and information they might
2 /// need out of the shared crate context before we get rid of it.
4 use rustc::session::{Session, filesearch};
5 use rustc::session::config::{
6 self, RUST_CGU_EXT, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer
8 use rustc::session::search_paths::PathKind;
9 use rustc::middle::dependency_format::Linkage;
10 use rustc::middle::cstore::{EncodedMetadata, LibSource, NativeLibrary, NativeLibraryKind};
11 use rustc::util::common::{time, time_ext};
12 use rustc::hir::def_id::CrateNum;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_fs_util::fix_windows_verbatim_for_gcc;
15 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor};
17 use crate::{METADATA_FILENAME, RLIB_BYTECODE_EXTENSION, CrateInfo, CodegenResults};
18 use super::archive::ArchiveBuilder;
19 use super::command::Command;
20 use super::linker::Linker;
21 use super::rpath::{self, RPathConfig};
23 use cc::windows_registry;
24 use tempfile::{Builder as TempFileBuilder, TempDir};
31 use std::path::{Path, PathBuf};
32 use std::process::{Output, Stdio};
36 pub use rustc_codegen_utils::link::*;
38 pub fn remove(sess: &Session, path: &Path) {
39 if let Err(e) = fs::remove_file(path) {
40 sess.err(&format!("failed to remove {}: {}",
46 /// Performs the linkage portion of the compilation phase. This will generate all
47 /// of the requested outputs for this compilation session.
48 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
49 codegen_results: &CodegenResults,
50 outputs: &OutputFilenames,
53 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
54 for &crate_type in sess.crate_types.borrow().iter() {
55 // Ignore executable crates if we have -Z no-codegen, as they will error.
56 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen()) &&
58 crate_type == config::CrateType::Executable {
62 if invalid_output_for_target(sess, crate_type) {
63 bug!("invalid output type `{:?}` for target os `{}`",
64 crate_type, sess.opts.target_triple);
67 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
68 check_file_is_writeable(obj, sess);
71 let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err|
72 sess.fatal(&format!("couldn't create a temp dir: {}", err)));
74 if outputs.outputs.should_codegen() {
75 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
77 config::CrateType::Rlib => {
84 config::CrateType::Staticlib => {
85 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
98 if sess.opts.debugging_opts.emit_artifact_notifications {
99 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
103 if sess.opts.cg.save_temps {
104 let _ = tmpdir.into_path();
108 // Remove the temporary object file and metadata if we aren't saving temps
109 if !sess.opts.cg.save_temps {
110 if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) {
111 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
115 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
118 if let Some(ref metadata_module) = codegen_results.metadata_module {
119 if let Some(ref obj) = metadata_module.object {
123 if let Some(ref allocator_module) = codegen_results.allocator_module {
124 if let Some(ref obj) = allocator_module.object {
127 if let Some(ref bc) = allocator_module.bytecode_compressed {
134 // The third parameter is for env vars, used on windows to set up the
135 // path for MSVC to find its DLLs, and gcc to find its bundled
137 pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
138 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
140 // If our linker looks like a batch script on Windows then to execute this
141 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
142 // emscripten where the linker is `emcc.bat` and needs to be spawned as
143 // `cmd /c emcc.bat ...`.
145 // This worked historically but is needed manually since #42436 (regression
146 // was tagged as #42791) and some more info can be found on #44443 for
147 // emscripten itself.
148 let mut cmd = match linker.to_str() {
149 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
151 LinkerFlavor::Lld(f) => Command::lld(linker, f),
153 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
155 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
157 _ => Command::new(linker),
161 // The compiler's sysroot often has some bundled tools, so add it to the
162 // PATH for the child.
163 let mut new_path = sess.host_filesearch(PathKind::All)
164 .get_tools_search_paths();
165 let mut msvc_changed_path = false;
166 if sess.target.target.options.is_like_msvc {
167 if let Some(ref tool) = msvc_tool {
168 cmd.args(tool.args());
169 for &(ref k, ref v) in tool.env() {
171 new_path.extend(env::split_paths(v));
172 msvc_changed_path = true;
180 if !msvc_changed_path {
181 if let Some(path) = env::var_os("PATH") {
182 new_path.extend(env::split_paths(&path));
185 cmd.env("PATH", env::join_paths(new_path).unwrap());
187 (linker.to_path_buf(), cmd)
190 pub fn each_linked_rlib(sess: &Session,
192 f: &mut dyn FnMut(CrateNum, &Path)) -> Result<(), String> {
193 let crates = info.used_crates_static.iter();
194 let fmts = sess.dependency_formats.borrow();
195 let fmts = fmts.get(&config::CrateType::Executable)
196 .or_else(|| fmts.get(&config::CrateType::Staticlib))
197 .or_else(|| fmts.get(&config::CrateType::Cdylib))
198 .or_else(|| fmts.get(&config::CrateType::ProcMacro));
199 let fmts = match fmts {
201 None => return Err("could not find formats for rlibs".to_string())
203 for &(cnum, ref path) in crates {
204 match fmts.get(cnum.as_usize() - 1) {
205 Some(&Linkage::NotLinked) |
206 Some(&Linkage::IncludedFromDylib) => continue,
208 None => return Err("could not find formats for rlibs".to_string())
210 let name = &info.crate_name[&cnum];
211 let path = match *path {
212 LibSource::Some(ref p) => p,
213 LibSource::MetadataOnly => {
214 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
218 return Err(format!("could not find rlib for: `{}`", name))
226 /// We use a temp directory here to avoid races between concurrent rustc processes,
227 /// such as builds in the same directory using the same filename for metadata while
228 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
229 /// directory being searched for `extern crate` (observing an incomplete file).
230 /// The returned path is the temporary file containing the complete metadata.
231 pub fn emit_metadata<'a>(
233 metadata: &EncodedMetadata,
236 let out_filename = tmpdir.path().join(METADATA_FILENAME);
237 let result = fs::write(&out_filename, &metadata.raw_data);
239 if let Err(e) = result {
240 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
248 // An rlib in its current incarnation is essentially a renamed .a file. The
249 // rlib primarily contains the object file of the crate, but it also contains
250 // all of the object files from native libraries. This is done by unzipping
251 // native libraries and inserting all of the contents into this archive.
252 fn link_rlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
253 codegen_results: &CodegenResults,
256 tmpdir: &TempDir) -> B {
257 info!("preparing rlib to {:?}", out_filename);
258 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
260 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
264 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
265 // we may not be configured to actually include a static library if we're
266 // adding it here. That's because later when we consume this rlib we'll
267 // decide whether we actually needed the static library or not.
269 // To do this "correctly" we'd need to keep track of which libraries added
270 // which object files to the archive. We don't do that here, however. The
271 // #[link(cfg(..))] feature is unstable, though, and only intended to get
272 // liblibc working. In that sense the check below just indicates that if
273 // there are any libraries we want to omit object files for at link time we
274 // just exclude all custom object files.
276 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
277 // feature then we'll need to figure out how to record what objects were
278 // loaded from the libraries found here and then encode that into the
279 // metadata of the rlib we're generating somehow.
280 for lib in codegen_results.crate_info.used_libraries.iter() {
282 NativeLibraryKind::NativeStatic => {}
283 NativeLibraryKind::NativeStaticNobundle |
284 NativeLibraryKind::NativeFramework |
285 NativeLibraryKind::NativeUnknown => continue,
287 if let Some(name) = lib.name {
288 ab.add_native_library(&name.as_str());
292 // After adding all files to the archive, we need to update the
293 // symbol table of the archive.
296 // Note that it is important that we add all of our non-object "magical
297 // files" *after* all of the object files in the archive. The reason for
298 // this is as follows:
300 // * When performing LTO, this archive will be modified to remove
301 // objects from above. The reason for this is described below.
303 // * When the system linker looks at an archive, it will attempt to
304 // determine the architecture of the archive in order to see whether its
307 // The algorithm for this detection is: iterate over the files in the
308 // archive. Skip magical SYMDEF names. Interpret the first file as an
309 // object file. Read architecture from the object file.
311 // * As one can probably see, if "metadata" and "foo.bc" were placed
312 // before all of the objects, then the architecture of this archive would
313 // not be correctly inferred once 'foo.o' is removed.
315 // Basically, all this means is that this code should not move above the
318 RlibFlavor::Normal => {
319 // Instead of putting the metadata in an object file section, rlibs
320 // contain the metadata in a separate file.
321 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
323 // For LTO purposes, the bytecode of this library is also inserted
325 for bytecode in codegen_results
328 .filter_map(|m| m.bytecode_compressed.as_ref())
330 ab.add_file(bytecode);
333 // After adding all files to the archive, we need to update the
334 // symbol table of the archive. This currently dies on macOS (see
335 // #11162), and isn't necessary there anyway
336 if !sess.target.target.options.is_like_osx {
341 RlibFlavor::StaticlibBase => {
342 let obj = codegen_results.allocator_module
344 .and_then(|m| m.object.as_ref());
345 if let Some(obj) = obj {
354 // Create a static archive
356 // This is essentially the same thing as an rlib, but it also involves adding
357 // all of the upstream crates' objects into the archive. This will slurp in
358 // all of the native libraries of upstream dependencies as well.
360 // Additionally, there's no way for us to link dynamic libraries, so we warn
361 // about all dynamic library dependencies that they're not linked in.
363 // There's no need to include metadata in a static archive, so ensure to not
364 // link in the metadata object file (and also don't prepare the archive with a
366 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
367 codegen_results: &CodegenResults,
370 let mut ab = link_rlib::<B>(sess,
372 RlibFlavor::StaticlibBase,
375 let mut all_native_libs = vec![];
377 let res = each_linked_rlib(sess, &codegen_results.crate_info, &mut |cnum, path| {
378 let name = &codegen_results.crate_info.crate_name[&cnum];
379 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
381 // Here when we include the rlib into our staticlib we need to make a
382 // decision whether to include the extra object files along the way.
383 // These extra object files come from statically included native
384 // libraries, but they may be cfg'd away with #[link(cfg(..))].
386 // This unstable feature, though, only needs liblibc to work. The only
387 // use case there is where musl is statically included in liblibc.rlib,
388 // so if we don't want the included version we just need to skip it. As
389 // a result the logic here is that if *any* linked library is cfg'd away
390 // we just skip all object files.
392 // Clearly this is not sufficient for a general purpose feature, and
393 // we'd want to read from the library's metadata to determine which
394 // object files come from where and selectively skip them.
395 let skip_object_files = native_libs.iter().any(|lib| {
396 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
400 are_upstream_rust_objects_already_included(sess) &&
401 !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
402 skip_object_files).unwrap();
404 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
406 if let Err(e) = res {
413 if !all_native_libs.is_empty() {
414 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
415 print_native_static_libs(sess, &all_native_libs);
420 // Create a dynamic library or executable
422 // This will invoke the system linker/cc to create the resulting file. This
423 // links to all upstream files as well.
424 fn link_natively<'a, B: ArchiveBuilder<'a>>(sess: &'a Session,
425 crate_type: config::CrateType,
427 codegen_results: &CodegenResults,
430 info!("preparing {:?} to {:?}", crate_type, out_filename);
431 let (linker, flavor) = linker_and_flavor(sess);
433 // The invocations of cc share some flags across platforms
434 let (pname, mut cmd) = get_linker(sess, &linker, flavor);
436 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
439 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
440 if sess.crt_static() {
444 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
447 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
449 if sess.target.target.options.is_like_fuchsia {
450 let prefix = match sess.opts.debugging_opts.sanitizer {
451 Some(Sanitizer::Address) => "asan/",
454 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
457 let pre_link_objects = if crate_type == config::CrateType::Executable {
458 &sess.target.target.options.pre_link_objects_exe
460 &sess.target.target.options.pre_link_objects_dll
462 for obj in pre_link_objects {
463 cmd.arg(get_file_path(sess, obj));
466 if crate_type == config::CrateType::Executable && sess.crt_static() {
467 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
468 cmd.arg(get_file_path(sess, obj));
472 if sess.target.target.options.is_like_emscripten {
474 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
475 "DISABLE_EXCEPTION_CATCHING=1"
477 "DISABLE_EXCEPTION_CATCHING=0"
482 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
483 link_args::<B>(&mut *linker, flavor, sess, crate_type, tmpdir,
484 out_filename, codegen_results);
485 cmd = linker.finalize();
487 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
490 for obj in &sess.target.target.options.post_link_objects {
491 cmd.arg(get_file_path(sess, obj));
493 if sess.crt_static() {
494 for obj in &sess.target.target.options.post_link_objects_crt {
495 cmd.arg(get_file_path(sess, obj));
498 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
501 for &(ref k, ref v) in &sess.target.target.options.link_env {
505 if sess.opts.debugging_opts.print_link_args {
506 println!("{:?}", &cmd);
509 // May have not found libraries in the right formats.
510 sess.abort_if_errors();
512 // Invoke the system linker
514 // Note that there's a terribly awful hack that really shouldn't be present
515 // in any compiler. Here an environment variable is supported to
516 // automatically retry the linker invocation if the linker looks like it
519 // Gee that seems odd, normally segfaults are things we want to know about!
520 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
521 // linker segfaulting on Travis quite a bit which is causing quite a bit of
522 // pain to land PRs when they spuriously fail due to a segfault.
524 // The issue #38878 has some more debugging information on it as well, but
525 // this unfortunately looks like it's just a race condition in macOS's linker
526 // with some thread pool working in the background. It seems that no one
527 // currently knows a fix for this so in the meantime we're left with this...
529 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
534 prog = time(sess, "running linker", || {
535 exec_linker(sess, &mut cmd, out_filename, tmpdir)
537 let output = match prog {
538 Ok(ref output) => output,
541 if output.status.success() {
544 let mut out = output.stderr.clone();
545 out.extend(&output.stdout);
546 let out = String::from_utf8_lossy(&out);
548 // Check to see if the link failed with "unrecognized command line option:
549 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
550 // reperform the link step without the -no-pie option. This is safe because
551 // if the linker doesn't support -no-pie then it should not default to
552 // linking executables as pie. Different versions of gcc seem to use
553 // different quotes in the error message so don't check for them.
554 if sess.target.target.options.linker_is_gnu &&
555 flavor != LinkerFlavor::Ld &&
556 (out.contains("unrecognized command line option") ||
557 out.contains("unknown argument")) &&
558 out.contains("-no-pie") &&
559 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
560 info!("linker output: {:?}", out);
561 warn!("Linker does not support -no-pie command line option. Retrying without.");
562 for arg in cmd.take_args() {
563 if arg.to_string_lossy() != "-no-pie" {
570 if !retry_on_segfault || i > 3 {
573 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
574 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
575 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
580 "looks like the linker segfaulted when we tried to call it, \
581 automatically retrying again. cmd = {:?}, out = {}.",
589 fn escape_string(s: &[u8]) -> String {
590 str::from_utf8(s).map(|s| s.to_owned())
591 .unwrap_or_else(|_| {
592 let mut x = "Non-UTF-8 output: ".to_string();
594 .flat_map(|&b| ascii::escape_default(b))
599 if !prog.status.success() {
600 let mut output = prog.stderr.clone();
601 output.extend_from_slice(&prog.stdout);
602 sess.struct_err(&format!("linking with `{}` failed: {}",
605 .note(&format!("{:?}", &cmd))
606 .note(&escape_string(&output))
608 sess.abort_if_errors();
610 info!("linker stderr:\n{}", escape_string(&prog.stderr));
611 info!("linker stdout:\n{}", escape_string(&prog.stdout));
614 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
616 let mut linker_error = {
617 if linker_not_found {
618 sess.struct_err(&format!("linker `{}` not found", pname.display()))
620 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
624 linker_error.note(&e.to_string());
626 if !linker_not_found {
627 linker_error.note(&format!("{:?}", &cmd));
632 if sess.target.target.options.is_like_msvc && linker_not_found {
633 sess.note_without_error("the msvc targets depend on the msvc linker \
634 but `link.exe` was not found");
635 sess.note_without_error("please ensure that VS 2013, VS 2015 or VS 2017 \
636 was installed with the Visual C++ option");
638 sess.abort_if_errors();
643 // On macOS, debuggers need this utility to get run to do some munging of
644 // the symbols. Note, though, that if the object files are being preserved
645 // for their debug information there's no need for us to run dsymutil.
646 if sess.target.target.options.is_like_osx &&
647 sess.opts.debuginfo != DebugInfo::None &&
648 !preserve_objects_for_their_debuginfo(sess)
650 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
651 sess.fatal(&format!("failed to run dsymutil: {}", e))
655 if sess.opts.target_triple.triple() == "wasm32-unknown-unknown" {
656 super::wasm::add_producer_section(
658 &sess.edition().to_string(),
659 option_env!("CFG_VERSION").unwrap_or("unknown"),
664 /// Returns a boolean indicating whether the specified crate should be ignored
667 /// Crates ignored during LTO are not lumped together in the "massive object
668 /// file" that we create and are linked in their normal rlib states. See
669 /// comments below for what crates do not participate in LTO.
671 /// It's unusual for a crate to not participate in LTO. Typically only
672 /// compiler-specific and unstable crates have a reason to not participate in
674 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
675 // If our target enables builtin function lowering in LLVM then the
676 // crates providing these functions don't participate in LTO (e.g.
677 // no_builtins or compiler builtins crates).
678 !sess.target.target.options.no_builtins &&
679 (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
682 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
685 linker: Option<PathBuf>,
686 flavor: Option<LinkerFlavor>,
687 ) -> Option<(PathBuf, LinkerFlavor)> {
688 match (linker, flavor) {
689 (Some(linker), Some(flavor)) => Some((linker, flavor)),
690 // only the linker flavor is known; use the default linker for the selected flavor
691 (None, Some(flavor)) => Some((PathBuf::from(match flavor {
692 LinkerFlavor::Em => if cfg!(windows) { "emcc.bat" } else { "emcc" },
693 LinkerFlavor::Gcc => "cc",
694 LinkerFlavor::Ld => "ld",
695 LinkerFlavor::Msvc => "link.exe",
696 LinkerFlavor::Lld(_) => "lld",
697 LinkerFlavor::PtxLinker => "rust-ptx-linker",
699 (Some(linker), None) => {
702 .and_then(|stem| stem.to_str())
704 sess.fatal("couldn't extract file stem from specified linker")
707 let flavor = if stem == "emcc" {
709 } else if stem == "gcc"
710 || stem.ends_with("-gcc")
712 || stem.ends_with("-clang")
715 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
717 } else if stem == "link" || stem == "lld-link" {
719 } else if stem == "lld" || stem == "rust-lld" {
720 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
722 // fall back to the value in the target spec
723 sess.target.target.linker_flavor
726 Some((linker, flavor))
728 (None, None) => None,
732 // linker and linker flavor specified via command line have precedence over what the target
733 // specification specifies
734 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
738 if let Some(ret) = infer_from(
740 sess.target.target.options.linker.clone().map(PathBuf::from),
741 Some(sess.target.target.linker_flavor),
746 bug!("Not enough information provided to determine how to invoke the linker");
749 /// Returns a boolean indicating whether we should preserve the object files on
750 /// the filesystem for their debug information. This is often useful with
751 /// split-dwarf like schemes.
752 pub fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
753 // If the objects don't have debuginfo there's nothing to preserve.
754 if sess.opts.debuginfo == config::DebugInfo::None {
758 // If we're only producing artifacts that are archives, no need to preserve
759 // the objects as they're losslessly contained inside the archives.
760 let output_linked = sess.crate_types.borrow()
762 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
767 // If we're on OSX then the equivalent of split dwarf is turned on by
768 // default. The final executable won't actually have any debug information
769 // except it'll have pointers to elsewhere. Historically we've always run
770 // `dsymutil` to "link all the dwarf together" but this is actually sort of
771 // a bummer for incremental compilation! (the whole point of split dwarf is
772 // that you don't do this sort of dwarf link).
774 // Basically as a result this just means that if we're on OSX and we're
775 // *not* running dsymutil then the object files are the only source of truth
776 // for debug information, so we must preserve them.
777 if sess.target.target.options.is_like_osx {
778 match sess.opts.debugging_opts.run_dsymutil {
779 // dsymutil is not being run, preserve objects
780 Some(false) => return true,
782 // dsymutil is being run, no need to preserve the objects
783 Some(true) => return false,
785 // The default historical behavior was to always run dsymutil, so
786 // we're preserving that temporarily, but we're likely to switch the
788 None => return false,
795 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
796 sess.target_filesearch(PathKind::Native).search_path_dirs()
804 pub fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
805 let lib_args: Vec<_> = all_native_libs.iter()
806 .filter(|l| relevant_lib(sess, l))
808 let name = lib.name?;
810 NativeLibraryKind::NativeStaticNobundle |
811 NativeLibraryKind::NativeUnknown => {
812 if sess.target.target.options.is_like_msvc {
813 Some(format!("{}.lib", name))
815 Some(format!("-l{}", name))
818 NativeLibraryKind::NativeFramework => {
819 // ld-only syntax, since there are no frameworks in MSVC
820 Some(format!("-framework {}", name))
822 // These are included, no need to print them
823 NativeLibraryKind::NativeStatic => None,
827 if !lib_args.is_empty() {
828 sess.note_without_error("Link against the following native artifacts when linking \
829 against this static library. The order and any duplication \
830 can be significant on some platforms.");
831 // Prefix for greppability
832 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
836 pub fn get_file_path(sess: &Session, name: &str) -> PathBuf {
837 let fs = sess.target_filesearch(PathKind::Native);
838 let file_path = fs.get_lib_path().join(name);
839 if file_path.exists() {
842 for search_path in fs.search_paths() {
843 let file_path = search_path.dir.join(name);
844 if file_path.exists() {
851 pub 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 std::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() {
982 '\\' | ' ' => write!(f, "\\{}", c)?,
983 c => write!(f, "{}", c)?,
992 fn link_args<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
993 flavor: LinkerFlavor,
995 crate_type: config::CrateType,
998 codegen_results: &CodegenResults) {
1000 // Linker plugins should be specified early in the list of arguments
1001 cmd.linker_plugin_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 something like a dynamic library then some platforms
1024 // need to make sure that all symbols are exported correctly from the
1026 cmd.export_symbols(tmpdir, crate_type);
1028 // When linking a dynamic library, we put the metadata into a section of the
1029 // executable. This metadata is in a separate object file from the main
1030 // object file, so we link that in here.
1031 if crate_type == config::CrateType::Dylib ||
1032 crate_type == config::CrateType::ProcMacro {
1033 let obj = codegen_results.metadata_module
1035 .and_then(|m| m.object.as_ref());
1036 if let Some(obj) = obj {
1037 cmd.add_object(obj);
1041 let obj = codegen_results.allocator_module
1043 .and_then(|m| m.object.as_ref());
1044 if let Some(obj) = obj {
1045 cmd.add_object(obj);
1048 // Try to strip as much out of the generated object by removing unused
1049 // sections if possible. See more comments in linker.rs
1050 if !sess.opts.cg.link_dead_code {
1051 let keep_metadata = crate_type == config::CrateType::Dylib;
1052 cmd.gc_sections(keep_metadata);
1055 let used_link_args = &codegen_results.crate_info.link_args;
1057 if crate_type == config::CrateType::Executable {
1058 let mut position_independent_executable = false;
1060 if t.options.position_independent_executables {
1061 let empty_vec = Vec::new();
1062 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1063 let more_args = &sess.opts.cg.link_arg;
1064 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1066 if is_pic(sess) && !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 && 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, by default, prevent the compiler from accidentally leaking in
1109 // any system libraries, so we may explicitly ask linkers to not link to any
1110 // libraries by default. Note that this does not happen for windows because
1111 // windows pulls in some large number of libraries and I couldn't quite
1112 // figure out which subset we wanted.
1114 // This is all naturally configurable via the standard methods as well.
1115 if !sess.opts.cg.default_linker_libraries.unwrap_or(false) &&
1116 t.options.no_default_libraries
1118 cmd.no_default_libraries();
1121 // Take careful note of the ordering of the arguments we pass to the linker
1122 // here. Linkers will assume that things on the left depend on things to the
1123 // right. Things on the right cannot depend on things on the left. This is
1124 // all formally implemented in terms of resolving symbols (libs on the right
1125 // resolve unknown symbols of libs on the left, but not vice versa).
1127 // For this reason, we have organized the arguments we pass to the linker as
1130 // 1. The local object that LLVM just generated
1131 // 2. Local native libraries
1132 // 3. Upstream rust libraries
1133 // 4. Upstream native libraries
1135 // The rationale behind this ordering is that those items lower down in the
1136 // list can't depend on items higher up in the list. For example nothing can
1137 // depend on what we just generated (e.g., that'd be a circular dependency).
1138 // Upstream rust libraries are not allowed to depend on our local native
1139 // libraries as that would violate the structure of the DAG, in that
1140 // scenario they are required to link to them as well in a shared fashion.
1142 // Note that upstream rust libraries may contain native dependencies as
1143 // well, but they also can't depend on what we just started to add to the
1144 // link line. And finally upstream native libraries can't depend on anything
1145 // in this DAG so far because they're only dylibs and dylibs can only depend
1146 // on other dylibs (e.g., other native deps).
1147 add_local_native_libraries(cmd, sess, codegen_results);
1148 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1149 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1151 // Tell the linker what we're doing.
1152 if crate_type != config::CrateType::Executable {
1153 cmd.build_dylib(out_filename);
1155 if crate_type == config::CrateType::Executable && sess.crt_static() {
1156 cmd.build_static_executable();
1159 if sess.opts.debugging_opts.pgo_gen.enabled() {
1163 // FIXME (#2397): At some point we want to rpath our guesses as to
1164 // where extern libraries might live, based on the
1165 // addl_lib_search_paths
1166 if sess.opts.cg.rpath {
1167 let target_triple = sess.opts.target_triple.triple();
1168 let mut get_install_prefix_lib_path = || {
1169 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1170 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1171 let mut path = PathBuf::from(install_prefix);
1176 let mut rpath_config = RPathConfig {
1177 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1178 out_filename: out_filename.to_path_buf(),
1179 has_rpath: sess.target.target.options.has_rpath,
1180 is_like_osx: sess.target.target.options.is_like_osx,
1181 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1182 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1184 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1187 // Finally add all the linker arguments provided on the command line along
1188 // with any #[link_args] attributes found inside the crate
1189 if let Some(ref args) = sess.opts.cg.link_args {
1192 cmd.args(&sess.opts.cg.link_arg);
1193 cmd.args(&used_link_args);
1196 // # Native library linking
1198 // User-supplied library search paths (-L on the command line). These are
1199 // the same paths used to find Rust crates, so some of them may have been
1200 // added already by the previous crate linking code. This only allows them
1201 // to be found at compile time so it is still entirely up to outside
1202 // forces to make sure that library can be found at runtime.
1204 // Also note that the native libraries linked here are only the ones located
1205 // in the current crate. Upstream crates with native library dependencies
1206 // may have their native library pulled in above.
1207 pub fn add_local_native_libraries(cmd: &mut dyn Linker,
1209 codegen_results: &CodegenResults) {
1210 let filesearch = sess.target_filesearch(PathKind::All);
1211 for search_path in filesearch.search_paths() {
1212 match search_path.kind {
1213 PathKind::Framework => { cmd.framework_path(&search_path.dir); }
1214 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)); }
1218 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1219 relevant_lib(sess, l)
1222 let search_path = archive_search_paths(sess);
1223 for lib in relevant_libs {
1224 let name = match lib.name {
1229 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1230 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1231 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&name.as_str()),
1232 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&name.as_str(),
1238 // # Rust Crate linking
1240 // Rust crates are not considered at all when creating an rlib output. All
1241 // dependencies will be linked when producing the final output (instead of
1242 // the intermediate rlib version)
1243 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1245 codegen_results: &CodegenResults,
1246 crate_type: config::CrateType,
1248 // All of the heavy lifting has previously been accomplished by the
1249 // dependency_format module of the compiler. This is just crawling the
1250 // output of that module, adding crates as necessary.
1252 // Linking to a rlib involves just passing it to the linker (the linker
1253 // will slurp up the object files inside), and linking to a dynamic library
1254 // involves just passing the right -l flag.
1256 let formats = sess.dependency_formats.borrow();
1257 let data = formats.get(&crate_type).unwrap();
1259 // Invoke get_used_crates to ensure that we get a topological sorting of
1261 let deps = &codegen_results.crate_info.used_crates_dynamic;
1263 // There's a few internal crates in the standard library (aka libcore and
1264 // libstd) which actually have a circular dependence upon one another. This
1265 // currently arises through "weak lang items" where libcore requires things
1266 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1267 // circular dependence to work correctly in all situations we'll need to be
1268 // sure to correctly apply the `--start-group` and `--end-group` options to
1269 // GNU linkers, otherwise if we don't use any other symbol from the standard
1270 // library it'll get discarded and the whole application won't link.
1272 // In this loop we're calculating the `group_end`, after which crate to
1273 // pass `--end-group` and `group_start`, before which crate to pass
1274 // `--start-group`. We currently do this by passing `--end-group` after
1275 // the first crate (when iterating backwards) that requires a lang item
1276 // defined somewhere else. Once that's set then when we've defined all the
1277 // necessary lang items we'll pass `--start-group`.
1279 // Note that this isn't amazing logic for now but it should do the trick
1280 // for the current implementation of the standard library.
1281 let mut group_end = None;
1282 let mut group_start = None;
1283 let mut end_with = FxHashSet::default();
1284 let info = &codegen_results.crate_info;
1285 for &(cnum, _) in deps.iter().rev() {
1286 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1287 end_with.extend(missing.iter().cloned());
1288 if end_with.len() > 0 && group_end.is_none() {
1289 group_end = Some(cnum);
1292 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1293 if end_with.len() == 0 && group_end.is_some() {
1294 group_start = Some(cnum);
1299 // If we didn't end up filling in all lang items from upstream crates then
1300 // we'll be filling it in with our crate. This probably means we're the
1301 // standard library itself, so skip this for now.
1302 if group_end.is_some() && group_start.is_none() {
1306 let mut compiler_builtins = None;
1308 for &(cnum, _) in deps.iter() {
1309 if group_start == Some(cnum) {
1313 // We may not pass all crates through to the linker. Some crates may
1314 // appear statically in an existing dylib, meaning we'll pick up all the
1315 // symbols from the dylib.
1316 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1317 match data[cnum.as_usize() - 1] {
1318 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1319 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1321 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) => {
1322 link_sanitizer_runtime::<B>(cmd, sess, codegen_results, tmpdir, cnum);
1324 // compiler-builtins are always placed last to ensure that they're
1325 // linked correctly.
1326 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1327 assert!(compiler_builtins.is_none());
1328 compiler_builtins = Some(cnum);
1330 Linkage::NotLinked |
1331 Linkage::IncludedFromDylib => {}
1332 Linkage::Static => {
1333 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1335 Linkage::Dynamic => {
1336 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1340 if group_end == Some(cnum) {
1345 // compiler-builtins are always placed last to ensure that they're
1346 // linked correctly.
1347 // We must always link the `compiler_builtins` crate statically. Even if it
1348 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1350 if let Some(cnum) = compiler_builtins {
1351 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1354 // Converts a library file-stem into a cc -l argument
1355 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1356 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1363 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1364 // it's packed in a .rlib, it contains stuff that are not objects that will
1365 // make the linker error. So we must remove those bits from the .rlib before
1367 fn link_sanitizer_runtime<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1369 codegen_results: &CodegenResults,
1372 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1373 let cratepath = &src.rlib.as_ref().unwrap().0;
1375 if sess.target.target.options.is_like_osx {
1376 // On Apple platforms, the sanitizer is always built as a dylib, and
1377 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1378 // rpath to the library as well (the rpath should be absolute, see
1379 // PR #41352 for details).
1381 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1382 let rpath = cratepath.parent().unwrap();
1383 let rpath = rpath.to_str().expect("non-utf8 component in path");
1384 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1387 let dst = tmpdir.join(cratepath.file_name().unwrap());
1388 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1389 archive.update_symbols();
1391 for f in archive.src_files() {
1392 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1393 archive.remove_file(&f);
1399 cmd.link_whole_rlib(&dst);
1402 // Adds the static "rlib" versions of all crates to the command line.
1403 // There's a bit of magic which happens here specifically related to LTO and
1404 // dynamic libraries. Specifically:
1406 // * For LTO, we remove upstream object files.
1407 // * For dylibs we remove metadata and bytecode from upstream rlibs
1409 // When performing LTO, almost(*) all of the bytecode from the upstream
1410 // libraries has already been included in our object file output. As a
1411 // result we need to remove the object files in the upstream libraries so
1412 // the linker doesn't try to include them twice (or whine about duplicate
1413 // symbols). We must continue to include the rest of the rlib, however, as
1414 // it may contain static native libraries which must be linked in.
1416 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1417 // their bytecode wasn't included. The object files in those libraries must
1418 // still be passed to the linker.
1420 // When making a dynamic library, linkers by default don't include any
1421 // object files in an archive if they're not necessary to resolve the link.
1422 // We basically want to convert the archive (rlib) to a dylib, though, so we
1423 // *do* want everything included in the output, regardless of whether the
1424 // linker thinks it's needed or not. As a result we must use the
1425 // --whole-archive option (or the platform equivalent). When using this
1426 // option the linker will fail if there are non-objects in the archive (such
1427 // as our own metadata and/or bytecode). All in all, for rlibs to be
1428 // entirely included in dylibs, we need to remove all non-object files.
1430 // Note, however, that if we're not doing LTO or we're not producing a dylib
1431 // (aka we're making an executable), we can just pass the rlib blindly to
1432 // the linker (fast) because it's fine if it's not actually included as
1433 // we're at the end of the dependency chain.
1434 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(cmd: &mut dyn Linker,
1436 codegen_results: &CodegenResults,
1438 crate_type: config::CrateType,
1440 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1441 let cratepath = &src.rlib.as_ref().unwrap().0;
1443 // See the comment above in `link_staticlib` and `link_rlib` for why if
1444 // there's a static library that's not relevant we skip all object
1446 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1447 let skip_native = native_libs.iter().any(|lib| {
1448 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1451 if (!are_upstream_rust_objects_already_included(sess) ||
1452 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1453 crate_type != config::CrateType::Dylib &&
1455 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1459 let dst = tmpdir.join(cratepath.file_name().unwrap());
1460 let name = cratepath.file_name().unwrap().to_str().unwrap();
1461 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1463 time_ext(sess.time_extended(), Some(sess), &format!("altering {}.rlib", name), || {
1464 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1465 archive.update_symbols();
1467 let mut any_objects = false;
1468 for f in archive.src_files() {
1469 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1470 archive.remove_file(&f);
1474 let canonical = f.replace("-", "_");
1475 let canonical_name = name.replace("-", "_");
1477 // Look for `.rcgu.o` at the end of the filename to conclude
1478 // that this is a Rust-related object file.
1479 fn looks_like_rust(s: &str) -> bool {
1480 let path = Path::new(s);
1481 let ext = path.extension().and_then(|s| s.to_str());
1482 if ext != Some(OutputType::Object.extension()) {
1485 let ext2 = path.file_stem()
1486 .and_then(|s| Path::new(s).extension())
1487 .and_then(|s| s.to_str());
1488 ext2 == Some(RUST_CGU_EXT)
1491 let is_rust_object =
1492 canonical.starts_with(&canonical_name) &&
1493 looks_like_rust(&f);
1495 // If we've been requested to skip all native object files
1496 // (those not generated by the rust compiler) then we can skip
1497 // this file. See above for why we may want to do this.
1498 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1500 // If we're performing LTO and this is a rust-generated object
1501 // file, then we don't need the object file as it's part of the
1502 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1503 // though, so we let that object file slide.
1504 let skip_because_lto = are_upstream_rust_objects_already_included(sess) &&
1506 (sess.target.target.options.no_builtins ||
1507 !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1509 if skip_because_cfg_say_so || skip_because_lto {
1510 archive.remove_file(&f);
1521 // If we're creating a dylib, then we need to include the
1522 // whole of each object in our archive into that artifact. This is
1523 // because a `dylib` can be reused as an intermediate artifact.
1525 // Note, though, that we don't want to include the whole of a
1526 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1527 // repeatedly linked anyway.
1528 if crate_type == config::CrateType::Dylib &&
1529 codegen_results.crate_info.compiler_builtins != Some(cnum) {
1530 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1532 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1537 // Same thing as above, but for dynamic crates instead of static crates.
1538 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1539 // Just need to tell the linker about where the library lives and
1541 let parent = cratepath.parent();
1542 if let Some(dir) = parent {
1543 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1545 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1546 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1547 parent.unwrap_or(Path::new("")));
1551 // Link in all of our upstream crates' native dependencies. Remember that
1552 // all of these upstream native dependencies are all non-static
1553 // dependencies. We've got two cases then:
1555 // 1. The upstream crate is an rlib. In this case we *must* link in the
1556 // native dependency because the rlib is just an archive.
1558 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1559 // have the dependency present on the system somewhere. Thus, we don't
1560 // gain a whole lot from not linking in the dynamic dependency to this
1563 // The use case for this is a little subtle. In theory the native
1564 // dependencies of a crate are purely an implementation detail of the crate
1565 // itself, but the problem arises with generic and inlined functions. If a
1566 // generic function calls a native function, then the generic function must
1567 // be instantiated in the target crate, meaning that the native symbol must
1568 // also be resolved in the target crate.
1569 pub fn add_upstream_native_libraries(cmd: &mut dyn Linker,
1571 codegen_results: &CodegenResults,
1572 crate_type: config::CrateType) {
1573 // Be sure to use a topological sorting of crates because there may be
1574 // interdependencies between native libraries. When passing -nodefaultlibs,
1575 // for example, almost all native libraries depend on libc, so we have to
1576 // make sure that's all the way at the right (liblibc is near the base of
1577 // the dependency chain).
1579 // This passes RequireStatic, but the actual requirement doesn't matter,
1580 // we're just getting an ordering of crate numbers, we're not worried about
1582 let formats = sess.dependency_formats.borrow();
1583 let data = formats.get(&crate_type).unwrap();
1585 let crates = &codegen_results.crate_info.used_crates_static;
1586 for &(cnum, _) in crates {
1587 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1588 let name = match lib.name {
1592 if !relevant_lib(sess, &lib) {
1596 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1597 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1598 NativeLibraryKind::NativeStaticNobundle => {
1599 // Link "static-nobundle" native libs only if the crate they originate from
1600 // is being linked statically to the current crate. If it's linked dynamically
1601 // or is an rlib already included via some other dylib crate, the symbols from
1602 // native libs will have already been included in that dylib.
1603 if data[cnum.as_usize() - 1] == Linkage::Static {
1604 cmd.link_staticlib(&name.as_str())
1607 // ignore statically included native libraries here as we've
1608 // already included them when we included the rust library
1610 NativeLibraryKind::NativeStatic => {}
1616 pub fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1618 Some(ref cfg) => syntax::attr::cfg_matches(cfg, &sess.parse_sess, None),
1623 pub fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1625 config::Lto::Fat => true,
1626 config::Lto::Thin => {
1627 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1628 // any upstream object files have not been copied yet.
1629 !sess.opts.cg.linker_plugin_lto.enabled()
1632 config::Lto::ThinLocal => false,
1636 fn is_pic(sess: &Session) -> bool {
1637 let reloc_model_arg = match sess.opts.cg.relocation_model {
1638 Some(ref s) => &s[..],
1639 None => &sess.target.target.options.relocation_model[..],
1642 reloc_model_arg == "pic"