1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use cc
::windows_registry
;
13 use super::archive
::{ArchiveBuilder, ArchiveConfig}
;
14 use super::bytecode
::RLIB_BYTECODE_EXTENSION
;
15 use super::linker
::Linker
;
16 use super::command
::Command
;
17 use super::rpath
::RPathConfig
;
19 use metadata
::METADATA_FILENAME
;
20 use rustc
::session
::config
::{self, NoDebugInfo, OutputFilenames, OutputType, PrintRequest}
;
21 use rustc
::session
::config
::{RUST_CGU_EXT, Lto}
;
22 use rustc
::session
::filesearch
;
23 use rustc
::session
::search_paths
::PathKind
;
24 use rustc
::session
::Session
;
25 use rustc
::middle
::cstore
::{NativeLibrary, LibSource, NativeLibraryKind}
;
26 use rustc
::middle
::dependency_format
::Linkage
;
27 use {CodegenResults, CrateInfo}
;
28 use rustc
::util
::common
::time
;
29 use rustc
::util
::fs
::fix_windows_verbatim_for_gcc
;
30 use rustc
::hir
::def_id
::CrateNum
;
32 use rustc_target
::spec
::{PanicStrategy, RelroLevel, LinkerFlavor, TargetTriple}
;
33 use rustc_data_structures
::fx
::FxHashSet
;
34 use context
::get_reloc_model
;
43 use std
::path
::{Path, PathBuf}
;
44 use std
::process
::{Output, Stdio}
;
48 /// The LLVM module name containing crate-metadata. This includes a `.` on
49 /// purpose, so it cannot clash with the name of a user-defined module.
50 pub const METADATA_MODULE_NAME
: &'
static str = "crate.metadata";
52 // same as for metadata above, but for allocator shim
53 pub const ALLOCATOR_MODULE_NAME
: &'
static str = "crate.allocator";
55 pub use rustc_codegen_utils
::link
::{find_crate_name
, filename_for_input
, default_output_for_target
,
56 invalid_output_for_target
, build_link_meta
, out_filename
,
57 check_file_is_writeable
};
59 // The third parameter is for env vars, used on windows to set up the
60 // path for MSVC to find its DLLs, and gcc to find its bundled
62 pub fn get_linker(sess
: &Session
) -> (PathBuf
, Command
) {
63 // If our linker looks like a batch script on Windows then to execute this
64 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
65 // emscripten where the linker is `emcc.bat` and needs to be spawned as
66 // `cmd /c emcc.bat ...`.
68 // This worked historically but is needed manually since #42436 (regression
69 // was tagged as #42791) and some more info can be found on #44443 for
71 let cmd
= |linker
: &Path
| {
72 if let Some(linker
) = linker
.to_str() {
73 if cfg
!(windows
) && linker
.ends_with(".bat") {
74 return Command
::bat_script(linker
)
77 match sess
.linker_flavor() {
78 LinkerFlavor
::Lld(f
) => Command
::lld(linker
, f
),
79 _
=> Command
::new(linker
),
84 let msvc_tool
= windows_registry
::find_tool(&sess
.opts
.target_triple
.triple(), "link.exe");
86 let linker_path
= sess
.opts
.cg
.linker
.as_ref().map(|s
| &**s
)
87 .or(sess
.target
.target
.options
.linker
.as_ref().map(|s
| s
.as_ref()))
88 .unwrap_or(match sess
.linker_flavor() {
89 LinkerFlavor
::Msvc
=> {
90 msvc_tool
.as_ref().map(|t
| t
.path()).unwrap_or("link.exe".as_ref())
92 LinkerFlavor
::Em
if cfg
!(windows
) => "emcc.bat".as_ref(),
93 LinkerFlavor
::Em
=> "emcc".as_ref(),
94 LinkerFlavor
::Gcc
=> "cc".as_ref(),
95 LinkerFlavor
::Ld
=> "ld".as_ref(),
96 LinkerFlavor
::Lld(_
) => "lld".as_ref(),
99 let mut cmd
= cmd(linker_path
);
101 // The compiler's sysroot often has some bundled tools, so add it to the
102 // PATH for the child.
103 let mut new_path
= sess
.host_filesearch(PathKind
::All
)
104 .get_tools_search_paths();
105 let mut msvc_changed_path
= false;
106 if sess
.target
.target
.options
.is_like_msvc
{
107 if let Some(ref tool
) = msvc_tool
{
108 cmd
.args(tool
.args());
109 for &(ref k
, ref v
) in tool
.env() {
111 new_path
.extend(env
::split_paths(v
));
112 msvc_changed_path
= true;
120 if !msvc_changed_path
{
121 if let Some(path
) = env
::var_os("PATH") {
122 new_path
.extend(env
::split_paths(&path
));
125 cmd
.env("PATH", env
::join_paths(new_path
).unwrap());
127 (linker_path
.to_path_buf(), cmd
)
130 pub fn remove(sess
: &Session
, path
: &Path
) {
131 match fs
::remove_file(path
) {
134 sess
.err(&format
!("failed to remove {}: {}",
141 /// Perform the linkage portion of the compilation phase. This will generate all
142 /// of the requested outputs for this compilation session.
143 pub(crate) fn link_binary(sess
: &Session
,
144 codegen_results
: &CodegenResults
,
145 outputs
: &OutputFilenames
,
146 crate_name
: &str) -> Vec
<PathBuf
> {
147 let mut out_filenames
= Vec
::new();
148 for &crate_type
in sess
.crate_types
.borrow().iter() {
149 // Ignore executable crates if we have -Z no-codegen, as they will error.
150 let output_metadata
= sess
.opts
.output_types
.contains_key(&OutputType
::Metadata
);
151 if (sess
.opts
.debugging_opts
.no_codegen
|| !sess
.opts
.output_types
.should_codegen()) &&
153 crate_type
== config
::CrateTypeExecutable
{
157 if invalid_output_for_target(sess
, crate_type
) {
158 bug
!("invalid output type `{:?}` for target os `{}`",
159 crate_type
, sess
.opts
.target_triple
);
161 let mut out_files
= link_binary_output(sess
,
166 out_filenames
.append(&mut out_files
);
169 // Remove the temporary object file and metadata if we aren't saving temps
170 if !sess
.opts
.cg
.save_temps
{
171 if sess
.opts
.output_types
.should_codegen() &&
172 !preserve_objects_for_their_debuginfo(sess
)
174 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
178 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.bytecode_compressed
.as_ref()) {
181 if let Some(ref obj
) = codegen_results
.metadata_module
.object
{
184 if let Some(ref allocator
) = codegen_results
.allocator_module
{
185 if let Some(ref obj
) = allocator
.object
{
188 if let Some(ref bc
) = allocator
.bytecode_compressed
{
197 /// Returns a boolean indicating whether we should preserve the object files on
198 /// the filesystem for their debug information. This is often useful with
199 /// split-dwarf like schemes.
200 fn preserve_objects_for_their_debuginfo(sess
: &Session
) -> bool
{
201 // If the objects don't have debuginfo there's nothing to preserve.
202 if sess
.opts
.debuginfo
== NoDebugInfo
{
206 // If we're only producing artifacts that are archives, no need to preserve
207 // the objects as they're losslessly contained inside the archives.
208 let output_linked
= sess
.crate_types
.borrow()
210 .any(|x
| *x
!= config
::CrateTypeRlib
&& *x
!= config
::CrateTypeStaticlib
);
215 // If we're on OSX then the equivalent of split dwarf is turned on by
216 // default. The final executable won't actually have any debug information
217 // except it'll have pointers to elsewhere. Historically we've always run
218 // `dsymutil` to "link all the dwarf together" but this is actually sort of
219 // a bummer for incremental compilation! (the whole point of split dwarf is
220 // that you don't do this sort of dwarf link).
222 // Basically as a result this just means that if we're on OSX and we're
223 // *not* running dsymutil then the object files are the only source of truth
224 // for debug information, so we must preserve them.
225 if sess
.target
.target
.options
.is_like_osx
{
226 match sess
.opts
.debugging_opts
.run_dsymutil
{
227 // dsymutil is not being run, preserve objects
228 Some(false) => return true,
230 // dsymutil is being run, no need to preserve the objects
231 Some(true) => return false,
233 // The default historical behavior was to always run dsymutil, so
234 // we're preserving that temporarily, but we're likely to switch the
236 None
=> return false,
243 fn filename_for_metadata(sess
: &Session
, crate_name
: &str, outputs
: &OutputFilenames
) -> PathBuf
{
244 let out_filename
= outputs
.single_output_file
.clone()
247 .join(&format
!("lib{}{}.rmeta", crate_name
, sess
.opts
.cg
.extra_filename
)));
248 check_file_is_writeable(&out_filename
, sess
);
252 pub(crate) fn each_linked_rlib(sess
: &Session
,
254 f
: &mut FnMut(CrateNum
, &Path
)) -> Result
<(), String
> {
255 let crates
= info
.used_crates_static
.iter();
256 let fmts
= sess
.dependency_formats
.borrow();
257 let fmts
= fmts
.get(&config
::CrateTypeExecutable
)
258 .or_else(|| fmts
.get(&config
::CrateTypeStaticlib
))
259 .or_else(|| fmts
.get(&config
::CrateTypeCdylib
))
260 .or_else(|| fmts
.get(&config
::CrateTypeProcMacro
));
261 let fmts
= match fmts
{
263 None
=> return Err(format
!("could not find formats for rlibs"))
265 for &(cnum
, ref path
) in crates
{
266 match fmts
.get(cnum
.as_usize() - 1) {
267 Some(&Linkage
::NotLinked
) |
268 Some(&Linkage
::IncludedFromDylib
) => continue,
270 None
=> return Err(format
!("could not find formats for rlibs"))
272 let name
= &info
.crate_name
[&cnum
];
273 let path
= match *path
{
274 LibSource
::Some(ref p
) => p
,
275 LibSource
::MetadataOnly
=> {
276 return Err(format
!("could not find rlib for: `{}`, found rmeta (metadata) file",
280 return Err(format
!("could not find rlib for: `{}`", name
))
288 /// Returns a boolean indicating whether the specified crate should be ignored
291 /// Crates ignored during LTO are not lumped together in the "massive object
292 /// file" that we create and are linked in their normal rlib states. See
293 /// comments below for what crates do not participate in LTO.
295 /// It's unusual for a crate to not participate in LTO. Typically only
296 /// compiler-specific and unstable crates have a reason to not participate in
298 pub(crate) fn ignored_for_lto(sess
: &Session
, info
: &CrateInfo
, cnum
: CrateNum
) -> bool
{
299 // If our target enables builtin function lowering in LLVM then the
300 // crates providing these functions don't participate in LTO (e.g.
301 // no_builtins or compiler builtins crates).
302 !sess
.target
.target
.options
.no_builtins
&&
303 (info
.is_no_builtins
.contains(&cnum
) || info
.compiler_builtins
== Some(cnum
))
306 fn link_binary_output(sess
: &Session
,
307 codegen_results
: &CodegenResults
,
308 crate_type
: config
::CrateType
,
309 outputs
: &OutputFilenames
,
310 crate_name
: &str) -> Vec
<PathBuf
> {
311 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
312 check_file_is_writeable(obj
, sess
);
315 let mut out_filenames
= vec
![];
317 if outputs
.outputs
.contains_key(&OutputType
::Metadata
) {
318 let out_filename
= filename_for_metadata(sess
, crate_name
, outputs
);
319 // To avoid races with another rustc process scanning the output directory,
320 // we need to write the file somewhere else and atomically move it to its
321 // final destination, with a `fs::rename` call. In order for the rename to
322 // always succeed, the temporary file needs to be on the same filesystem,
323 // which is why we create it inside the output directory specifically.
324 let metadata_tmpdir
= match TempDir
::new_in(out_filename
.parent().unwrap(), "rmeta") {
325 Ok(tmpdir
) => tmpdir
,
326 Err(err
) => sess
.fatal(&format
!("couldn't create a temp dir: {}", err
)),
328 let metadata
= emit_metadata(sess
, codegen_results
, &metadata_tmpdir
);
329 if let Err(e
) = fs
::rename(metadata
, &out_filename
) {
330 sess
.fatal(&format
!("failed to write {}: {}", out_filename
.display(), e
));
332 out_filenames
.push(out_filename
);
335 let tmpdir
= match TempDir
::new("rustc") {
336 Ok(tmpdir
) => tmpdir
,
337 Err(err
) => sess
.fatal(&format
!("couldn't create a temp dir: {}", err
)),
340 if outputs
.outputs
.should_codegen() {
341 let out_filename
= out_filename(sess
, crate_type
, outputs
, crate_name
);
343 config
::CrateTypeRlib
=> {
350 config
::CrateTypeStaticlib
=> {
351 link_staticlib(sess
, codegen_results
, &out_filename
, &tmpdir
);
354 link_natively(sess
, crate_type
, &out_filename
, codegen_results
, tmpdir
.path());
357 out_filenames
.push(out_filename
);
360 if sess
.opts
.cg
.save_temps
{
361 let _
= tmpdir
.into_path();
367 fn archive_search_paths(sess
: &Session
) -> Vec
<PathBuf
> {
368 let mut search
= Vec
::new();
369 sess
.target_filesearch(PathKind
::Native
).for_each_lib_search_path(|path
, _
| {
370 search
.push(path
.to_path_buf());
375 fn archive_config
<'a
>(sess
: &'a Session
,
377 input
: Option
<&Path
>) -> ArchiveConfig
<'a
> {
380 dst
: output
.to_path_buf(),
381 src
: input
.map(|p
| p
.to_path_buf()),
382 lib_search_paths
: archive_search_paths(sess
),
386 /// We use a temp directory here to avoid races between concurrent rustc processes,
387 /// such as builds in the same directory using the same filename for metadata while
388 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
389 /// directory being searched for `extern crate` (observing an incomplete file).
390 /// The returned path is the temporary file containing the complete metadata.
391 fn emit_metadata
<'a
>(sess
: &'a Session
, codegen_results
: &CodegenResults
, tmpdir
: &TempDir
)
393 let out_filename
= tmpdir
.path().join(METADATA_FILENAME
);
394 let result
= fs
::write(&out_filename
, &codegen_results
.metadata
.raw_data
);
396 if let Err(e
) = result
{
397 sess
.fatal(&format
!("failed to write {}: {}", out_filename
.display(), e
));
410 // An rlib in its current incarnation is essentially a renamed .a file. The
411 // rlib primarily contains the object file of the crate, but it also contains
412 // all of the object files from native libraries. This is done by unzipping
413 // native libraries and inserting all of the contents into this archive.
414 fn link_rlib
<'a
>(sess
: &'a Session
,
415 codegen_results
: &CodegenResults
,
418 tmpdir
: &TempDir
) -> ArchiveBuilder
<'a
> {
419 info
!("preparing rlib to {:?}", out_filename
);
420 let mut ab
= ArchiveBuilder
::new(archive_config(sess
, out_filename
, None
));
422 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
426 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
427 // we may not be configured to actually include a static library if we're
428 // adding it here. That's because later when we consume this rlib we'll
429 // decide whether we actually needed the static library or not.
431 // To do this "correctly" we'd need to keep track of which libraries added
432 // which object files to the archive. We don't do that here, however. The
433 // #[link(cfg(..))] feature is unstable, though, and only intended to get
434 // liblibc working. In that sense the check below just indicates that if
435 // there are any libraries we want to omit object files for at link time we
436 // just exclude all custom object files.
438 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
439 // feature then we'll need to figure out how to record what objects were
440 // loaded from the libraries found here and then encode that into the
441 // metadata of the rlib we're generating somehow.
442 for lib
in codegen_results
.crate_info
.used_libraries
.iter() {
444 NativeLibraryKind
::NativeStatic
=> {}
445 NativeLibraryKind
::NativeStaticNobundle
|
446 NativeLibraryKind
::NativeFramework
|
447 NativeLibraryKind
::NativeUnknown
=> continue,
449 ab
.add_native_library(&lib
.name
.as_str());
452 // After adding all files to the archive, we need to update the
453 // symbol table of the archive.
456 // Note that it is important that we add all of our non-object "magical
457 // files" *after* all of the object files in the archive. The reason for
458 // this is as follows:
460 // * When performing LTO, this archive will be modified to remove
461 // objects from above. The reason for this is described below.
463 // * When the system linker looks at an archive, it will attempt to
464 // determine the architecture of the archive in order to see whether its
467 // The algorithm for this detection is: iterate over the files in the
468 // archive. Skip magical SYMDEF names. Interpret the first file as an
469 // object file. Read architecture from the object file.
471 // * As one can probably see, if "metadata" and "foo.bc" were placed
472 // before all of the objects, then the architecture of this archive would
473 // not be correctly inferred once 'foo.o' is removed.
475 // Basically, all this means is that this code should not move above the
478 RlibFlavor
::Normal
=> {
479 // Instead of putting the metadata in an object file section, rlibs
480 // contain the metadata in a separate file.
481 ab
.add_file(&emit_metadata(sess
, codegen_results
, tmpdir
));
483 // For LTO purposes, the bytecode of this library is also inserted
485 for bytecode
in codegen_results
488 .filter_map(|m
| m
.bytecode_compressed
.as_ref())
490 ab
.add_file(bytecode
);
493 // After adding all files to the archive, we need to update the
494 // symbol table of the archive. This currently dies on macOS (see
495 // #11162), and isn't necessary there anyway
496 if !sess
.target
.target
.options
.is_like_osx
{
501 RlibFlavor
::StaticlibBase
=> {
502 let obj
= codegen_results
.allocator_module
504 .and_then(|m
| m
.object
.as_ref());
505 if let Some(obj
) = obj
{
514 // Create a static archive
516 // This is essentially the same thing as an rlib, but it also involves adding
517 // all of the upstream crates' objects into the archive. This will slurp in
518 // all of the native libraries of upstream dependencies as well.
520 // Additionally, there's no way for us to link dynamic libraries, so we warn
521 // about all dynamic library dependencies that they're not linked in.
523 // There's no need to include metadata in a static archive, so ensure to not
524 // link in the metadata object file (and also don't prepare the archive with a
526 fn link_staticlib(sess
: &Session
,
527 codegen_results
: &CodegenResults
,
530 let mut ab
= link_rlib(sess
,
532 RlibFlavor
::StaticlibBase
,
535 let mut all_native_libs
= vec
![];
537 let res
= each_linked_rlib(sess
, &codegen_results
.crate_info
, &mut |cnum
, path
| {
538 let name
= &codegen_results
.crate_info
.crate_name
[&cnum
];
539 let native_libs
= &codegen_results
.crate_info
.native_libraries
[&cnum
];
541 // Here when we include the rlib into our staticlib we need to make a
542 // decision whether to include the extra object files along the way.
543 // These extra object files come from statically included native
544 // libraries, but they may be cfg'd away with #[link(cfg(..))].
546 // This unstable feature, though, only needs liblibc to work. The only
547 // use case there is where musl is statically included in liblibc.rlib,
548 // so if we don't want the included version we just need to skip it. As
549 // a result the logic here is that if *any* linked library is cfg'd away
550 // we just skip all object files.
552 // Clearly this is not sufficient for a general purpose feature, and
553 // we'd want to read from the library's metadata to determine which
554 // object files come from where and selectively skip them.
555 let skip_object_files
= native_libs
.iter().any(|lib
| {
556 lib
.kind
== NativeLibraryKind
::NativeStatic
&& !relevant_lib(sess
, lib
)
560 is_full_lto_enabled(sess
) &&
561 !ignored_for_lto(sess
, &codegen_results
.crate_info
, cnum
),
562 skip_object_files
).unwrap();
564 all_native_libs
.extend(codegen_results
.crate_info
.native_libraries
[&cnum
].iter().cloned());
566 if let Err(e
) = res
{
573 if !all_native_libs
.is_empty() {
574 if sess
.opts
.prints
.contains(&PrintRequest
::NativeStaticLibs
) {
575 print_native_static_libs(sess
, &all_native_libs
);
580 fn print_native_static_libs(sess
: &Session
, all_native_libs
: &[NativeLibrary
]) {
581 let lib_args
: Vec
<_
> = all_native_libs
.iter()
582 .filter(|l
| relevant_lib(sess
, l
))
583 .filter_map(|lib
| match lib
.kind
{
584 NativeLibraryKind
::NativeStaticNobundle
|
585 NativeLibraryKind
::NativeUnknown
=> {
586 if sess
.target
.target
.options
.is_like_msvc
{
587 Some(format
!("{}.lib", lib
.name
))
589 Some(format
!("-l{}", lib
.name
))
592 NativeLibraryKind
::NativeFramework
=> {
593 // ld-only syntax, since there are no frameworks in MSVC
594 Some(format
!("-framework {}", lib
.name
))
596 // These are included, no need to print them
597 NativeLibraryKind
::NativeStatic
=> None
,
600 if !lib_args
.is_empty() {
601 sess
.note_without_error("Link against the following native artifacts when linking \
602 against this static library. The order and any duplication \
603 can be significant on some platforms.");
604 // Prefix for greppability
605 sess
.note_without_error(&format
!("native-static-libs: {}", &lib_args
.join(" ")));
609 // Create a dynamic library or executable
611 // This will invoke the system linker/cc to create the resulting file. This
612 // links to all upstream files as well.
613 fn link_natively(sess
: &Session
,
614 crate_type
: config
::CrateType
,
616 codegen_results
: &CodegenResults
,
618 info
!("preparing {:?} to {:?}", crate_type
, out_filename
);
619 let flavor
= sess
.linker_flavor();
621 // The invocations of cc share some flags across platforms
622 let (pname
, mut cmd
) = get_linker(sess
);
624 let root
= sess
.target_filesearch(PathKind
::Native
).get_lib_path();
625 if let Some(args
) = sess
.target
.target
.options
.pre_link_args
.get(&flavor
) {
628 if let Some(args
) = sess
.target
.target
.options
.pre_link_args_crt
.get(&flavor
) {
629 if sess
.crt_static() {
633 if let Some(ref args
) = sess
.opts
.debugging_opts
.pre_link_args
{
636 cmd
.args(&sess
.opts
.debugging_opts
.pre_link_arg
);
638 let pre_link_objects
= if crate_type
== config
::CrateTypeExecutable
{
639 &sess
.target
.target
.options
.pre_link_objects_exe
641 &sess
.target
.target
.options
.pre_link_objects_dll
643 for obj
in pre_link_objects
{
644 cmd
.arg(root
.join(obj
));
647 if crate_type
== config
::CrateTypeExecutable
&& sess
.crt_static() {
648 for obj
in &sess
.target
.target
.options
.pre_link_objects_exe_crt
{
649 cmd
.arg(root
.join(obj
));
653 if sess
.target
.target
.options
.is_like_emscripten
{
655 cmd
.arg(if sess
.panic_strategy() == PanicStrategy
::Abort
{
656 "DISABLE_EXCEPTION_CATCHING=1"
658 "DISABLE_EXCEPTION_CATCHING=0"
663 let mut linker
= codegen_results
.linker_info
.to_linker(cmd
, &sess
);
664 link_args(&mut *linker
, sess
, crate_type
, tmpdir
,
665 out_filename
, codegen_results
);
666 cmd
= linker
.finalize();
668 if let Some(args
) = sess
.target
.target
.options
.late_link_args
.get(&flavor
) {
671 for obj
in &sess
.target
.target
.options
.post_link_objects
{
672 cmd
.arg(root
.join(obj
));
674 if sess
.crt_static() {
675 for obj
in &sess
.target
.target
.options
.post_link_objects_crt
{
676 cmd
.arg(root
.join(obj
));
679 if let Some(args
) = sess
.target
.target
.options
.post_link_args
.get(&flavor
) {
682 for &(ref k
, ref v
) in &sess
.target
.target
.options
.link_env
{
686 if sess
.opts
.debugging_opts
.print_link_args
{
687 println
!("{:?}", &cmd
);
690 // May have not found libraries in the right formats.
691 sess
.abort_if_errors();
693 // Invoke the system linker
695 // Note that there's a terribly awful hack that really shouldn't be present
696 // in any compiler. Here an environment variable is supported to
697 // automatically retry the linker invocation if the linker looks like it
700 // Gee that seems odd, normally segfaults are things we want to know about!
701 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
702 // linker segfaulting on Travis quite a bit which is causing quite a bit of
703 // pain to land PRs when they spuriously fail due to a segfault.
705 // The issue #38878 has some more debugging information on it as well, but
706 // this unfortunately looks like it's just a race condition in macOS's linker
707 // with some thread pool working in the background. It seems that no one
708 // currently knows a fix for this so in the meantime we're left with this...
710 let retry_on_segfault
= env
::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
715 prog
= time(sess
, "running linker", || {
716 exec_linker(sess
, &mut cmd
, out_filename
, tmpdir
)
718 let output
= match prog
{
719 Ok(ref output
) => output
,
722 if output
.status
.success() {
725 let mut out
= output
.stderr
.clone();
726 out
.extend(&output
.stdout
);
727 let out
= String
::from_utf8_lossy(&out
);
729 // Check to see if the link failed with "unrecognized command line option:
730 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
731 // reperform the link step without the -no-pie option. This is safe because
732 // if the linker doesn't support -no-pie then it should not default to
733 // linking executables as pie. Different versions of gcc seem to use
734 // different quotes in the error message so don't check for them.
735 if sess
.target
.target
.options
.linker_is_gnu
&&
736 sess
.linker_flavor() != LinkerFlavor
::Ld
&&
737 (out
.contains("unrecognized command line option") ||
738 out
.contains("unknown argument")) &&
739 out
.contains("-no-pie") &&
740 cmd
.get_args().iter().any(|e
| e
.to_string_lossy() == "-no-pie") {
741 info
!("linker output: {:?}", out
);
742 warn
!("Linker does not support -no-pie command line option. Retrying without.");
743 for arg
in cmd
.take_args() {
744 if arg
.to_string_lossy() != "-no-pie" {
751 if !retry_on_segfault
|| i
> 3 {
754 let msg_segv
= "clang: error: unable to execute command: Segmentation fault: 11";
755 let msg_bus
= "clang: error: unable to execute command: Bus error: 10";
756 if !(out
.contains(msg_segv
) || out
.contains(msg_bus
)) {
761 "looks like the linker segfaulted when we tried to call it, \
762 automatically retrying again. cmd = {:?}, out = {}.",
770 fn escape_string(s
: &[u8]) -> String
{
771 str::from_utf8(s
).map(|s
| s
.to_owned())
772 .unwrap_or_else(|_
| {
773 let mut x
= "Non-UTF-8 output: ".to_string();
775 .flat_map(|&b
| ascii
::escape_default(b
))
776 .map(|b
| char::from_u32(b
as u32).unwrap()));
780 if !prog
.status
.success() {
781 let mut output
= prog
.stderr
.clone();
782 output
.extend_from_slice(&prog
.stdout
);
783 sess
.struct_err(&format
!("linking with `{}` failed: {}",
786 .note(&format
!("{:?}", &cmd
))
787 .note(&escape_string(&output
))
789 sess
.abort_if_errors();
791 info
!("linker stderr:\n{}", escape_string(&prog
.stderr
));
792 info
!("linker stdout:\n{}", escape_string(&prog
.stdout
));
795 let linker_not_found
= e
.kind() == io
::ErrorKind
::NotFound
;
797 let mut linker_error
= {
798 if linker_not_found
{
799 sess
.struct_err(&format
!("linker `{}` not found", pname
.display()))
801 sess
.struct_err(&format
!("could not exec the linker `{}`", pname
.display()))
805 linker_error
.note(&format
!("{}", e
));
807 if !linker_not_found
{
808 linker_error
.note(&format
!("{:?}", &cmd
));
813 if sess
.target
.target
.options
.is_like_msvc
&& linker_not_found
{
814 sess
.note_without_error("the msvc targets depend on the msvc linker \
815 but `link.exe` was not found");
816 sess
.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
817 with the Visual C++ option");
819 sess
.abort_if_errors();
824 // On macOS, debuggers need this utility to get run to do some munging of
825 // the symbols. Note, though, that if the object files are being preserved
826 // for their debug information there's no need for us to run dsymutil.
827 if sess
.target
.target
.options
.is_like_osx
&&
828 sess
.opts
.debuginfo
!= NoDebugInfo
&&
829 !preserve_objects_for_their_debuginfo(sess
)
831 match Command
::new("dsymutil").arg(out_filename
).output() {
833 Err(e
) => sess
.fatal(&format
!("failed to run dsymutil: {}", e
)),
837 if sess
.opts
.target_triple
== TargetTriple
::from_triple("wasm32-unknown-unknown") {
838 wasm
::rewrite_imports(&out_filename
, &codegen_results
.crate_info
.wasm_imports
);
839 wasm
::add_custom_sections(&out_filename
,
840 &codegen_results
.crate_info
.wasm_custom_sections
);
844 fn exec_linker(sess
: &Session
, cmd
: &mut Command
, out_filename
: &Path
, tmpdir
: &Path
)
845 -> io
::Result
<Output
>
847 // When attempting to spawn the linker we run a risk of blowing out the
848 // size limits for spawning a new process with respect to the arguments
849 // we pass on the command line.
851 // Here we attempt to handle errors from the OS saying "your list of
852 // arguments is too big" by reinvoking the linker again with an `@`-file
853 // that contains all the arguments. The theory is that this is then
854 // accepted on all linkers and the linker will read all its options out of
855 // there instead of looking at the command line.
856 if !cmd
.very_likely_to_exceed_some_spawn_limit() {
857 match cmd
.command().stdout(Stdio
::piped()).stderr(Stdio
::piped()).spawn() {
859 let output
= child
.wait_with_output();
860 flush_linked_file(&output
, out_filename
)?
;
863 Err(ref e
) if command_line_too_big(e
) => {
864 info
!("command line to linker was too big: {}", e
);
866 Err(e
) => return Err(e
)
870 info
!("falling back to passing arguments to linker via an @-file");
871 let mut cmd2
= cmd
.clone();
872 let mut args
= String
::new();
873 for arg
in cmd2
.take_args() {
874 args
.push_str(&Escape
{
875 arg
: arg
.to_str().unwrap(),
876 is_like_msvc
: sess
.target
.target
.options
.is_like_msvc
,
880 let file
= tmpdir
.join("linker-arguments");
881 let bytes
= if sess
.target
.target
.options
.is_like_msvc
{
882 let mut out
= vec
![];
883 // start the stream with a UTF-16 BOM
884 for c
in vec
![0xFEFF].into_iter().chain(args
.encode_utf16()) {
885 // encode in little endian
887 out
.push((c
>> 8) as u8);
893 fs
::write(&file
, &bytes
)?
;
894 cmd2
.arg(format
!("@{}", file
.display()));
895 info
!("invoking linker {:?}", cmd2
);
896 let output
= cmd2
.output();
897 flush_linked_file(&output
, out_filename
)?
;
901 fn flush_linked_file(_
: &io
::Result
<Output
>, _
: &Path
) -> io
::Result
<()> {
906 fn flush_linked_file(command_output
: &io
::Result
<Output
>, out_filename
: &Path
)
909 // On Windows, under high I/O load, output buffers are sometimes not flushed,
910 // even long after process exit, causing nasty, non-reproducible output bugs.
912 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
914 // А full writeup of the original Chrome bug can be found at
915 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
917 if let &Ok(ref out
) = command_output
{
918 if out
.status
.success() {
919 if let Ok(of
) = fs
::OpenOptions
::new().write(true).open(out_filename
) {
929 fn command_line_too_big(err
: &io
::Error
) -> bool
{
930 err
.raw_os_error() == Some(::libc
::E2BIG
)
934 fn command_line_too_big(err
: &io
::Error
) -> bool
{
935 const ERROR_FILENAME_EXCED_RANGE
: i32 = 206;
936 err
.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE
)
944 impl<'a
> fmt
::Display
for Escape
<'a
> {
945 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
946 if self.is_like_msvc
{
947 // This is "documented" at
948 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
950 // Unfortunately there's not a great specification of the
951 // syntax I could find online (at least) but some local
952 // testing showed that this seemed sufficient-ish to catch
953 // at least a few edge cases.
955 for c
in self.arg
.chars() {
957 '
"' => write!(f, "\\{}
", c)?,
958 c => write!(f, "{}
", c)?,
963 // This is documented at https://linux.die.net/man/1/ld, namely:
965 // > Options in file are separated by whitespace. A whitespace
966 // > character may be included in an option by surrounding the
967 // > entire option in either single or double quotes. Any
968 // > character (including a backslash) may be included by
969 // > prefixing the character to be included with a backslash.
971 // We put an argument on each line, so all we need to do is
972 // ensure the line is interpreted as one whole argument.
973 for c in self.arg.chars() {
976 ' ' => write!(f, "\\{}
", c)?,
977 c => write!(f, "{}
", c)?,
986 fn link_args(cmd: &mut Linker,
988 crate_type: config::CrateType,
991 codegen_results: &CodegenResults) {
993 // Linker plugins should be specified early in the list of arguments
994 cmd.cross_lang_lto();
996 // The default library location, we need this to find the runtime.
997 // The location of crates will be determined as needed.
998 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1000 // target descriptor
1001 let t = &sess.target.target;
1003 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1004 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1005 cmd.add_object(obj);
1007 cmd.output_filename(out_filename);
1009 if crate_type == config::CrateTypeExecutable &&
1010 sess.target.target.options.is_like_windows {
1011 if let Some(ref s) = codegen_results.windows_subsystem {
1016 // If we're building a dynamic library then some platforms need to make sure
1017 // that all symbols are exported correctly from the dynamic library.
1018 if crate_type != config::CrateTypeExecutable ||
1019 sess.target.target.options.is_like_emscripten {
1020 cmd.export_symbols(tmpdir, crate_type);
1023 // When linking a dynamic library, we put the metadata into a section of the
1024 // executable. This metadata is in a separate object file from the main
1025 // object file, so we link that in here.
1026 if crate_type == config::CrateTypeDylib ||
1027 crate_type == config::CrateTypeProcMacro {
1028 if let Some(obj) = codegen_results.metadata_module.object.as_ref() {
1029 cmd.add_object(obj);
1033 let obj = codegen_results.allocator_module
1035 .and_then(|m| m.object.as_ref());
1036 if let Some(obj) = obj {
1037 cmd.add_object(obj);
1040 // Try to strip as much out of the generated object by removing unused
1041 // sections if possible. See more comments in linker.rs
1042 if !sess.opts.cg.link_dead_code {
1043 let keep_metadata = crate_type == config::CrateTypeDylib;
1044 cmd.gc_sections(keep_metadata);
1047 let used_link_args = &codegen_results.crate_info.link_args;
1049 if crate_type == config::CrateTypeExecutable {
1050 let mut position_independent_executable = false;
1052 if t.options.position_independent_executables {
1053 let empty_vec = Vec::new();
1054 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1055 let more_args = &sess.opts.cg.link_arg;
1056 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1058 if get_reloc_model(sess) == llvm::RelocMode::PIC
1059 && !sess.crt_static() && !args.any(|x| *x == "-static") {
1060 position_independent_executable = true;
1064 if position_independent_executable {
1065 cmd.position_independent_executable();
1067 // recent versions of gcc can be configured to generate position
1068 // independent executables by default. We have to pass -no-pie to
1069 // explicitly turn that off. Not applicable to ld.
1070 if sess.target.target.options.linker_is_gnu
1071 && sess.linker_flavor() != LinkerFlavor::Ld {
1072 cmd.no_position_independent_executable();
1077 let relro_level = match sess.opts.debugging_opts.relro_level {
1078 Some(level) => level,
1079 None => t.options.relro_level,
1082 RelroLevel::Full => {
1085 RelroLevel::Partial => {
1086 cmd.partial_relro();
1088 RelroLevel::Off => {
1091 RelroLevel::None => {
1095 // Pass optimization flags down to the linker.
1098 // Pass debuginfo flags down to the linker.
1101 // We want to prevent the compiler from accidentally leaking in any system
1102 // libraries, so we explicitly ask gcc to not link to any libraries by
1103 // default. Note that this does not happen for windows because windows pulls
1104 // in some large number of libraries and I couldn't quite figure out which
1105 // subset we wanted.
1106 if t.options.no_default_libraries {
1107 cmd.no_default_libraries();
1110 // Take careful note of the ordering of the arguments we pass to the linker
1111 // here. Linkers will assume that things on the left depend on things to the
1112 // right. Things on the right cannot depend on things on the left. This is
1113 // all formally implemented in terms of resolving symbols (libs on the right
1114 // resolve unknown symbols of libs on the left, but not vice versa).
1116 // For this reason, we have organized the arguments we pass to the linker as
1119 // 1. The local object that LLVM just generated
1120 // 2. Local native libraries
1121 // 3. Upstream rust libraries
1122 // 4. Upstream native libraries
1124 // The rationale behind this ordering is that those items lower down in the
1125 // list can't depend on items higher up in the list. For example nothing can
1126 // depend on what we just generated (e.g. that'd be a circular dependency).
1127 // Upstream rust libraries are not allowed to depend on our local native
1128 // libraries as that would violate the structure of the DAG, in that
1129 // scenario they are required to link to them as well in a shared fashion.
1131 // Note that upstream rust libraries may contain native dependencies as
1132 // well, but they also can't depend on what we just started to add to the
1133 // link line. And finally upstream native libraries can't depend on anything
1134 // in this DAG so far because they're only dylibs and dylibs can only depend
1135 // on other dylibs (e.g. other native deps).
1136 add_local_native_libraries(cmd, sess, codegen_results);
1137 add_upstream_rust_crates(cmd, sess, codegen_results, crate_type, tmpdir);
1138 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1140 // Tell the linker what we're doing.
1141 if crate_type != config::CrateTypeExecutable {
1142 cmd.build_dylib(out_filename);
1144 if crate_type == config::CrateTypeExecutable && sess.crt_static() {
1145 cmd.build_static_executable();
1148 if sess.opts.debugging_opts.pgo_gen.is_some() {
1152 // FIXME (#2397): At some point we want to rpath our guesses as to
1153 // where extern libraries might live, based on the
1154 // addl_lib_search_paths
1155 if sess.opts.cg.rpath {
1156 let sysroot = sess.sysroot();
1157 let target_triple = sess.opts.target_triple.triple();
1158 let mut get_install_prefix_lib_path = || {
1159 let install_prefix = option_env!("CFG_PREFIX
").expect("CFG_PREFIX
");
1160 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1161 let mut path = PathBuf::from(install_prefix);
1166 let mut rpath_config = RPathConfig {
1167 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1168 out_filename: out_filename.to_path_buf(),
1169 has_rpath: sess.target.target.options.has_rpath,
1170 is_like_osx: sess.target.target.options.is_like_osx,
1171 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1172 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1174 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1177 // Finally add all the linker arguments provided on the command line along
1178 // with any #[link_args] attributes found inside the crate
1179 if let Some(ref args) = sess.opts.cg.link_args {
1182 cmd.args(&sess.opts.cg.link_arg);
1183 cmd.args(&used_link_args);
1186 // # Native library linking
1188 // User-supplied library search paths (-L on the command line). These are
1189 // the same paths used to find Rust crates, so some of them may have been
1190 // added already by the previous crate linking code. This only allows them
1191 // to be found at compile time so it is still entirely up to outside
1192 // forces to make sure that library can be found at runtime.
1194 // Also note that the native libraries linked here are only the ones located
1195 // in the current crate. Upstream crates with native library dependencies
1196 // may have their native library pulled in above.
1197 fn add_local_native_libraries(cmd: &mut Linker,
1199 codegen_results: &CodegenResults) {
1200 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1202 PathKind::Framework => { cmd.framework_path(path); }
1203 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1207 let relevant_libs = codegen_results.crate_info.used_libraries.iter().filter(|l| {
1208 relevant_lib(sess, l)
1211 let search_path = archive_search_paths(sess);
1212 for lib in relevant_libs {
1214 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1215 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1216 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1217 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1223 // # Rust Crate linking
1225 // Rust crates are not considered at all when creating an rlib output. All
1226 // dependencies will be linked when producing the final output (instead of
1227 // the intermediate rlib version)
1228 fn add_upstream_rust_crates(cmd: &mut Linker,
1230 codegen_results: &CodegenResults,
1231 crate_type: config::CrateType,
1233 // All of the heavy lifting has previously been accomplished by the
1234 // dependency_format module of the compiler. This is just crawling the
1235 // output of that module, adding crates as necessary.
1237 // Linking to a rlib involves just passing it to the linker (the linker
1238 // will slurp up the object files inside), and linking to a dynamic library
1239 // involves just passing the right -l flag.
1241 let formats = sess.dependency_formats.borrow();
1242 let data = formats.get(&crate_type).unwrap();
1244 // Invoke get_used_crates to ensure that we get a topological sorting of
1246 let deps = &codegen_results.crate_info.used_crates_dynamic;
1248 // There's a few internal crates in the standard library (aka libcore and
1249 // libstd) which actually have a circular dependence upon one another. This
1250 // currently arises through "weak lang items
" where libcore requires things
1251 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1252 // circular dependence to work correctly in all situations we'll need to be
1253 // sure to correctly apply the `--start-group` and `--end-group` options to
1254 // GNU linkers, otherwise if we don't use any other symbol from the standard
1255 // library it'll get discarded and the whole application won't link.
1257 // In this loop we're calculating the `group_end`, after which crate to
1258 // pass `--end-group` and `group_start`, before which crate to pass
1259 // `--start-group`. We currently do this by passing `--end-group` after
1260 // the first crate (when iterating backwards) that requires a lang item
1261 // defined somewhere else. Once that's set then when we've defined all the
1262 // necessary lang items we'll pass `--start-group`.
1264 // Note that this isn't amazing logic for now but it should do the trick
1265 // for the current implementation of the standard library.
1266 let mut group_end = None;
1267 let mut group_start = None;
1268 let mut end_with = FxHashSet();
1269 let info = &codegen_results.crate_info;
1270 for &(cnum, _) in deps.iter().rev() {
1271 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1272 end_with.extend(missing.iter().cloned());
1273 if end_with.len() > 0 && group_end.is_none() {
1274 group_end = Some(cnum);
1277 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1278 if end_with.len() == 0 && group_end.is_some() {
1279 group_start = Some(cnum);
1284 // If we didn't end up filling in all lang items from upstream crates then
1285 // we'll be filling it in with our crate. This probably means we're the
1286 // standard library itself, so skip this for now.
1287 if group_end.is_some() && group_start.is_none() {
1291 let mut compiler_builtins = None;
1293 for &(cnum, _) in deps.iter() {
1294 if group_start == Some(cnum) {
1298 // We may not pass all crates through to the linker. Some crates may
1299 // appear statically in an existing dylib, meaning we'll pick up all the
1300 // symbols from the dylib.
1301 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1302 match data[cnum.as_usize() - 1] {
1303 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1304 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1306 _ if codegen_results.crate_info.sanitizer_runtime == Some(cnum) => {
1307 link_sanitizer_runtime(cmd, sess, codegen_results, tmpdir, cnum);
1309 // compiler-builtins are always placed last to ensure that they're
1310 // linked correctly.
1311 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1312 assert!(compiler_builtins.is_none());
1313 compiler_builtins = Some(cnum);
1315 Linkage::NotLinked |
1316 Linkage::IncludedFromDylib => {}
1317 Linkage::Static => {
1318 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1320 Linkage::Dynamic => {
1321 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1325 if group_end == Some(cnum) {
1330 // compiler-builtins are always placed last to ensure that they're
1331 // linked correctly.
1332 // We must always link the `compiler_builtins` crate statically. Even if it
1333 // was already "included
" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1335 if let Some(cnum) = compiler_builtins {
1336 add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1339 // Converts a library file-stem into a cc -l argument
1340 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1341 if stem.starts_with("lib
") && !config.target.options.is_like_windows {
1348 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1349 // it's packed in a .rlib, it contains stuff that are not objects that will
1350 // make the linker error. So we must remove those bits from the .rlib before
1352 fn link_sanitizer_runtime(cmd: &mut Linker,
1354 codegen_results: &CodegenResults,
1357 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1358 let cratepath = &src.rlib.as_ref().unwrap().0;
1360 if sess.target.target.options.is_like_osx {
1361 // On Apple platforms, the sanitizer is always built as a dylib, and
1362 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1363 // rpath to the library as well (the rpath should be absolute, see
1364 // PR #41352 for details).
1366 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1367 let rpath = cratepath.parent().unwrap();
1368 let rpath = rpath.to_str().expect("non
-utf8 component
in path
");
1369 cmd.args(&["-Wl
,-rpath
".into(), "-Xlinker
".into(), rpath.into()]);
1372 let dst = tmpdir.join(cratepath.file_name().unwrap());
1373 let cfg = archive_config(sess, &dst, Some(cratepath));
1374 let mut archive = ArchiveBuilder::new(cfg);
1375 archive.update_symbols();
1377 for f in archive.src_files() {
1378 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1379 archive.remove_file(&f);
1386 cmd.link_whole_rlib(&dst);
1389 // Adds the static "rlib
" versions of all crates to the command line.
1390 // There's a bit of magic which happens here specifically related to LTO and
1391 // dynamic libraries. Specifically:
1393 // * For LTO, we remove upstream object files.
1394 // * For dylibs we remove metadata and bytecode from upstream rlibs
1396 // When performing LTO, almost(*) all of the bytecode from the upstream
1397 // libraries has already been included in our object file output. As a
1398 // result we need to remove the object files in the upstream libraries so
1399 // the linker doesn't try to include them twice (or whine about duplicate
1400 // symbols). We must continue to include the rest of the rlib, however, as
1401 // it may contain static native libraries which must be linked in.
1403 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1404 // their bytecode wasn't included. The object files in those libraries must
1405 // still be passed to the linker.
1407 // When making a dynamic library, linkers by default don't include any
1408 // object files in an archive if they're not necessary to resolve the link.
1409 // We basically want to convert the archive (rlib) to a dylib, though, so we
1410 // *do* want everything included in the output, regardless of whether the
1411 // linker thinks it's needed or not. As a result we must use the
1412 // --whole-archive option (or the platform equivalent). When using this
1413 // option the linker will fail if there are non-objects in the archive (such
1414 // as our own metadata and/or bytecode). All in all, for rlibs to be
1415 // entirely included in dylibs, we need to remove all non-object files.
1417 // Note, however, that if we're not doing LTO or we're not producing a dylib
1418 // (aka we're making an executable), we can just pass the rlib blindly to
1419 // the linker (fast) because it's fine if it's not actually included as
1420 // we're at the end of the dependency chain.
1421 fn add_static_crate(cmd: &mut Linker,
1423 codegen_results: &CodegenResults,
1425 crate_type: config::CrateType,
1427 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1428 let cratepath = &src.rlib.as_ref().unwrap().0;
1430 // See the comment above in `link_staticlib` and `link_rlib` for why if
1431 // there's a static library that's not relevant we skip all object
1433 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1434 let skip_native = native_libs.iter().any(|lib| {
1435 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1438 if (!is_full_lto_enabled(sess) ||
1439 ignored_for_lto(sess, &codegen_results.crate_info, cnum)) &&
1440 crate_type != config::CrateTypeDylib &&
1442 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1446 let dst = tmpdir.join(cratepath.file_name().unwrap());
1447 let name = cratepath.file_name().unwrap().to_str().unwrap();
1448 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1450 time(sess, &format!("altering {}
.rlib
", name), || {
1451 let cfg = archive_config(sess, &dst, Some(cratepath));
1452 let mut archive = ArchiveBuilder::new(cfg);
1453 archive.update_symbols();
1455 let mut any_objects = false;
1456 for f in archive.src_files() {
1457 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1458 archive.remove_file(&f);
1462 let canonical = f.replace("-", "_
");
1463 let canonical_name = name.replace("-", "_
");
1465 // Look for `.rcgu.o` at the end of the filename to conclude
1466 // that this is a Rust-related object file.
1467 fn looks_like_rust(s: &str) -> bool {
1468 let path = Path::new(s);
1469 let ext = path.extension().and_then(|s| s.to_str());
1470 if ext != Some(OutputType::Object.extension()) {
1473 let ext2 = path.file_stem()
1474 .and_then(|s| Path::new(s).extension())
1475 .and_then(|s| s.to_str());
1476 ext2 == Some(RUST_CGU_EXT)
1479 let is_rust_object =
1480 canonical.starts_with(&canonical_name) &&
1481 looks_like_rust(&f);
1483 // If we've been requested to skip all native object files
1484 // (those not generated by the rust compiler) then we can skip
1485 // this file. See above for why we may want to do this.
1486 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1488 // If we're performing LTO and this is a rust-generated object
1489 // file, then we don't need the object file as it's part of the
1490 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1491 // though, so we let that object file slide.
1492 let skip_because_lto = is_full_lto_enabled(sess) &&
1494 (sess.target.target.options.no_builtins ||
1495 !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1497 if skip_because_cfg_say_so || skip_because_lto {
1498 archive.remove_file(&f);
1509 // If we're creating a dylib, then we need to include the
1510 // whole of each object in our archive into that artifact. This is
1511 // because a `dylib` can be reused as an intermediate artifact.
1513 // Note, though, that we don't want to include the whole of a
1514 // compiler-builtins crate (e.g. compiler-rt) because it'll get
1515 // repeatedly linked anyway.
1516 if crate_type == config::CrateTypeDylib &&
1517 codegen_results.crate_info.compiler_builtins != Some(cnum) {
1518 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1520 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1525 // Same thing as above, but for dynamic crates instead of static crates.
1526 fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1527 // If we're performing LTO, then it should have been previously required
1528 // that all upstream rust dependencies were available in an rlib format.
1529 assert!(!is_full_lto_enabled(sess));
1531 // Just need to tell the linker about where the library lives and
1533 let parent = cratepath.parent();
1534 if let Some(dir) = parent {
1535 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1537 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1538 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1539 parent.unwrap_or(Path::new("")));
1543 // Link in all of our upstream crates' native dependencies. Remember that
1544 // all of these upstream native dependencies are all non-static
1545 // dependencies. We've got two cases then:
1547 // 1. The upstream crate is an rlib. In this case we *must* link in the
1548 // native dependency because the rlib is just an archive.
1550 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1551 // have the dependency present on the system somewhere. Thus, we don't
1552 // gain a whole lot from not linking in the dynamic dependency to this
1555 // The use case for this is a little subtle. In theory the native
1556 // dependencies of a crate are purely an implementation detail of the crate
1557 // itself, but the problem arises with generic and inlined functions. If a
1558 // generic function calls a native function, then the generic function must
1559 // be instantiated in the target crate, meaning that the native symbol must
1560 // also be resolved in the target crate.
1561 fn add_upstream_native_libraries(cmd: &mut Linker,
1563 codegen_results: &CodegenResults,
1564 crate_type: config::CrateType) {
1565 // Be sure to use a topological sorting of crates because there may be
1566 // interdependencies between native libraries. When passing -nodefaultlibs,
1567 // for example, almost all native libraries depend on libc, so we have to
1568 // make sure that's all the way at the right (liblibc is near the base of
1569 // the dependency chain).
1571 // This passes RequireStatic, but the actual requirement doesn't matter,
1572 // we're just getting an ordering of crate numbers, we're not worried about
1574 let formats = sess.dependency_formats.borrow();
1575 let data = formats.get(&crate_type).unwrap();
1577 let crates = &codegen_results.crate_info.used_crates_static;
1578 for &(cnum, _) in crates {
1579 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1580 if !relevant_lib(sess, &lib) {
1584 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1585 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1586 NativeLibraryKind::NativeStaticNobundle => {
1587 // Link "static-nobundle
" native libs only if the crate they originate from
1588 // is being linked statically to the current crate. If it's linked dynamically
1589 // or is an rlib already included via some other dylib crate, the symbols from
1590 // native libs will have already been included in that dylib.
1591 if data[cnum.as_usize() - 1] == Linkage::Static {
1592 cmd.link_staticlib(&lib.name.as_str())
1595 // ignore statically included native libraries here as we've
1596 // already included them when we included the rust library
1598 NativeLibraryKind::NativeStatic => {}
1604 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1606 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1611 fn is_full_lto_enabled(sess: &Session) -> bool {
1617 Lto::ThinLocal => false,