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 super::archive::{ArchiveBuilder, ArchiveConfig};
13 use super::bytecode::RLIB_BYTECODE_EXTENSION;
14 use rustc_codegen_ssa::back::linker::Linker;
15 use rustc_codegen_ssa::back::link::{remove, ignored_for_lto, each_linked_rlib, linker_and_flavor,
17 use rustc_codegen_ssa::back::command::Command;
18 use super::rpath::RPathConfig;
20 use metadata::METADATA_FILENAME;
21 use rustc::session::config::{self, DebugInfo, OutputFilenames, OutputType, PrintRequest};
22 use rustc::session::config::{RUST_CGU_EXT, Lto, Sanitizer};
23 use rustc::session::filesearch;
24 use rustc::session::search_paths::PathKind;
25 use rustc::session::Session;
26 use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind};
27 use rustc::middle::dependency_format::Linkage;
28 use rustc_codegen_ssa::CodegenResults;
29 use rustc::util::common::time;
30 use rustc_fs_util::fix_windows_verbatim_for_gcc;
31 use rustc::hir::def_id::CrateNum;
32 use tempfile::{Builder as TempFileBuilder, TempDir};
33 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor};
34 use rustc_data_structures::fx::FxHashSet;
35 use context::get_reloc_model;
45 use std::path::{Path, PathBuf};
46 use std::process::{Output, Stdio};
50 pub use rustc_codegen_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
51 invalid_output_for_target, filename_for_metadata,
52 out_filename, check_file_is_writeable};
55 /// Perform the linkage portion of the compilation phase. This will generate all
56 /// of the requested outputs for this compilation session.
57 pub(crate) fn link_binary(sess: &Session,
58 codegen_results: &CodegenResults,
59 outputs: &OutputFilenames,
60 crate_name: &str) -> Vec<PathBuf> {
61 let mut out_filenames = Vec::new();
62 for &crate_type in sess.crate_types.borrow().iter() {
63 // Ignore executable crates if we have -Z no-codegen, as they will error.
64 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
65 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen()) &&
67 crate_type == config::CrateType::Executable {
71 if invalid_output_for_target(sess, crate_type) {
72 bug!("invalid output type `{:?}` for target os `{}`",
73 crate_type, sess.opts.target_triple);
75 let out_files = link_binary_output(sess,
80 out_filenames.extend(out_files);
83 // Remove the temporary object file and metadata if we aren't saving temps
84 if !sess.opts.cg.save_temps {
85 if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) {
86 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
90 for obj in codegen_results.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
93 if let Some(ref obj) = codegen_results.metadata_module.object {
96 if let Some(ref allocator) = codegen_results.allocator_module {
97 if let Some(ref obj) = allocator.object {
100 if let Some(ref bc) = allocator.bytecode_compressed {
109 /// Returns a boolean indicating whether we should preserve the object files on
110 /// the filesystem for their debug information. This is often useful with
111 /// split-dwarf like schemes.
112 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
113 // If the objects don't have debuginfo there's nothing to preserve.
114 if sess.opts.debuginfo == DebugInfo::None {
118 // If we're only producing artifacts that are archives, no need to preserve
119 // the objects as they're losslessly contained inside the archives.
120 let output_linked = sess.crate_types.borrow()
122 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
127 // If we're on OSX then the equivalent of split dwarf is turned on by
128 // default. The final executable won't actually have any debug information
129 // except it'll have pointers to elsewhere. Historically we've always run
130 // `dsymutil` to "link all the dwarf together" but this is actually sort of
131 // a bummer for incremental compilation! (the whole point of split dwarf is
132 // that you don't do this sort of dwarf link).
134 // Basically as a result this just means that if we're on OSX and we're
135 // *not* running dsymutil then the object files are the only source of truth
136 // for debug information, so we must preserve them.
137 if sess.target.target.options.is_like_osx {
138 match sess.opts.debugging_opts.run_dsymutil {
139 // dsymutil is not being run, preserve objects
140 Some(false) => return true,
142 // dsymutil is being run, no need to preserve the objects
143 Some(true) => return false,
145 // The default historical behavior was to always run dsymutil, so
146 // we're preserving that temporarily, but we're likely to switch the
148 None => return false,
155 fn link_binary_output(sess: &Session,
156 codegen_results: &CodegenResults,
157 crate_type: config::CrateType,
158 outputs: &OutputFilenames,
159 crate_name: &str) -> Vec<PathBuf> {
160 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
161 check_file_is_writeable(obj, sess);
164 let mut out_filenames = vec![];
166 if outputs.outputs.contains_key(&OutputType::Metadata) {
167 let out_filename = filename_for_metadata(sess, crate_name, outputs);
168 // To avoid races with another rustc process scanning the output directory,
169 // we need to write the file somewhere else and atomically move it to its
170 // final destination, with a `fs::rename` call. In order for the rename to
171 // always succeed, the temporary file needs to be on the same filesystem,
172 // which is why we create it inside the output directory specifically.
173 let metadata_tmpdir = TempFileBuilder::new()
175 .tempdir_in(out_filename.parent().unwrap())
176 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
177 let metadata = emit_metadata(sess, codegen_results, &metadata_tmpdir);
178 if let Err(e) = fs::rename(metadata, &out_filename) {
179 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
181 out_filenames.push(out_filename);
184 let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err|
185 sess.fatal(&format!("couldn't create a temp dir: {}", err)));
187 if outputs.outputs.should_codegen() {
188 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
190 config::CrateType::Rlib => {
197 config::CrateType::Staticlib => {
198 link_staticlib(sess, codegen_results, &out_filename, &tmpdir);
201 link_natively(sess, crate_type, &out_filename, codegen_results, tmpdir.path());
204 out_filenames.push(out_filename);
207 if sess.opts.cg.save_temps {
208 let _ = tmpdir.into_path();
214 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
215 let mut search = Vec::new();
216 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
217 search.push(path.to_path_buf());
223 fn archive_config<'a>(sess: &'a Session,
225 input: Option<&Path>) -> ArchiveConfig<'a> {
228 dst: output.to_path_buf(),
229 src: input.map(|p| p.to_path_buf()),
230 lib_search_paths: archive_search_paths(sess),
234 /// We use a temp directory here to avoid races between concurrent rustc processes,
235 /// such as builds in the same directory using the same filename for metadata while
236 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
237 /// directory being searched for `extern crate` (observing an incomplete file).
238 /// The returned path is the temporary file containing the complete metadata.
239 fn emit_metadata<'a>(
241 codegen_results: &CodegenResults,
244 let out_filename = tmpdir.path().join(METADATA_FILENAME);
245 let result = fs::write(&out_filename, &codegen_results.metadata.raw_data);
247 if let Err(e) = result {
248 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
261 // An rlib in its current incarnation is essentially a renamed .a file. The
262 // rlib primarily contains the object file of the crate, but it also contains
263 // all of the object files from native libraries. This is done by unzipping
264 // native libraries and inserting all of the contents into this archive.
265 fn link_rlib<'a>(sess: &'a Session,
266 codegen_results: &CodegenResults,
269 tmpdir: &TempDir) -> ArchiveBuilder<'a> {
270 info!("preparing rlib to {:?}", out_filename);
271 let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
273 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
277 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
278 // we may not be configured to actually include a static library if we're
279 // adding it here. That's because later when we consume this rlib we'll
280 // decide whether we actually needed the static library or not.
282 // To do this "correctly" we'd need to keep track of which libraries added
283 // which object files to the archive. We don't do that here, however. The
284 // #[link(cfg(..))] feature is unstable, though, and only intended to get
285 // liblibc working. In that sense the check below just indicates that if
286 // there are any libraries we want to omit object files for at link time we
287 // just exclude all custom object files.
289 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
290 // feature then we'll need to figure out how to record what objects were
291 // loaded from the libraries found here and then encode that into the
292 // metadata of the rlib we're generating somehow.
293 for lib in codegen_results.crate_info.used_libraries.iter() {
295 NativeLibraryKind::NativeStatic => {}
296 NativeLibraryKind::NativeStaticNobundle |
297 NativeLibraryKind::NativeFramework |
298 NativeLibraryKind::NativeUnknown => continue,
300 if let Some(name) = lib.name {
301 ab.add_native_library(&name.as_str());
305 // After adding all files to the archive, we need to update the
306 // symbol table of the archive.
309 // Note that it is important that we add all of our non-object "magical
310 // files" *after* all of the object files in the archive. The reason for
311 // this is as follows:
313 // * When performing LTO, this archive will be modified to remove
314 // objects from above. The reason for this is described below.
316 // * When the system linker looks at an archive, it will attempt to
317 // determine the architecture of the archive in order to see whether its
320 // The algorithm for this detection is: iterate over the files in the
321 // archive. Skip magical SYMDEF names. Interpret the first file as an
322 // object file. Read architecture from the object file.
324 // * As one can probably see, if "metadata" and "foo.bc" were placed
325 // before all of the objects, then the architecture of this archive would
326 // not be correctly inferred once 'foo.o' is removed.
328 // Basically, all this means is that this code should not move above the
331 RlibFlavor::Normal => {
332 // Instead of putting the metadata in an object file section, rlibs
333 // contain the metadata in a separate file.
334 ab.add_file(&emit_metadata(sess, codegen_results, tmpdir));
336 // For LTO purposes, the bytecode of this library is also inserted
338 for bytecode in codegen_results
341 .filter_map(|m| m.bytecode_compressed.as_ref())
343 ab.add_file(bytecode);
346 // After adding all files to the archive, we need to update the
347 // symbol table of the archive. This currently dies on macOS (see
348 // #11162), and isn't necessary there anyway
349 if !sess.target.target.options.is_like_osx {
354 RlibFlavor::StaticlibBase => {
355 let obj = codegen_results.allocator_module
357 .and_then(|m| m.object.as_ref());
358 if let Some(obj) = obj {
367 // Create a static archive
369 // This is essentially the same thing as an rlib, but it also involves adding
370 // all of the upstream crates' objects into the archive. This will slurp in
371 // all of the native libraries of upstream dependencies as well.
373 // Additionally, there's no way for us to link dynamic libraries, so we warn
374 // about all dynamic library dependencies that they're not linked in.
376 // There's no need to include metadata in a static archive, so ensure to not
377 // link in the metadata object file (and also don't prepare the archive with a
379 fn link_staticlib(sess: &Session,
380 codegen_results: &CodegenResults,
383 let mut ab = link_rlib(sess,
385 RlibFlavor::StaticlibBase,
388 let mut all_native_libs = vec![];
390 let res = each_linked_rlib(sess, &codegen_results.crate_info, &mut |cnum, path| {
391 let name = &codegen_results.crate_info.crate_name[&cnum];
392 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
394 // Here when we include the rlib into our staticlib we need to make a
395 // decision whether to include the extra object files along the way.
396 // These extra object files come from statically included native
397 // libraries, but they may be cfg'd away with #[link(cfg(..))].
399 // This unstable feature, though, only needs liblibc to work. The only
400 // use case there is where musl is statically included in liblibc.rlib,
401 // so if we don't want the included version we just need to skip it. As
402 // a result the logic here is that if *any* linked library is cfg'd away
403 // we just skip all object files.
405 // Clearly this is not sufficient for a general purpose feature, and
406 // we'd want to read from the library's metadata to determine which
407 // object files come from where and selectively skip them.
408 let skip_object_files = native_libs.iter().any(|lib| {
409 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
413 are_upstream_rust_objects_already_included(sess) &&
414 !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
415 skip_object_files).unwrap();
417 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
419 if let Err(e) = res {
426 if !all_native_libs.is_empty() {
427 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
428 print_native_static_libs(sess, &all_native_libs);
433 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
434 let lib_args: Vec<_> = all_native_libs.iter()
435 .filter(|l| relevant_lib(sess, l))
437 let name = lib.name?;
439 NativeLibraryKind::NativeStaticNobundle |
440 NativeLibraryKind::NativeUnknown => {
441 if sess.target.target.options.is_like_msvc {
442 Some(format!("{}.lib", name))
444 Some(format!("-l{}", name))
447 NativeLibraryKind::NativeFramework => {
448 // ld-only syntax, since there are no frameworks in MSVC
449 Some(format!("-framework {}", name))
451 // These are included, no need to print them
452 NativeLibraryKind::NativeStatic => None,
456 if !lib_args.is_empty() {
457 sess.note_without_error("Link against the following native artifacts when linking \
458 against this static library. The order and any duplication \
459 can be significant on some platforms.");
460 // Prefix for greppability
461 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
465 // Create a dynamic library or executable
467 // This will invoke the system linker/cc to create the resulting file. This
468 // links to all upstream files as well.
469 fn link_natively(sess: &Session,
470 crate_type: config::CrateType,
472 codegen_results: &CodegenResults,
474 info!("preparing {:?} to {:?}", crate_type, out_filename);
475 let (linker, flavor) = linker_and_flavor(sess);
477 // The invocations of cc share some flags across platforms
478 let (pname, mut cmd) = get_linker(sess, &linker, flavor);
480 let root = sess.target_filesearch(PathKind::Native).get_lib_path();
481 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
484 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
485 if sess.crt_static() {
489 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
492 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
494 if sess.target.target.options.is_like_fuchsia {
495 let prefix = match sess.opts.debugging_opts.sanitizer {
496 Some(Sanitizer::Address) => "asan/",
499 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
502 let pre_link_objects = if crate_type == config::CrateType::Executable {
503 &sess.target.target.options.pre_link_objects_exe
505 &sess.target.target.options.pre_link_objects_dll
507 for obj in pre_link_objects {
508 cmd.arg(root.join(obj));
511 if crate_type == config::CrateType::Executable && sess.crt_static() {
512 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
513 cmd.arg(root.join(obj));
517 if sess.target.target.options.is_like_emscripten {
519 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
520 "DISABLE_EXCEPTION_CATCHING=1"
522 "DISABLE_EXCEPTION_CATCHING=0"
527 let target_cpu = ::llvm_util::target_cpu(sess);
528 let mut linker = codegen_results.linker_info.to_linker(cmd, &sess, flavor, target_cpu);
529 link_args(&mut *linker, flavor, sess, crate_type, tmpdir,
530 out_filename, codegen_results);
531 cmd = linker.finalize();
533 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
536 for obj in &sess.target.target.options.post_link_objects {
537 cmd.arg(root.join(obj));
539 if sess.crt_static() {
540 for obj in &sess.target.target.options.post_link_objects_crt {
541 cmd.arg(root.join(obj));
544 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
547 for &(ref k, ref v) in &sess.target.target.options.link_env {
551 if sess.opts.debugging_opts.print_link_args {
552 println!("{:?}", &cmd);
555 // May have not found libraries in the right formats.
556 sess.abort_if_errors();
558 // Invoke the system linker
560 // Note that there's a terribly awful hack that really shouldn't be present
561 // in any compiler. Here an environment variable is supported to
562 // automatically retry the linker invocation if the linker looks like it
565 // Gee that seems odd, normally segfaults are things we want to know about!
566 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
567 // linker segfaulting on Travis quite a bit which is causing quite a bit of
568 // pain to land PRs when they spuriously fail due to a segfault.
570 // The issue #38878 has some more debugging information on it as well, but
571 // this unfortunately looks like it's just a race condition in macOS's linker
572 // with some thread pool working in the background. It seems that no one
573 // currently knows a fix for this so in the meantime we're left with this...
575 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
580 prog = time(sess, "running linker", || {
581 exec_linker(sess, &mut cmd, out_filename, tmpdir)
583 let output = match prog {
584 Ok(ref output) => output,
587 if output.status.success() {
590 let mut out = output.stderr.clone();
591 out.extend(&output.stdout);
592 let out = String::from_utf8_lossy(&out);
594 // Check to see if the link failed with "unrecognized command line option:
595 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
596 // reperform the link step without the -no-pie option. This is safe because
597 // if the linker doesn't support -no-pie then it should not default to
598 // linking executables as pie. Different versions of gcc seem to use
599 // different quotes in the error message so don't check for them.
600 if sess.target.target.options.linker_is_gnu &&
601 flavor != LinkerFlavor::Ld &&
602 (out.contains("unrecognized command line option") ||
603 out.contains("unknown argument")) &&
604 out.contains("-no-pie") &&
605 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
606 info!("linker output: {:?}", out);
607 warn!("Linker does not support -no-pie command line option. Retrying without.");
608 for arg in cmd.take_args() {
609 if arg.to_string_lossy() != "-no-pie" {
616 if !retry_on_segfault || i > 3 {
619 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
620 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
621 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
626 "looks like the linker segfaulted when we tried to call it, \
627 automatically retrying again. cmd = {:?}, out = {}.",
635 fn escape_string(s: &[u8]) -> String {
636 str::from_utf8(s).map(|s| s.to_owned())
637 .unwrap_or_else(|_| {
638 let mut x = "Non-UTF-8 output: ".to_string();
640 .flat_map(|&b| ascii::escape_default(b))
645 if !prog.status.success() {
646 let mut output = prog.stderr.clone();
647 output.extend_from_slice(&prog.stdout);
648 sess.struct_err(&format!("linking with `{}` failed: {}",
651 .note(&format!("{:?}", &cmd))
652 .note(&escape_string(&output))
654 sess.abort_if_errors();
656 info!("linker stderr:\n{}", escape_string(&prog.stderr));
657 info!("linker stdout:\n{}", escape_string(&prog.stdout));
660 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
662 let mut linker_error = {
663 if linker_not_found {
664 sess.struct_err(&format!("linker `{}` not found", pname.display()))
666 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
670 linker_error.note(&e.to_string());
672 if !linker_not_found {
673 linker_error.note(&format!("{:?}", &cmd));
678 if sess.target.target.options.is_like_msvc && linker_not_found {
679 sess.note_without_error("the msvc targets depend on the msvc linker \
680 but `link.exe` was not found");
681 sess.note_without_error("please ensure that VS 2013, VS 2015 or VS 2017 \
682 was installed with the Visual C++ option");
684 sess.abort_if_errors();
689 // On macOS, debuggers need this utility to get run to do some munging of
690 // the symbols. Note, though, that if the object files are being preserved
691 // for their debug information there's no need for us to run dsymutil.
692 if sess.target.target.options.is_like_osx &&
693 sess.opts.debuginfo != DebugInfo::None &&
694 !preserve_objects_for_their_debuginfo(sess)
696 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
697 sess.fatal(&format!("failed to run dsymutil: {}", e))
701 if sess.opts.target_triple.triple() == "wasm32-unknown-unknown" {
702 wasm::rewrite_imports(&out_filename, &codegen_results.crate_info.wasm_imports);
703 wasm::add_producer_section(
705 &sess.edition().to_string(),
706 option_env!("CFG_VERSION").unwrap_or("unknown"),
711 fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
712 -> io::Result<Output>
714 // When attempting to spawn the linker we run a risk of blowing out the
715 // size limits for spawning a new process with respect to the arguments
716 // we pass on the command line.
718 // Here we attempt to handle errors from the OS saying "your list of
719 // arguments is too big" by reinvoking the linker again with an `@`-file
720 // that contains all the arguments. The theory is that this is then
721 // accepted on all linkers and the linker will read all its options out of
722 // there instead of looking at the command line.
723 if !cmd.very_likely_to_exceed_some_spawn_limit() {
724 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
726 let output = child.wait_with_output();
727 flush_linked_file(&output, out_filename)?;
730 Err(ref e) if command_line_too_big(e) => {
731 info!("command line to linker was too big: {}", e);
733 Err(e) => return Err(e)
737 info!("falling back to passing arguments to linker via an @-file");
738 let mut cmd2 = cmd.clone();
739 let mut args = String::new();
740 for arg in cmd2.take_args() {
741 args.push_str(&Escape {
742 arg: arg.to_str().unwrap(),
743 is_like_msvc: sess.target.target.options.is_like_msvc,
747 let file = tmpdir.join("linker-arguments");
748 let bytes = if sess.target.target.options.is_like_msvc {
749 let mut out = Vec::with_capacity((1 + args.len()) * 2);
750 // start the stream with a UTF-16 BOM
751 for c in iter::once(0xFEFF).chain(args.encode_utf16()) {
752 // encode in little endian
754 out.push((c >> 8) as u8);
760 fs::write(&file, &bytes)?;
761 cmd2.arg(format!("@{}", file.display()));
762 info!("invoking linker {:?}", cmd2);
763 let output = cmd2.output();
764 flush_linked_file(&output, out_filename)?;
768 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
773 fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
776 // On Windows, under high I/O load, output buffers are sometimes not flushed,
777 // even long after process exit, causing nasty, non-reproducible output bugs.
779 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
781 // А full writeup of the original Chrome bug can be found at
782 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
784 if let &Ok(ref out) = command_output {
785 if out.status.success() {
786 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
796 fn command_line_too_big(err: &io::Error) -> bool {
797 err.raw_os_error() == Some(::libc::E2BIG)
801 fn command_line_too_big(err: &io::Error) -> bool {
802 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
803 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
811 impl<'a> fmt::Display for Escape<'a> {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 if self.is_like_msvc {
814 // This is "documented" at
815 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
817 // Unfortunately there's not a great specification of the
818 // syntax I could find online (at least) but some local
819 // testing showed that this seemed sufficient-ish to catch
820 // at least a few edge cases.
822 for c in self.arg.chars() {
824 '"' => write!(f, "\\{}", c)?,
825 c => write!(f, "{}", c)?,
830 // This is documented at https://linux.die.net/man/1/ld, namely:
832 // > Options in file are separated by whitespace. A whitespace
833 // > character may be included in an option by surrounding the
834 // > entire option in either single or double quotes. Any
835 // > character (including a backslash) may be included by
836 // > prefixing the character to be included with a backslash.
838 // We put an argument on each line, so all we need to do is
839 // ensure the line is interpreted as one whole argument.
840 for c in self.arg.chars() {
842 '\\' | ' ' => write!(f, "\\{}", c)?,
843 c => write!(f, "{}", c)?,
852 fn link_args(cmd: &mut dyn Linker,
853 flavor: LinkerFlavor,
855 crate_type: config::CrateType,
858 codegen_results: &CodegenResults) {
860 // Linker plugins should be specified early in the list of arguments
861 cmd.cross_lang_lto();
863 // The default library location, we need this to find the runtime.
864 // The location of crates will be determined as needed.
865 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
868 let t = &sess.target.target;
870 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
871 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
874 cmd.output_filename(out_filename);
876 if crate_type == config::CrateType::Executable &&
877 sess.target.target.options.is_like_windows {
878 if let Some(ref s) = codegen_results.windows_subsystem {
883 // If we're building a dynamic library then some platforms need to make sure
884 // that all symbols are exported correctly from the dynamic library.
885 if crate_type != config::CrateType::Executable ||
886 sess.target.target.options.is_like_emscripten {
887 cmd.export_symbols(tmpdir, crate_type);
890 // When linking a dynamic library, we put the metadata into a section of the
891 // executable. This metadata is in a separate object file from the main
892 // object file, so we link that in here.
893 if crate_type == config::CrateType::Dylib ||
894 crate_type == config::CrateType::ProcMacro {
895 if let Some(obj) = codegen_results.metadata_module.object.as_ref() {
900 let obj = codegen_results.allocator_module
902 .and_then(|m| m.object.as_ref());
903 if let Some(obj) = obj {
907 // Try to strip as much out of the generated object by removing unused
908 // sections if possible. See more comments in linker.rs
909 if !sess.opts.cg.link_dead_code {
910 let keep_metadata = crate_type == config::CrateType::Dylib;
911 cmd.gc_sections(keep_metadata);
914 let used_link_args = &codegen_results.crate_info.link_args;
916 if crate_type == config::CrateType::Executable {
917 let mut position_independent_executable = false;
919 if t.options.position_independent_executables {
920 let empty_vec = Vec::new();
921 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
922 let more_args = &sess.opts.cg.link_arg;
923 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
925 if get_reloc_model(sess) == llvm::RelocMode::PIC
926 && !sess.crt_static() && !args.any(|x| *x == "-static") {
927 position_independent_executable = true;
931 if position_independent_executable {
932 cmd.position_independent_executable();
934 // recent versions of gcc can be configured to generate position
935 // independent executables by default. We have to pass -no-pie to
936 // explicitly turn that off. Not applicable to ld.
937 if sess.target.target.options.linker_is_gnu
938 && flavor != LinkerFlavor::Ld {
939 cmd.no_position_independent_executable();
944 let relro_level = match sess.opts.debugging_opts.relro_level {
945 Some(level) => level,
946 None => t.options.relro_level,
949 RelroLevel::Full => {
952 RelroLevel::Partial => {
958 RelroLevel::None => {
962 // Pass optimization flags down to the linker.
965 // Pass debuginfo flags down to the linker.
968 // We want to, by default, prevent the compiler from accidentally leaking in
969 // any system libraries, so we may explicitly ask linkers to not link to any
970 // libraries by default. Note that this does not happen for windows because
971 // windows pulls in some large number of libraries and I couldn't quite
972 // figure out which subset we wanted.
974 // This is all naturally configurable via the standard methods as well.
975 if !sess.opts.cg.default_linker_libraries.unwrap_or(false) &&
976 t.options.no_default_libraries
978 cmd.no_default_libraries();
981 // Take careful note of the ordering of the arguments we pass to the linker
982 // here. Linkers will assume that things on the left depend on things to the
983 // right. Things on the right cannot depend on things on the left. This is
984 // all formally implemented in terms of resolving symbols (libs on the right
985 // resolve unknown symbols of libs on the left, but not vice versa).
987 // For this reason, we have organized the arguments we pass to the linker as
990 // 1. The local object that LLVM just generated
991 // 2. Local native libraries
992 // 3. Upstream rust libraries
993 // 4. Upstream native libraries
995 // The rationale behind this ordering is that those items lower down in the
996 // list can't depend on items higher up in the list. For example nothing can
997 // depend on what we just generated (e.g., that'd be a circular dependency).
998 // Upstream rust libraries are not allowed to depend on our local native
999 // libraries as that would violate the structure of the DAG, in that
1000 // scenario they are required to link to them as well in a shared fashion.
1002 // Note that upstream rust libraries may contain native dependencies as
1003 // well, but they also can't depend on what we just started to add to the
1004 // link line. And finally upstream native libraries can't depend on anything
1005 // in this DAG so far because they're only dylibs and dylibs can only depend
1006 // on other dylibs (e.g., other native deps).
1007 add_local_native_libraries(cmd, sess, codegen_results);
1008 add_upstream_rust_crates(cmd, sess, codegen_results, crate_type, tmpdir);
1009 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1011 // Tell the linker what we're doing.
1012 if crate_type != config::CrateType::Executable {
1013 cmd.build_dylib(out_filename);
1015 if crate_type == config::CrateType::Executable && sess.crt_static() {
1016 cmd.build_static_executable();
1019 if sess.opts.debugging_opts.pgo_gen.is_some() {
1023 // FIXME (#2397): At some point we want to rpath our guesses as to
1024 // where extern libraries might live, based on the
1025 // addl_lib_search_paths
1026 if sess.opts.cg.rpath {
1027 let sysroot = sess.sysroot();
1028 let target_triple = sess.opts.target_triple.triple();
1029 let mut get_install_prefix_lib_path = || {
1030 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1031 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1032 let mut path = PathBuf::from(install_prefix);
1037 let mut rpath_config = RPathConfig {
1038 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1039 out_filename: out_filename.to_path_buf(),
1040 has_rpath: sess.target.target.options.has_rpath,
1041 is_like_osx: sess.target.target.options.is_like_osx,
1042 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1043 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1045 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1048 // Finally add all the linker arguments provided on the command line along
1049 // with any #[link_args] attributes found inside the crate
1050 if let Some(ref args) = sess.opts.cg.link_args {
1053 cmd.args(&sess.opts.cg.link_arg);
1054 cmd.args(&used_link_args);
1057 // # Native library linking
1059 // User-supplied library search paths (-L on the command line). These are
1060 // the same paths used to find Rust crates, so some of them may have been
1061 // added already by the previous crate linking code. This only allows them
1062 // to be found at compile time so it is still entirely up to outside
1063 // forces to make sure that library can be found at runtime.
1065 // Also note that the native libraries linked here are only the ones located
1066 // in the current crate. Upstream crates with native library dependencies
1067 // may have their native library pulled in above.
1068 fn add_local_native_libraries(cmd: &mut dyn Linker,
1070 codegen_results: &CodegenResults) {
1071 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1073 PathKind::Framework => { cmd.framework_path(path); }
1074 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1078 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1079 relevant_lib(sess, l)
1082 let search_path = archive_search_paths(sess);
1083 for lib in relevant_libs {
1084 let name = match lib.name {
1089 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1090 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1091 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&name.as_str()),
1092 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&name.as_str(),
1098 // # Rust Crate linking
1100 // Rust crates are not considered at all when creating an rlib output. All
1101 // dependencies will be linked when producing the final output (instead of
1102 // the intermediate rlib version)
1103 fn add_upstream_rust_crates(cmd: &mut dyn Linker,
1105 codegen_results: &CodegenResults,
1106 crate_type: config::CrateType,
1108 // All of the heavy lifting has previously been accomplished by the
1109 // dependency_format module of the compiler. This is just crawling the
1110 // output of that module, adding crates as necessary.
1112 // Linking to a rlib involves just passing it to the linker (the linker
1113 // will slurp up the object files inside), and linking to a dynamic library
1114 // involves just passing the right -l flag.
1116 let formats = sess.dependency_formats.borrow();
1117 let data = formats.get(&crate_type).unwrap();
1119 // Invoke get_used_crates to ensure that we get a topological sorting of
1121 let deps = &codegen_results.crate_info.used_crates_dynamic;
1123 // There's a few internal crates in the standard library (aka libcore and
1124 // libstd) which actually have a circular dependence upon one another. This
1125 // currently arises through "weak lang items" where libcore requires things
1126 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1127 // circular dependence to work correctly in all situations we'll need to be
1128 // sure to correctly apply the `--start-group` and `--end-group` options to
1129 // GNU linkers, otherwise if we don't use any other symbol from the standard
1130 // library it'll get discarded and the whole application won't link.
1132 // In this loop we're calculating the `group_end`, after which crate to
1133 // pass `--end-group` and `group_start`, before which crate to pass
1134 // `--start-group`. We currently do this by passing `--end-group` after
1135 // the first crate (when iterating backwards) that requires a lang item
1136 // defined somewhere else. Once that's set then when we've defined all the
1137 // necessary lang items we'll pass `--start-group`.
1139 // Note that this isn't amazing logic for now but it should do the trick
1140 // for the current implementation of the standard library.
1141 let mut group_end = None;
1142 let mut group_start = None;
1143 let mut end_with = FxHashSet::default();
1144 let info = &codegen_results.crate_info;
1145 for &(cnum, _) in deps.iter().rev() {
1146 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1147 end_with.extend(missing.iter().cloned());
1148 if end_with.len() > 0 && group_end.is_none() {
1149 group_end = Some(cnum);
1152 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1153 if end_with.len() == 0 && group_end.is_some() {
1154 group_start = Some(cnum);
1159 // If we didn't end up filling in all lang items from upstream crates then
1160 // we'll be filling it in with our crate. This probably means we're the
1161 // standard library itself, so skip this for now.
1162 if group_end.is_some() && group_start.is_none() {
1166 let mut compiler_builtins = None;
1168 for &(cnum, _) in deps.iter() {
1169 if group_start == Some(cnum) {
1173 // We may not pass all crates through to the linker. Some crates may
1174 // appear statically in an existing dylib, meaning we'll pick up all the
1175 // symbols from the dylib.
1176 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1177 match data[cnum.as_usize() - 1] {
1178 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1179 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1181 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) => {
1182 link_sanitizer_runtime(cmd, sess, codegen_results, tmpdir, cnum);
1184 // compiler-builtins are always placed last to ensure that they're
1185 // linked correctly.
1186 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1187 assert!(compiler_builtins.is_none());
1188 compiler_builtins = Some(cnum);
1190 Linkage::NotLinked |
1191 Linkage::IncludedFromDylib => {}
1192 Linkage::Static => {
1193 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1195 Linkage::Dynamic => {
1196 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1200 if group_end == Some(cnum) {
1205 // compiler-builtins are always placed last to ensure that they're
1206 // linked correctly.
1207 // We must always link the `compiler_builtins` crate statically. Even if it
1208 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1210 if let Some(cnum) = compiler_builtins {
1211 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1214 // Converts a library file-stem into a cc -l argument
1215 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1216 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1223 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1224 // it's packed in a .rlib, it contains stuff that are not objects that will
1225 // make the linker error. So we must remove those bits from the .rlib before
1227 fn link_sanitizer_runtime(cmd: &mut dyn Linker,
1229 codegen_results: &CodegenResults,
1232 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1233 let cratepath = &src.rlib.as_ref().unwrap().0;
1235 if sess.target.target.options.is_like_osx {
1236 // On Apple platforms, the sanitizer is always built as a dylib, and
1237 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1238 // rpath to the library as well (the rpath should be absolute, see
1239 // PR #41352 for details).
1241 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1242 let rpath = cratepath.parent().unwrap();
1243 let rpath = rpath.to_str().expect("non-utf8 component in path");
1244 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1247 let dst = tmpdir.join(cratepath.file_name().unwrap());
1248 let cfg = archive_config(sess, &dst, Some(cratepath));
1249 let mut archive = ArchiveBuilder::new(cfg);
1250 archive.update_symbols();
1252 for f in archive.src_files() {
1253 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1254 archive.remove_file(&f);
1260 cmd.link_whole_rlib(&dst);
1263 // Adds the static "rlib" versions of all crates to the command line.
1264 // There's a bit of magic which happens here specifically related to LTO and
1265 // dynamic libraries. Specifically:
1267 // * For LTO, we remove upstream object files.
1268 // * For dylibs we remove metadata and bytecode from upstream rlibs
1270 // When performing LTO, almost(*) all of the bytecode from the upstream
1271 // libraries has already been included in our object file output. As a
1272 // result we need to remove the object files in the upstream libraries so
1273 // the linker doesn't try to include them twice (or whine about duplicate
1274 // symbols). We must continue to include the rest of the rlib, however, as
1275 // it may contain static native libraries which must be linked in.
1277 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1278 // their bytecode wasn't included. The object files in those libraries must
1279 // still be passed to the linker.
1281 // When making a dynamic library, linkers by default don't include any
1282 // object files in an archive if they're not necessary to resolve the link.
1283 // We basically want to convert the archive (rlib) to a dylib, though, so we
1284 // *do* want everything included in the output, regardless of whether the
1285 // linker thinks it's needed or not. As a result we must use the
1286 // --whole-archive option (or the platform equivalent). When using this
1287 // option the linker will fail if there are non-objects in the archive (such
1288 // as our own metadata and/or bytecode). All in all, for rlibs to be
1289 // entirely included in dylibs, we need to remove all non-object files.
1291 // Note, however, that if we're not doing LTO or we're not producing a dylib
1292 // (aka we're making an executable), we can just pass the rlib blindly to
1293 // the linker (fast) because it's fine if it's not actually included as
1294 // we're at the end of the dependency chain.
1295 fn add_static_crate(cmd: &mut dyn Linker,
1297 codegen_results: &CodegenResults,
1299 crate_type: config::CrateType,
1301 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1302 let cratepath = &src.rlib.as_ref().unwrap().0;
1304 // See the comment above in `link_staticlib` and `link_rlib` for why if
1305 // there's a static library that's not relevant we skip all object
1307 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1308 let skip_native = native_libs.iter().any(|lib| {
1309 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1312 if (!are_upstream_rust_objects_already_included(sess) ||
1313 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1314 crate_type != config::CrateType::Dylib &&
1316 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1320 let dst = tmpdir.join(cratepath.file_name().unwrap());
1321 let name = cratepath.file_name().unwrap().to_str().unwrap();
1322 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1324 time(sess, &format!("altering {}.rlib", name), || {
1325 let cfg = archive_config(sess, &dst, Some(cratepath));
1326 let mut archive = ArchiveBuilder::new(cfg);
1327 archive.update_symbols();
1329 let mut any_objects = false;
1330 for f in archive.src_files() {
1331 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1332 archive.remove_file(&f);
1336 let canonical = f.replace("-", "_");
1337 let canonical_name = name.replace("-", "_");
1339 // Look for `.rcgu.o` at the end of the filename to conclude
1340 // that this is a Rust-related object file.
1341 fn looks_like_rust(s: &str) -> bool {
1342 let path = Path::new(s);
1343 let ext = path.extension().and_then(|s| s.to_str());
1344 if ext != Some(OutputType::Object.extension()) {
1347 let ext2 = path.file_stem()
1348 .and_then(|s| Path::new(s).extension())
1349 .and_then(|s| s.to_str());
1350 ext2 == Some(RUST_CGU_EXT)
1353 let is_rust_object =
1354 canonical.starts_with(&canonical_name) &&
1355 looks_like_rust(&f);
1357 // If we've been requested to skip all native object files
1358 // (those not generated by the rust compiler) then we can skip
1359 // this file. See above for why we may want to do this.
1360 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1362 // If we're performing LTO and this is a rust-generated object
1363 // file, then we don't need the object file as it's part of the
1364 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1365 // though, so we let that object file slide.
1366 let skip_because_lto = are_upstream_rust_objects_already_included(sess) &&
1368 (sess.target.target.options.no_builtins ||
1369 !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1371 if skip_because_cfg_say_so || skip_because_lto {
1372 archive.remove_file(&f);
1383 // If we're creating a dylib, then we need to include the
1384 // whole of each object in our archive into that artifact. This is
1385 // because a `dylib` can be reused as an intermediate artifact.
1387 // Note, though, that we don't want to include the whole of a
1388 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1389 // repeatedly linked anyway.
1390 if crate_type == config::CrateType::Dylib &&
1391 codegen_results.crate_info.compiler_builtins != Some(cnum) {
1392 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1394 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1399 // Same thing as above, but for dynamic crates instead of static crates.
1400 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1401 // If we're performing LTO, then it should have been previously required
1402 // that all upstream rust dependencies were available in an rlib format.
1403 assert!(!are_upstream_rust_objects_already_included(sess));
1405 // Just need to tell the linker about where the library lives and
1407 let parent = cratepath.parent();
1408 if let Some(dir) = parent {
1409 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1411 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1412 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1413 parent.unwrap_or(Path::new("")));
1417 // Link in all of our upstream crates' native dependencies. Remember that
1418 // all of these upstream native dependencies are all non-static
1419 // dependencies. We've got two cases then:
1421 // 1. The upstream crate is an rlib. In this case we *must* link in the
1422 // native dependency because the rlib is just an archive.
1424 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1425 // have the dependency present on the system somewhere. Thus, we don't
1426 // gain a whole lot from not linking in the dynamic dependency to this
1429 // The use case for this is a little subtle. In theory the native
1430 // dependencies of a crate are purely an implementation detail of the crate
1431 // itself, but the problem arises with generic and inlined functions. If a
1432 // generic function calls a native function, then the generic function must
1433 // be instantiated in the target crate, meaning that the native symbol must
1434 // also be resolved in the target crate.
1435 fn add_upstream_native_libraries(cmd: &mut dyn Linker,
1437 codegen_results: &CodegenResults,
1438 crate_type: config::CrateType) {
1439 // Be sure to use a topological sorting of crates because there may be
1440 // interdependencies between native libraries. When passing -nodefaultlibs,
1441 // for example, almost all native libraries depend on libc, so we have to
1442 // make sure that's all the way at the right (liblibc is near the base of
1443 // the dependency chain).
1445 // This passes RequireStatic, but the actual requirement doesn't matter,
1446 // we're just getting an ordering of crate numbers, we're not worried about
1448 let formats = sess.dependency_formats.borrow();
1449 let data = formats.get(&crate_type).unwrap();
1451 let crates = &codegen_results.crate_info.used_crates_static;
1452 for &(cnum, _) in crates {
1453 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1454 let name = match lib.name {
1458 if !relevant_lib(sess, &lib) {
1462 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&name.as_str()),
1463 NativeLibraryKind::NativeFramework => cmd.link_framework(&name.as_str()),
1464 NativeLibraryKind::NativeStaticNobundle => {
1465 // Link "static-nobundle" native libs only if the crate they originate from
1466 // is being linked statically to the current crate. If it's linked dynamically
1467 // or is an rlib already included via some other dylib crate, the symbols from
1468 // native libs will have already been included in that dylib.
1469 if data[cnum.as_usize() - 1] == Linkage::Static {
1470 cmd.link_staticlib(&name.as_str())
1473 // ignore statically included native libraries here as we've
1474 // already included them when we included the rust library
1476 NativeLibraryKind::NativeStatic => {}
1482 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1484 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1489 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1493 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1494 // any upstream object files have not been copied yet.
1495 !sess.opts.debugging_opts.cross_lang_lto.enabled()
1498 Lto::ThinLocal => false,