1 use rustc_data_structures
::fx
::FxHashSet
;
2 use rustc_data_structures
::temp_dir
::MaybeTempDir
;
3 use rustc_fs_util
::fix_windows_verbatim_for_gcc
;
4 use rustc_hir
::def_id
::CrateNum
;
5 use rustc_middle
::middle
::cstore
::{EncodedMetadata, LibSource, NativeLib}
;
6 use rustc_middle
::middle
::dependency_format
::Linkage
;
7 use rustc_session
::config
::{self, CFGuard, CrateType, DebugInfo}
;
8 use rustc_session
::config
::{OutputFilenames, OutputType, PrintRequest, SanitizerSet}
;
9 use rustc_session
::output
::{check_file_is_writeable, invalid_output_for_target, out_filename}
;
10 use rustc_session
::search_paths
::PathKind
;
11 use rustc_session
::utils
::NativeLibKind
;
12 /// For all the linkers we support, and information they might
13 /// need out of the shared crate context before we get rid of it.
14 use rustc_session
::{filesearch, Session}
;
15 use rustc_span
::symbol
::Symbol
;
16 use rustc_target
::spec
::crt_objects
::{CrtObjects, CrtObjectsFallback}
;
17 use rustc_target
::spec
::{LinkOutputKind, LinkerFlavor, LldFlavor}
;
18 use rustc_target
::spec
::{PanicStrategy, RelocModel, RelroLevel}
;
20 use super::archive
::ArchiveBuilder
;
21 use super::command
::Command
;
22 use super::linker
::{self, Linker}
;
23 use super::rpath
::{self, RPathConfig}
;
24 use crate::{looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME}
;
26 use cc
::windows_registry
;
27 use tempfile
::Builder
as TempFileBuilder
;
29 use std
::ffi
::OsString
;
30 use std
::path
::{Path, PathBuf}
;
31 use std
::process
::{ExitStatus, Output, Stdio}
;
32 use std
::{ascii, char, env, fmt, fs, io, mem, str}
;
34 pub fn remove(sess
: &Session
, path
: &Path
) {
35 if let Err(e
) = fs
::remove_file(path
) {
36 sess
.err(&format
!("failed to remove {}: {}", path
.display(), e
));
40 /// Performs the linkage portion of the compilation phase. This will generate all
41 /// of the requested outputs for this compilation session.
42 pub fn link_binary
<'a
, B
: ArchiveBuilder
<'a
>>(
44 codegen_results
: &CodegenResults
,
45 outputs
: &OutputFilenames
,
49 let _timer
= sess
.timer("link_binary");
50 let output_metadata
= sess
.opts
.output_types
.contains_key(&OutputType
::Metadata
);
51 for &crate_type
in sess
.crate_types().iter() {
52 // Ignore executable crates if we have -Z no-codegen, as they will error.
53 if (sess
.opts
.debugging_opts
.no_codegen
|| !sess
.opts
.output_types
.should_codegen())
55 && crate_type
== CrateType
::Executable
60 if invalid_output_for_target(sess
, crate_type
) {
62 "invalid output type `{:?}` for target os `{}`",
64 sess
.opts
.target_triple
68 sess
.time("link_binary_check_files_are_writeable", || {
69 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
70 check_file_is_writeable(obj
, sess
);
74 if outputs
.outputs
.should_codegen() {
75 let tmpdir
= TempFileBuilder
::new()
78 .unwrap_or_else(|err
| sess
.fatal(&format
!("couldn't create a temp dir: {}", err
)));
79 let path
= MaybeTempDir
::new(tmpdir
, sess
.opts
.cg
.save_temps
);
80 let out_filename
= out_filename(sess
, crate_type
, outputs
, crate_name
);
83 let _timer
= sess
.timer("link_rlib");
84 link_rlib
::<B
>(sess
, codegen_results
, RlibFlavor
::Normal
, &out_filename
, &path
)
87 CrateType
::Staticlib
=> {
88 link_staticlib
::<B
>(sess
, codegen_results
, &out_filename
, &path
);
101 if sess
.opts
.json_artifact_notifications
{
102 sess
.parse_sess
.span_diagnostic
.emit_artifact_notification(&out_filename
, "link");
107 // Remove the temporary object file and metadata if we aren't saving temps
108 sess
.time("link_binary_remove_temps", || {
109 if !sess
.opts
.cg
.save_temps
{
110 if sess
.opts
.output_types
.should_codegen()
111 && !preserve_objects_for_their_debuginfo(sess
)
113 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
117 if let Some(ref metadata_module
) = codegen_results
.metadata_module
{
118 if let Some(ref obj
) = metadata_module
.object
{
122 if let Some(ref allocator_module
) = codegen_results
.allocator_module
{
123 if let Some(ref obj
) = allocator_module
.object
{
131 // The third parameter is for env vars, used on windows to set up the
132 // path for MSVC to find its DLLs, and gcc to find its bundled
137 flavor
: LinkerFlavor
,
138 self_contained
: bool
,
140 let msvc_tool
= windows_registry
::find_tool(&sess
.opts
.target_triple
.triple(), "link.exe");
142 // If our linker looks like a batch script on Windows then to execute this
143 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
144 // emscripten where the linker is `emcc.bat` and needs to be spawned as
145 // `cmd /c emcc.bat ...`.
147 // This worked historically but is needed manually since #42436 (regression
148 // was tagged as #42791) and some more info can be found on #44443 for
149 // emscripten itself.
150 let mut cmd
= match linker
.to_str() {
151 Some(linker
) if cfg
!(windows
) && linker
.ends_with(".bat") => Command
::bat_script(linker
),
153 LinkerFlavor
::Lld(f
) => Command
::lld(linker
, f
),
155 if sess
.opts
.cg
.linker
.is_none() && sess
.target
.target
.options
.linker
.is_none() =>
157 Command
::new(msvc_tool
.as_ref().map(|t
| t
.path()).unwrap_or(linker
))
159 _
=> Command
::new(linker
),
163 // UWP apps have API restrictions enforced during Store submissions.
164 // To comply with the Windows App Certification Kit,
165 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
166 let t
= &sess
.target
.target
;
167 if (flavor
== LinkerFlavor
::Msvc
|| flavor
== LinkerFlavor
::Lld(LldFlavor
::Link
))
168 && t
.target_vendor
== "uwp"
170 if let Some(ref tool
) = msvc_tool
{
171 let original_path
= tool
.path();
172 if let Some(ref root_lib_path
) = original_path
.ancestors().nth(4) {
173 let arch
= match t
.arch
.as_str() {
174 "x86_64" => Some("x64".to_string()),
175 "x86" => Some("x86".to_string()),
176 "aarch64" => Some("arm64".to_string()),
177 "arm" => Some("arm".to_string()),
180 if let Some(ref a
) = arch
{
181 // FIXME: Move this to `fn linker_with_args`.
182 let mut arg
= OsString
::from("/LIBPATH:");
183 arg
.push(format
!("{}\\lib\\{}\\store", root_lib_path
.display(), a
.to_string()));
186 warn
!("arch is not supported");
189 warn
!("MSVC root path lib location not found");
192 warn
!("link.exe not found");
196 // The compiler's sysroot often has some bundled tools, so add it to the
197 // PATH for the child.
198 let mut new_path
= sess
.host_filesearch(PathKind
::All
).get_tools_search_paths(self_contained
);
199 let mut msvc_changed_path
= false;
200 if sess
.target
.target
.options
.is_like_msvc
{
201 if let Some(ref tool
) = msvc_tool
{
202 cmd
.args(tool
.args());
203 for &(ref k
, ref v
) in tool
.env() {
205 new_path
.extend(env
::split_paths(v
));
206 msvc_changed_path
= true;
214 if !msvc_changed_path
{
215 if let Some(path
) = env
::var_os("PATH") {
216 new_path
.extend(env
::split_paths(&path
));
219 cmd
.env("PATH", env
::join_paths(new_path
).unwrap());
224 pub fn each_linked_rlib(
226 f
: &mut dyn FnMut(CrateNum
, &Path
),
227 ) -> Result
<(), String
> {
228 let crates
= info
.used_crates_static
.iter();
230 for (ty
, list
) in info
.dependency_formats
.iter() {
232 CrateType
::Executable
233 | CrateType
::Staticlib
235 | CrateType
::ProcMacro
=> {
242 let fmts
= match fmts
{
244 None
=> return Err("could not find formats for rlibs".to_string()),
246 for &(cnum
, ref path
) in crates
{
247 match fmts
.get(cnum
.as_usize() - 1) {
248 Some(&Linkage
::NotLinked
| &Linkage
::IncludedFromDylib
) => continue,
250 None
=> return Err("could not find formats for rlibs".to_string()),
252 let name
= &info
.crate_name
[&cnum
];
253 let path
= match *path
{
254 LibSource
::Some(ref p
) => p
,
255 LibSource
::MetadataOnly
=> {
257 "could not find rlib for: `{}`, found rmeta (metadata) file",
261 LibSource
::None
=> return Err(format
!("could not find rlib for: `{}`", name
)),
268 /// We use a temp directory here to avoid races between concurrent rustc processes,
269 /// such as builds in the same directory using the same filename for metadata while
270 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
271 /// directory being searched for `extern crate` (observing an incomplete file).
272 /// The returned path is the temporary file containing the complete metadata.
273 pub fn emit_metadata(sess
: &Session
, metadata
: &EncodedMetadata
, tmpdir
: &MaybeTempDir
) -> PathBuf
{
274 let out_filename
= tmpdir
.as_ref().join(METADATA_FILENAME
);
275 let result
= fs
::write(&out_filename
, &metadata
.raw_data
);
277 if let Err(e
) = result
{
278 sess
.fatal(&format
!("failed to write {}: {}", out_filename
.display(), e
));
286 // An rlib in its current incarnation is essentially a renamed .a file. The
287 // rlib primarily contains the object file of the crate, but it also contains
288 // all of the object files from native libraries. This is done by unzipping
289 // native libraries and inserting all of the contents into this archive.
290 fn link_rlib
<'a
, B
: ArchiveBuilder
<'a
>>(
292 codegen_results
: &CodegenResults
,
295 tmpdir
: &MaybeTempDir
,
297 info
!("preparing rlib to {:?}", out_filename
);
298 let mut ab
= <B
as ArchiveBuilder
>::new(sess
, out_filename
, None
);
300 for obj
in codegen_results
.modules
.iter().filter_map(|m
| m
.object
.as_ref()) {
304 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
305 // we may not be configured to actually include a static library if we're
306 // adding it here. That's because later when we consume this rlib we'll
307 // decide whether we actually needed the static library or not.
309 // To do this "correctly" we'd need to keep track of which libraries added
310 // which object files to the archive. We don't do that here, however. The
311 // #[link(cfg(..))] feature is unstable, though, and only intended to get
312 // liblibc working. In that sense the check below just indicates that if
313 // there are any libraries we want to omit object files for at link time we
314 // just exclude all custom object files.
316 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
317 // feature then we'll need to figure out how to record what objects were
318 // loaded from the libraries found here and then encode that into the
319 // metadata of the rlib we're generating somehow.
320 for lib
in codegen_results
.crate_info
.used_libraries
.iter() {
322 NativeLibKind
::StaticBundle
=> {}
323 NativeLibKind
::StaticNoBundle
324 | NativeLibKind
::Dylib
325 | NativeLibKind
::Framework
326 | NativeLibKind
::RawDylib
327 | NativeLibKind
::Unspecified
=> continue,
329 if let Some(name
) = lib
.name
{
330 ab
.add_native_library(name
);
334 // After adding all files to the archive, we need to update the
335 // symbol table of the archive.
338 // Note that it is important that we add all of our non-object "magical
339 // files" *after* all of the object files in the archive. The reason for
340 // this is as follows:
342 // * When performing LTO, this archive will be modified to remove
343 // objects from above. The reason for this is described below.
345 // * When the system linker looks at an archive, it will attempt to
346 // determine the architecture of the archive in order to see whether its
349 // The algorithm for this detection is: iterate over the files in the
350 // archive. Skip magical SYMDEF names. Interpret the first file as an
351 // object file. Read architecture from the object file.
353 // * As one can probably see, if "metadata" and "foo.bc" were placed
354 // before all of the objects, then the architecture of this archive would
355 // not be correctly inferred once 'foo.o' is removed.
357 // Basically, all this means is that this code should not move above the
360 RlibFlavor
::Normal
=> {
361 // Instead of putting the metadata in an object file section, rlibs
362 // contain the metadata in a separate file.
363 ab
.add_file(&emit_metadata(sess
, &codegen_results
.metadata
, tmpdir
));
365 // After adding all files to the archive, we need to update the
366 // symbol table of the archive. This currently dies on macOS (see
367 // #11162), and isn't necessary there anyway
368 if !sess
.target
.target
.options
.is_like_osx
{
373 RlibFlavor
::StaticlibBase
=> {
374 let obj
= codegen_results
.allocator_module
.as_ref().and_then(|m
| m
.object
.as_ref());
375 if let Some(obj
) = obj
{
384 // Create a static archive
386 // This is essentially the same thing as an rlib, but it also involves adding
387 // all of the upstream crates' objects into the archive. This will slurp in
388 // all of the native libraries of upstream dependencies as well.
390 // Additionally, there's no way for us to link dynamic libraries, so we warn
391 // about all dynamic library dependencies that they're not linked in.
393 // There's no need to include metadata in a static archive, so ensure to not
394 // link in the metadata object file (and also don't prepare the archive with a
396 fn link_staticlib
<'a
, B
: ArchiveBuilder
<'a
>>(
398 codegen_results
: &CodegenResults
,
400 tempdir
: &MaybeTempDir
,
403 link_rlib
::<B
>(sess
, codegen_results
, RlibFlavor
::StaticlibBase
, out_filename
, tempdir
);
404 let mut all_native_libs
= vec
![];
406 let res
= each_linked_rlib(&codegen_results
.crate_info
, &mut |cnum
, path
| {
407 let name
= &codegen_results
.crate_info
.crate_name
[&cnum
];
408 let native_libs
= &codegen_results
.crate_info
.native_libraries
[&cnum
];
410 // Here when we include the rlib into our staticlib we need to make a
411 // decision whether to include the extra object files along the way.
412 // These extra object files come from statically included native
413 // libraries, but they may be cfg'd away with #[link(cfg(..))].
415 // This unstable feature, though, only needs liblibc to work. The only
416 // use case there is where musl is statically included in liblibc.rlib,
417 // so if we don't want the included version we just need to skip it. As
418 // a result the logic here is that if *any* linked library is cfg'd away
419 // we just skip all object files.
421 // Clearly this is not sufficient for a general purpose feature, and
422 // we'd want to read from the library's metadata to determine which
423 // object files come from where and selectively skip them.
424 let skip_object_files
= native_libs
426 .any(|lib
| lib
.kind
== NativeLibKind
::StaticBundle
&& !relevant_lib(sess
, lib
));
430 are_upstream_rust_objects_already_included(sess
)
431 && !ignored_for_lto(sess
, &codegen_results
.crate_info
, cnum
),
436 all_native_libs
.extend(codegen_results
.crate_info
.native_libraries
[&cnum
].iter().cloned());
438 if let Err(e
) = res
{
445 if !all_native_libs
.is_empty() {
446 if sess
.opts
.prints
.contains(&PrintRequest
::NativeStaticLibs
) {
447 print_native_static_libs(sess
, &all_native_libs
);
452 // Create a dynamic library or executable
454 // This will invoke the system linker/cc to create the resulting file. This
455 // links to all upstream files as well.
456 fn link_natively
<'a
, B
: ArchiveBuilder
<'a
>>(
458 crate_type
: CrateType
,
460 codegen_results
: &CodegenResults
,
464 info
!("preparing {:?} to {:?}", crate_type
, out_filename
);
465 let (linker_path
, flavor
) = linker_and_flavor(sess
);
466 let mut cmd
= linker_with_args
::<B
>(
477 linker
::disable_localization(&mut cmd
);
479 for &(ref k
, ref v
) in &sess
.target
.target
.options
.link_env
{
482 for k
in &sess
.target
.target
.options
.link_env_remove
{
486 if sess
.opts
.debugging_opts
.print_link_args
{
487 println
!("{:?}", &cmd
);
490 // May have not found libraries in the right formats.
491 sess
.abort_if_errors();
493 // Invoke the system linker
495 let retry_on_segfault
= env
::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
500 prog
= sess
.time("run_linker", || exec_linker(sess
, &cmd
, out_filename
, tmpdir
));
501 let output
= match prog
{
502 Ok(ref output
) => output
,
505 if output
.status
.success() {
508 let mut out
= output
.stderr
.clone();
509 out
.extend(&output
.stdout
);
510 let out
= String
::from_utf8_lossy(&out
);
512 // Check to see if the link failed with "unrecognized command line option:
513 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
514 // reperform the link step without the -no-pie option. This is safe because
515 // if the linker doesn't support -no-pie then it should not default to
516 // linking executables as pie. Different versions of gcc seem to use
517 // different quotes in the error message so don't check for them.
518 if sess
.target
.target
.options
.linker_is_gnu
519 && flavor
!= LinkerFlavor
::Ld
520 && (out
.contains("unrecognized command line option")
521 || out
.contains("unknown argument"))
522 && out
.contains("-no-pie")
523 && cmd
.get_args().iter().any(|e
| e
.to_string_lossy() == "-no-pie")
525 info
!("linker output: {:?}", out
);
526 warn
!("Linker does not support -no-pie command line option. Retrying without.");
527 for arg
in cmd
.take_args() {
528 if arg
.to_string_lossy() != "-no-pie" {
536 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
537 // Fallback from '-static-pie' to '-static' in that case.
538 if sess
.target
.target
.options
.linker_is_gnu
539 && flavor
!= LinkerFlavor
::Ld
540 && (out
.contains("unrecognized command line option")
541 || out
.contains("unknown argument"))
542 && (out
.contains("-static-pie") || out
.contains("--no-dynamic-linker"))
543 && cmd
.get_args().iter().any(|e
| e
.to_string_lossy() == "-static-pie")
545 info
!("linker output: {:?}", out
);
547 "Linker does not support -static-pie command line option. Retrying with -static instead."
549 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
550 let self_contained
= crt_objects_fallback(sess
, crate_type
);
551 let opts
= &sess
.target
.target
.options
;
552 let pre_objects
= if self_contained
{
553 &opts
.pre_link_objects_fallback
555 &opts
.pre_link_objects
557 let post_objects
= if self_contained
{
558 &opts
.post_link_objects_fallback
560 &opts
.post_link_objects
562 let get_objects
= |objects
: &CrtObjects
, kind
| {
568 .map(|obj
| get_object_file_path(sess
, obj
, self_contained
).into_os_string())
571 let pre_objects_static_pie
= get_objects(pre_objects
, LinkOutputKind
::StaticPicExe
);
572 let post_objects_static_pie
= get_objects(post_objects
, LinkOutputKind
::StaticPicExe
);
573 let mut pre_objects_static
= get_objects(pre_objects
, LinkOutputKind
::StaticNoPicExe
);
574 let mut post_objects_static
= get_objects(post_objects
, LinkOutputKind
::StaticNoPicExe
);
575 // Assume that we know insertion positions for the replacement arguments from replaced
576 // arguments, which is true for all supported targets.
577 assert
!(pre_objects_static
.is_empty() || !pre_objects_static_pie
.is_empty());
578 assert
!(post_objects_static
.is_empty() || !post_objects_static_pie
.is_empty());
579 for arg
in cmd
.take_args() {
580 if arg
.to_string_lossy() == "-static-pie" {
581 // Replace the output kind.
583 } else if pre_objects_static_pie
.contains(&arg
) {
584 // Replace the pre-link objects (replace the first and remove the rest).
585 cmd
.args(mem
::take(&mut pre_objects_static
));
586 } else if post_objects_static_pie
.contains(&arg
) {
587 // Replace the post-link objects (replace the first and remove the rest).
588 cmd
.args(mem
::take(&mut post_objects_static
));
597 // Here's a terribly awful hack that really shouldn't be present in any
598 // compiler. Here an environment variable is supported to automatically
599 // retry the linker invocation if the linker looks like it segfaulted.
601 // Gee that seems odd, normally segfaults are things we want to know
602 // about! Unfortunately though in rust-lang/rust#38878 we're
603 // experiencing the linker segfaulting on Travis quite a bit which is
604 // causing quite a bit of pain to land PRs when they spuriously fail
605 // due to a segfault.
607 // The issue #38878 has some more debugging information on it as well,
608 // but this unfortunately looks like it's just a race condition in
609 // macOS's linker with some thread pool working in the background. It
610 // seems that no one currently knows a fix for this so in the meantime
611 // we're left with this...
612 if !retry_on_segfault
|| i
> 3 {
615 let msg_segv
= "clang: error: unable to execute command: Segmentation fault: 11";
616 let msg_bus
= "clang: error: unable to execute command: Bus error: 10";
617 if out
.contains(msg_segv
) || out
.contains(msg_bus
) {
619 "looks like the linker segfaulted when we tried to call it, \
620 automatically retrying again. cmd = {:?}, out = {}.",
626 if is_illegal_instruction(&output
.status
) {
628 "looks like the linker hit an illegal instruction when we \
629 tried to call it, automatically retrying again. cmd = {:?}, ]\
630 out = {}, status = {}.",
631 cmd
, out
, output
.status
,
637 fn is_illegal_instruction(status
: &ExitStatus
) -> bool
{
638 use std
::os
::unix
::prelude
::*;
639 status
.signal() == Some(libc
::SIGILL
)
643 fn is_illegal_instruction(_status
: &ExitStatus
) -> bool
{
650 fn escape_string(s
: &[u8]) -> String
{
651 str::from_utf8(s
).map(|s
| s
.to_owned()).unwrap_or_else(|_
| {
652 let mut x
= "Non-UTF-8 output: ".to_string();
653 x
.extend(s
.iter().flat_map(|&b
| ascii
::escape_default(b
)).map(char::from
));
657 if !prog
.status
.success() {
658 let mut output
= prog
.stderr
.clone();
659 output
.extend_from_slice(&prog
.stdout
);
660 sess
.struct_err(&format
!(
661 "linking with `{}` failed: {}",
662 linker_path
.display(),
665 .note(&format
!("{:?}", &cmd
))
666 .note(&escape_string(&output
))
669 // If MSVC's `link.exe` was expected but the return code
670 // is not a Microsoft LNK error then suggest a way to fix or
671 // install the Visual Studio build tools.
672 if let Some(code
) = prog
.status
.code() {
673 if sess
.target
.target
.options
.is_like_msvc
674 && flavor
== LinkerFlavor
::Msvc
675 // Respect the command line override
676 && sess
.opts
.cg
.linker
.is_none()
677 // Match exactly "link.exe"
678 && linker_path
.to_str() == Some("link.exe")
679 // All Microsoft `link.exe` linking error codes are
680 // four digit numbers in the range 1000 to 9999 inclusive
681 && (code
< 1000 || code
> 9999)
683 let is_vs_installed
= windows_registry
::find_vs_version().is_ok();
684 let has_linker
= windows_registry
::find_tool(
685 &sess
.opts
.target_triple
.triple(),
690 sess
.note_without_error("`link.exe` returned an unexpected error");
691 if is_vs_installed
&& has_linker
{
692 // the linker is broken
693 sess
.note_without_error(
694 "the Visual Studio build tools may need to be repaired \
695 using the Visual Studio installer",
697 sess
.note_without_error(
698 "or a necessary component may be missing from the \
699 \"C++ build tools\" workload",
701 } else if is_vs_installed
{
702 // the linker is not installed
703 sess
.note_without_error(
704 "in the Visual Studio installer, ensure the \
705 \"C++ build tools\" workload is selected",
708 // visual studio is not installed
709 sess
.note_without_error(
710 "you may need to install Visual Studio build tools with the \
711 \"C++ build tools\" workload",
717 sess
.abort_if_errors();
719 info
!("linker stderr:\n{}", escape_string(&prog
.stderr
));
720 info
!("linker stdout:\n{}", escape_string(&prog
.stdout
));
723 let linker_not_found
= e
.kind() == io
::ErrorKind
::NotFound
;
725 let mut linker_error
= {
726 if linker_not_found
{
727 sess
.struct_err(&format
!("linker `{}` not found", linker_path
.display()))
729 sess
.struct_err(&format
!(
730 "could not exec the linker `{}`",
731 linker_path
.display()
736 linker_error
.note(&e
.to_string());
738 if !linker_not_found
{
739 linker_error
.note(&format
!("{:?}", &cmd
));
744 if sess
.target
.target
.options
.is_like_msvc
&& linker_not_found
{
745 sess
.note_without_error(
746 "the msvc targets depend on the msvc linker \
747 but `link.exe` was not found",
749 sess
.note_without_error(
750 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
751 was installed with the Visual C++ option",
754 sess
.abort_if_errors();
758 // On macOS, debuggers need this utility to get run to do some munging of
759 // the symbols. Note, though, that if the object files are being preserved
760 // for their debug information there's no need for us to run dsymutil.
761 if sess
.target
.target
.options
.is_like_osx
762 && sess
.opts
.debuginfo
!= DebugInfo
::None
763 && !preserve_objects_for_their_debuginfo(sess
)
765 if let Err(e
) = Command
::new("dsymutil").arg(out_filename
).output() {
766 sess
.fatal(&format
!("failed to run dsymutil: {}", e
))
771 fn link_sanitizers(sess
: &Session
, crate_type
: CrateType
, linker
: &mut dyn Linker
) {
772 // On macOS the runtimes are distributed as dylibs which should be linked to
773 // both executables and dynamic shared objects. Everywhere else the runtimes
774 // are currently distributed as static liraries which should be linked to
776 let needs_runtime
= match crate_type
{
777 CrateType
::Executable
=> true,
778 CrateType
::Dylib
| CrateType
::Cdylib
| CrateType
::ProcMacro
=> {
779 sess
.target
.target
.options
.is_like_osx
781 CrateType
::Rlib
| CrateType
::Staticlib
=> false,
788 let sanitizer
= sess
.opts
.debugging_opts
.sanitizer
;
789 if sanitizer
.contains(SanitizerSet
::ADDRESS
) {
790 link_sanitizer_runtime(sess
, linker
, "asan");
792 if sanitizer
.contains(SanitizerSet
::LEAK
) {
793 link_sanitizer_runtime(sess
, linker
, "lsan");
795 if sanitizer
.contains(SanitizerSet
::MEMORY
) {
796 link_sanitizer_runtime(sess
, linker
, "msan");
798 if sanitizer
.contains(SanitizerSet
::THREAD
) {
799 link_sanitizer_runtime(sess
, linker
, "tsan");
803 fn link_sanitizer_runtime(sess
: &Session
, linker
: &mut dyn Linker
, name
: &str) {
804 let default_sysroot
= filesearch
::get_or_default_sysroot();
806 filesearch
::make_target_lib_path(&default_sysroot
, sess
.opts
.target_triple
.triple());
807 let channel
= option_env
!("CFG_RELEASE_CHANNEL")
808 .map(|channel
| format
!("-{}", channel
))
809 .unwrap_or_default();
811 match sess
.opts
.target_triple
.triple() {
812 "x86_64-apple-darwin" => {
813 // On Apple platforms, the sanitizer is always built as a dylib, and
814 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
815 // rpath to the library as well (the rpath should be absolute, see
816 // PR #41352 for details).
817 let libname
= format
!("rustc{}_rt.{}", channel
, name
);
818 let rpath
= default_tlib
.to_str().expect("non-utf8 component in path");
819 linker
.args(&["-Wl,-rpath", "-Xlinker", rpath
]);
820 linker
.link_dylib(Symbol
::intern(&libname
));
823 | "aarch64-unknown-linux-gnu"
825 | "x86_64-unknown-freebsd"
826 | "x86_64-unknown-linux-gnu" => {
827 let filename
= format
!("librustc{}_rt.{}.a", channel
, name
);
828 let path
= default_tlib
.join(&filename
);
829 linker
.link_whole_rlib(&path
);
835 /// Returns a boolean indicating whether the specified crate should be ignored
838 /// Crates ignored during LTO are not lumped together in the "massive object
839 /// file" that we create and are linked in their normal rlib states. See
840 /// comments below for what crates do not participate in LTO.
842 /// It's unusual for a crate to not participate in LTO. Typically only
843 /// compiler-specific and unstable crates have a reason to not participate in
845 pub fn ignored_for_lto(sess
: &Session
, info
: &CrateInfo
, cnum
: CrateNum
) -> bool
{
846 // If our target enables builtin function lowering in LLVM then the
847 // crates providing these functions don't participate in LTO (e.g.
848 // no_builtins or compiler builtins crates).
849 !sess
.target
.target
.options
.no_builtins
850 && (info
.compiler_builtins
== Some(cnum
) || info
.is_no_builtins
.contains(&cnum
))
853 fn linker_and_flavor(sess
: &Session
) -> (PathBuf
, LinkerFlavor
) {
856 linker
: Option
<PathBuf
>,
857 flavor
: Option
<LinkerFlavor
>,
858 ) -> Option
<(PathBuf
, LinkerFlavor
)> {
859 match (linker
, flavor
) {
860 (Some(linker
), Some(flavor
)) => Some((linker
, flavor
)),
861 // only the linker flavor is known; use the default linker for the selected flavor
862 (None
, Some(flavor
)) => Some((
863 PathBuf
::from(match flavor
{
864 LinkerFlavor
::Em
=> {
871 LinkerFlavor
::Gcc
=> {
872 if cfg
!(any(target_os
= "solaris", target_os
= "illumos")) {
873 // On historical Solaris systems, "cc" may have
874 // been Sun Studio, which is not flag-compatible
875 // with "gcc". This history casts a long shadow,
876 // and many modern illumos distributions today
877 // ship GCC as "gcc" without also making it
878 // available as "cc".
884 LinkerFlavor
::Ld
=> "ld",
885 LinkerFlavor
::Msvc
=> "link.exe",
886 LinkerFlavor
::Lld(_
) => "lld",
887 LinkerFlavor
::PtxLinker
=> "rust-ptx-linker",
891 (Some(linker
), None
) => {
892 let stem
= linker
.file_stem().and_then(|stem
| stem
.to_str()).unwrap_or_else(|| {
893 sess
.fatal("couldn't extract file stem from specified linker")
896 let flavor
= if stem
== "emcc" {
898 } else if stem
== "gcc"
899 || stem
.ends_with("-gcc")
901 || stem
.ends_with("-clang")
904 } else if stem
== "ld" || stem
== "ld.lld" || stem
.ends_with("-ld") {
906 } else if stem
== "link" || stem
== "lld-link" {
908 } else if stem
== "lld" || stem
== "rust-lld" {
909 LinkerFlavor
::Lld(sess
.target
.target
.options
.lld_flavor
)
911 // fall back to the value in the target spec
912 sess
.target
.target
.linker_flavor
915 Some((linker
, flavor
))
917 (None
, None
) => None
,
921 // linker and linker flavor specified via command line have precedence over what the target
922 // specification specifies
923 if let Some(ret
) = infer_from(sess
, sess
.opts
.cg
.linker
.clone(), sess
.opts
.cg
.linker_flavor
) {
927 if let Some(ret
) = infer_from(
929 sess
.target
.target
.options
.linker
.clone().map(PathBuf
::from
),
930 Some(sess
.target
.target
.linker_flavor
),
935 bug
!("Not enough information provided to determine how to invoke the linker");
938 /// Returns a boolean indicating whether we should preserve the object files on
939 /// the filesystem for their debug information. This is often useful with
940 /// split-dwarf like schemes.
941 fn preserve_objects_for_their_debuginfo(sess
: &Session
) -> bool
{
942 // If the objects don't have debuginfo there's nothing to preserve.
943 if sess
.opts
.debuginfo
== config
::DebugInfo
::None
{
947 // If we're only producing artifacts that are archives, no need to preserve
948 // the objects as they're losslessly contained inside the archives.
950 sess
.crate_types().iter().any(|&x
| x
!= CrateType
::Rlib
&& x
!= CrateType
::Staticlib
);
955 // If we're on OSX then the equivalent of split dwarf is turned on by
956 // default. The final executable won't actually have any debug information
957 // except it'll have pointers to elsewhere. Historically we've always run
958 // `dsymutil` to "link all the dwarf together" but this is actually sort of
959 // a bummer for incremental compilation! (the whole point of split dwarf is
960 // that you don't do this sort of dwarf link).
962 // Basically as a result this just means that if we're on OSX and we're
963 // *not* running dsymutil then the object files are the only source of truth
964 // for debug information, so we must preserve them.
965 if sess
.target
.target
.options
.is_like_osx
{
966 return !sess
.opts
.debugging_opts
.run_dsymutil
;
972 pub fn archive_search_paths(sess
: &Session
) -> Vec
<PathBuf
> {
973 sess
.target_filesearch(PathKind
::Native
).search_path_dirs()
981 fn print_native_static_libs(sess
: &Session
, all_native_libs
: &[NativeLib
]) {
982 let lib_args
: Vec
<_
> = all_native_libs
984 .filter(|l
| relevant_lib(sess
, l
))
986 let name
= lib
.name?
;
988 NativeLibKind
::StaticNoBundle
989 | NativeLibKind
::Dylib
990 | NativeLibKind
::Unspecified
=> {
991 if sess
.target
.target
.options
.is_like_msvc
{
992 Some(format
!("{}.lib", name
))
994 Some(format
!("-l{}", name
))
997 NativeLibKind
::Framework
=> {
998 // ld-only syntax, since there are no frameworks in MSVC
999 Some(format
!("-framework {}", name
))
1001 // These are included, no need to print them
1002 NativeLibKind
::StaticBundle
| NativeLibKind
::RawDylib
=> None
,
1006 if !lib_args
.is_empty() {
1007 sess
.note_without_error(
1008 "Link against the following native artifacts when linking \
1009 against this static library. The order and any duplication \
1010 can be significant on some platforms.",
1012 // Prefix for greppability
1013 sess
.note_without_error(&format
!("native-static-libs: {}", &lib_args
.join(" ")));
1017 // Because windows-gnu target is meant to be self-contained for pure Rust code it bundles
1018 // own mingw-w64 libraries. These libraries are usually not compatible with mingw-w64
1019 // installed in the system. This breaks many cases where Rust is mixed with other languages
1020 // (e.g. *-sys crates).
1021 // We prefer system mingw-w64 libraries if they are available to avoid this issue.
1022 fn get_crt_libs_path(sess
: &Session
) -> Option
<PathBuf
> {
1023 fn find_exe_in_path
<P
>(exe_name
: P
) -> Option
<PathBuf
>
1027 for dir
in env
::split_paths(&env
::var_os("PATH")?
) {
1028 let full_path
= dir
.join(&exe_name
);
1029 if full_path
.is_file() {
1030 return Some(fix_windows_verbatim_for_gcc(&full_path
));
1036 fn probe(sess
: &Session
) -> Option
<PathBuf
> {
1037 if let (linker
, LinkerFlavor
::Gcc
) = linker_and_flavor(&sess
) {
1038 let linker_path
= if cfg
!(windows
) && linker
.extension().is_none() {
1039 linker
.with_extension("exe")
1043 if let Some(linker_path
) = find_exe_in_path(linker_path
) {
1044 let mingw_arch
= match &sess
.target
.target
.arch
{
1045 x
if x
== "x86" => "i686",
1048 let mingw_bits
= &sess
.target
.target
.target_pointer_width
;
1049 let mingw_dir
= format
!("{}-w64-mingw32", mingw_arch
);
1050 // Here we have path/bin/gcc but we need path/
1051 let mut path
= linker_path
;
1054 // Loosely based on Clang MinGW driver
1055 let probe_paths
= vec
![
1056 path
.join(&mingw_dir
).join("lib"), // Typical path
1057 path
.join(&mingw_dir
).join("sys-root/mingw/lib"), // Rare path
1059 "lib/mingw/tools/install/mingw{}/{}/lib",
1060 &mingw_bits
, &mingw_dir
1061 )), // Chocolatey is creative
1063 for probe_path
in probe_paths
{
1064 if probe_path
.join("crt2.o").exists() {
1065 return Some(probe_path
);
1073 let mut system_library_path
= sess
.system_library_path
.borrow_mut();
1074 match &*system_library_path
{
1075 Some(Some(compiler_libs_path
)) => Some(compiler_libs_path
.clone()),
1078 let path
= probe(sess
);
1079 *system_library_path
= Some(path
.clone());
1085 fn get_object_file_path(sess
: &Session
, name
: &str, self_contained
: bool
) -> PathBuf
{
1086 // prefer system {,dll}crt2.o libs, see get_crt_libs_path comment for more details
1087 if sess
.opts
.debugging_opts
.link_self_contained
.is_none()
1088 && sess
.target
.target
.llvm_target
.contains("windows-gnu")
1090 if let Some(compiler_libs_path
) = get_crt_libs_path(sess
) {
1091 let file_path
= compiler_libs_path
.join(name
);
1092 if file_path
.exists() {
1097 let fs
= sess
.target_filesearch(PathKind
::Native
);
1098 let file_path
= fs
.get_lib_path().join(name
);
1099 if file_path
.exists() {
1102 // Special directory with objects used only in self-contained linkage mode
1104 let file_path
= fs
.get_self_contained_lib_path().join(name
);
1105 if file_path
.exists() {
1109 for search_path
in fs
.search_paths() {
1110 let file_path
= search_path
.dir
.join(name
);
1111 if file_path
.exists() {
1121 out_filename
: &Path
,
1123 ) -> io
::Result
<Output
> {
1124 // When attempting to spawn the linker we run a risk of blowing out the
1125 // size limits for spawning a new process with respect to the arguments
1126 // we pass on the command line.
1128 // Here we attempt to handle errors from the OS saying "your list of
1129 // arguments is too big" by reinvoking the linker again with an `@`-file
1130 // that contains all the arguments. The theory is that this is then
1131 // accepted on all linkers and the linker will read all its options out of
1132 // there instead of looking at the command line.
1133 if !cmd
.very_likely_to_exceed_some_spawn_limit() {
1134 match cmd
.command().stdout(Stdio
::piped()).stderr(Stdio
::piped()).spawn() {
1136 let output
= child
.wait_with_output();
1137 flush_linked_file(&output
, out_filename
)?
;
1140 Err(ref e
) if command_line_too_big(e
) => {
1141 info
!("command line to linker was too big: {}", e
);
1143 Err(e
) => return Err(e
),
1147 info
!("falling back to passing arguments to linker via an @-file");
1148 let mut cmd2
= cmd
.clone();
1149 let mut args
= String
::new();
1150 for arg
in cmd2
.take_args() {
1153 arg
: arg
.to_str().unwrap(),
1154 is_like_msvc
: sess
.target
.target
.options
.is_like_msvc
,
1158 args
.push_str("\n");
1160 let file
= tmpdir
.join("linker-arguments");
1161 let bytes
= if sess
.target
.target
.options
.is_like_msvc
{
1162 let mut out
= Vec
::with_capacity((1 + args
.len()) * 2);
1163 // start the stream with a UTF-16 BOM
1164 for c
in std
::iter
::once(0xFEFF).chain(args
.encode_utf16()) {
1165 // encode in little endian
1167 out
.push((c
>> 8) as u8);
1173 fs
::write(&file
, &bytes
)?
;
1174 cmd2
.arg(format
!("@{}", file
.display()));
1175 info
!("invoking linker {:?}", cmd2
);
1176 let output
= cmd2
.output();
1177 flush_linked_file(&output
, out_filename
)?
;
1181 fn flush_linked_file(_
: &io
::Result
<Output
>, _
: &Path
) -> io
::Result
<()> {
1186 fn flush_linked_file(
1187 command_output
: &io
::Result
<Output
>,
1188 out_filename
: &Path
,
1189 ) -> io
::Result
<()> {
1190 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1191 // even long after process exit, causing nasty, non-reproducible output bugs.
1193 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1195 // А full writeup of the original Chrome bug can be found at
1196 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1198 if let &Ok(ref out
) = command_output
{
1199 if out
.status
.success() {
1200 if let Ok(of
) = fs
::OpenOptions
::new().write(true).open(out_filename
) {
1210 fn command_line_too_big(err
: &io
::Error
) -> bool
{
1211 err
.raw_os_error() == Some(::libc
::E2BIG
)
1215 fn command_line_too_big(err
: &io
::Error
) -> bool
{
1216 const ERROR_FILENAME_EXCED_RANGE
: i32 = 206;
1217 err
.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE
)
1225 impl<'a
> fmt
::Display
for Escape
<'a
> {
1226 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1227 if self.is_like_msvc
{
1228 // This is "documented" at
1229 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1231 // Unfortunately there's not a great specification of the
1232 // syntax I could find online (at least) but some local
1233 // testing showed that this seemed sufficient-ish to catch
1234 // at least a few edge cases.
1236 for c
in self.arg
.chars() {
1238 '
"' => write!(f, "\\{}
", c)?,
1239 c => write!(f, "{}
", c)?,
1244 // This is documented at https://linux.die.net/man/1/ld, namely:
1246 // > Options in file are separated by whitespace. A whitespace
1247 // > character may be included in an option by surrounding the
1248 // > entire option in either single or double quotes. Any
1249 // > character (including a backslash) may be included by
1250 // > prefixing the character to be included with a backslash.
1252 // We put an argument on each line, so all we need to do is
1253 // ensure the line is interpreted as one whole argument.
1254 for c in self.arg.chars() {
1256 '\\' | ' ' => write!(f, "\\{}
", c)?,
1257 c => write!(f, "{}
", c)?,
1266 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1267 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1268 (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1269 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1270 (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1271 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1272 (_, true, _) => LinkOutputKind::StaticDylib,
1273 (_, false, _) => LinkOutputKind::DynamicDylib,
1276 // Adjust the output kind to target capabilities.
1277 let opts = &sess.target.target.options;
1278 let pic_exe_supported = opts.position_independent_executables;
1279 let static_pic_exe_supported = opts.static_position_independent_executables;
1280 let static_dylib_supported = opts.crt_static_allows_dylibs;
1282 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1283 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1284 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1289 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1290 /// We only provide such support for a very limited number of targets.
1291 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1292 if let Some(self_contained) = sess.opts.debugging_opts.link_self_contained {
1293 return self_contained;
1296 match sess.target.target.options.crt_objects_fallback {
1297 // FIXME: Find a better heuristic for "native musl toolchain is available
",
1298 // based on host and linker path, for example.
1299 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1300 Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1301 // FIXME: Find some heuristic for "native mingw toolchain is available
",
1302 // likely based on `get_crt_libs_path` (https://github.com/rust-lang/rust/pull/67429).
1303 Some(CrtObjectsFallback::Mingw) => {
1304 sess.host == sess.target.target && sess.target.target.target_vendor != "uwp
"
1306 // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1307 Some(CrtObjectsFallback::Wasm) => true,
1312 /// Add pre-link object files defined by the target spec.
1313 fn add_pre_link_objects(
1314 cmd: &mut dyn Linker,
1316 link_output_kind: LinkOutputKind,
1317 self_contained: bool,
1319 let opts = &sess.target.target.options;
1321 if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1322 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1323 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1327 /// Add post-link object files defined by the target spec.
1328 fn add_post_link_objects(
1329 cmd: &mut dyn Linker,
1331 link_output_kind: LinkOutputKind,
1332 self_contained: bool,
1334 let opts = &sess.target.target.options;
1336 if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1337 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1338 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1342 /// Add arbitrary "pre
-link
" args defined by the target spec or from command line.
1343 /// FIXME: Determine where exactly these args need to be inserted.
1344 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1345 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
1348 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1351 /// Add a link script embedded in the target, if applicable.
1352 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1353 match (crate_type, &sess.target.target.options.link_script) {
1354 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1355 if !sess.target.target.options.linker_is_gnu {
1356 sess.fatal("can only
use link script when linking with GNU
-like linker
");
1359 let file_name = ["rustc
", &sess.target.target.llvm_target, "linkfile
.ld
"].join("-");
1361 let path = tmpdir.join(file_name);
1362 if let Err(e) = fs::write(&path, script) {
1363 sess.fatal(&format!("failed to write link script to {}
: {}
", path.display(), e));
1366 cmd.arg("--script
");
1373 /// Add arbitrary "user defined
" args defined from command line and by `#[link_args]` attributes.
1374 /// FIXME: Determine where exactly these args need to be inserted.
1375 fn add_user_defined_link_args(
1376 cmd: &mut dyn Linker,
1378 codegen_results: &CodegenResults,
1380 cmd.args(&sess.opts.cg.link_args);
1381 cmd.args(&*codegen_results.crate_info.link_args);
1384 /// Add arbitrary "late link
" args defined by the target spec.
1385 /// FIXME: Determine where exactly these args need to be inserted.
1386 fn add_late_link_args(
1387 cmd: &mut dyn Linker,
1389 flavor: LinkerFlavor,
1390 crate_type: CrateType,
1391 codegen_results: &CodegenResults,
1393 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
1396 let any_dynamic_crate = crate_type == CrateType::Dylib
1397 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1398 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1400 if any_dynamic_crate {
1401 if let Some(args) = sess.target.target.options.late_link_args_dynamic.get(&flavor) {
1405 if let Some(args) = sess.target.target.options.late_link_args_static.get(&flavor) {
1411 /// Add arbitrary "post
-link
" args defined by the target spec.
1412 /// FIXME: Determine where exactly these args need to be inserted.
1413 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1414 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
1419 /// Add object files containing code from the current crate.
1420 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1421 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1422 cmd.add_object(obj);
1426 /// Add object files for allocator code linked once for the whole crate tree.
1427 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1428 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1429 cmd.add_object(obj);
1433 /// Add object files containing metadata for the current crate.
1434 fn add_local_crate_metadata_objects(
1435 cmd: &mut dyn Linker,
1436 crate_type: CrateType,
1437 codegen_results: &CodegenResults,
1439 // When linking a dynamic library, we put the metadata into a section of the
1440 // executable. This metadata is in a separate object file from the main
1441 // object file, so we link that in here.
1442 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1443 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1445 cmd.add_object(obj);
1450 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1451 /// all its dependency crates.
1452 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1453 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1454 cmd: &mut dyn Linker,
1456 crate_type: CrateType,
1457 codegen_results: &CodegenResults,
1460 // Take careful note of the ordering of the arguments we pass to the linker
1461 // here. Linkers will assume that things on the left depend on things to the
1462 // right. Things on the right cannot depend on things on the left. This is
1463 // all formally implemented in terms of resolving symbols (libs on the right
1464 // resolve unknown symbols of libs on the left, but not vice versa).
1466 // For this reason, we have organized the arguments we pass to the linker as
1469 // 1. The local object that LLVM just generated
1470 // 2. Local native libraries
1471 // 3. Upstream rust libraries
1472 // 4. Upstream native libraries
1474 // The rationale behind this ordering is that those items lower down in the
1475 // list can't depend on items higher up in the list. For example nothing can
1476 // depend on what we just generated (e.g., that'd be a circular dependency).
1477 // Upstream rust libraries are not allowed to depend on our local native
1478 // libraries as that would violate the structure of the DAG, in that
1479 // scenario they are required to link to them as well in a shared fashion.
1481 // Note that upstream rust libraries may contain native dependencies as
1482 // well, but they also can't depend on what we just started to add to the
1483 // link line. And finally upstream native libraries can't depend on anything
1484 // in this DAG so far because they're only dylibs and dylibs can only depend
1485 // on other dylibs (e.g., other native deps).
1487 // If -Zlink-native-libraries=false is set, then the assumption is that an
1488 // external build system already has the native dependencies defined, and it
1489 // will provide them to the linker itself.
1490 if sess.opts.debugging_opts.link_native_libraries {
1491 add_local_native_libraries(cmd, sess, codegen_results);
1493 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1494 if sess.opts.debugging_opts.link_native_libraries {
1495 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1499 /// Add sysroot and other globally set directories to the directory search list.
1500 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1501 // Prefer system mingw-w64 libs, see get_crt_libs_path comment for more details.
1502 if sess.opts.debugging_opts.link_self_contained.is_none()
1504 && sess.target.target.llvm_target.contains("windows
-gnu
")
1506 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1507 cmd.include_path(&compiler_libs_path);
1511 // The default library location, we need this to find the runtime.
1512 // The location of crates will be determined as needed.
1513 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1514 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1516 // Special directory with libraries used only in self-contained linkage mode
1518 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1519 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1523 /// Add options making relocation sections in the produced ELF files read-only
1524 /// and suppressing lazy binding.
1525 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1526 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.target.options.relro_level) {
1527 RelroLevel::Full => cmd.full_relro(),
1528 RelroLevel::Partial => cmd.partial_relro(),
1529 RelroLevel::Off => cmd.no_relro(),
1530 RelroLevel::None => {}
1534 /// Add library search paths used at runtime by dynamic linkers.
1536 cmd: &mut dyn Linker,
1538 codegen_results: &CodegenResults,
1539 out_filename: &Path,
1541 // FIXME (#2397): At some point we want to rpath our guesses as to
1542 // where extern libraries might live, based on the
1543 // addl_lib_search_paths
1544 if sess.opts.cg.rpath {
1545 let target_triple = sess.opts.target_triple.triple();
1546 let mut get_install_prefix_lib_path = || {
1547 let install_prefix = option_env!("CFG_PREFIX
").expect("CFG_PREFIX
");
1548 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1549 let mut path = PathBuf::from(install_prefix);
1554 let mut rpath_config = RPathConfig {
1555 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1556 out_filename: out_filename.to_path_buf(),
1557 has_rpath: sess.target.target.options.has_rpath,
1558 is_like_osx: sess.target.target.options.is_like_osx,
1559 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1560 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1562 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1566 /// Produce the linker command line containing linker path and arguments.
1567 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1568 /// by the user without creating a custom target specification.
1569 /// `OBJECT-FILES` specify whether the arguments can add object files.
1570 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1571 /// or by the target spec can be inserted here.
1572 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1573 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1575 flavor: LinkerFlavor,
1577 crate_type: CrateType,
1579 out_filename: &Path,
1580 codegen_results: &CodegenResults,
1583 let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1584 let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1585 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1586 // to the linker args construction.
1587 assert!(base_cmd.get_args().is_empty() || sess.target.target.target_vendor == "uwp
");
1588 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1589 let link_output_kind = link_output_kind(sess, crate_type);
1591 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1592 add_pre_link_args(cmd, sess, flavor);
1595 add_link_script(cmd, sess, tmpdir, crate_type);
1597 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1598 if sess.target.target.options.is_like_fuchsia && crate_type == CrateType::Executable {
1599 let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1604 cmd.arg(format!("--dynamic
-linker
={}ld
.so
.1", prefix));
1607 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1608 if sess.target.target.options.eh_frame_header {
1609 cmd.add_eh_frame_header();
1612 // NO-OPT-OUT, OBJECT-FILES-NO
1613 if crt_objects_fallback {
1614 cmd.no_crt_objects();
1617 // NO-OPT-OUT, OBJECT-FILES-YES
1618 add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1620 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1621 if sess.target.target.options.is_like_emscripten {
1623 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1624 "DISABLE_EXCEPTION_CATCHING
=1"
1626 "DISABLE_EXCEPTION_CATCHING
=0"
1630 // OBJECT-FILES-YES, AUDIT-ORDER
1631 link_sanitizers(sess, crate_type, cmd);
1633 // OBJECT-FILES-NO, AUDIT-ORDER
1634 // Linker plugins should be specified early in the list of arguments
1635 // FIXME: How "early
" exactly?
1636 cmd.linker_plugin_lto();
1638 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1639 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1640 add_library_search_dirs(cmd, sess, crt_objects_fallback);
1643 add_local_crate_regular_objects(cmd, codegen_results);
1645 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1646 cmd.output_filename(out_filename);
1648 // OBJECT-FILES-NO, AUDIT-ORDER
1649 if crate_type == CrateType::Executable && sess.target.target.options.is_like_windows {
1650 if let Some(ref s) = codegen_results.windows_subsystem {
1655 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1656 // If we're building something like a dynamic library then some platforms
1657 // need to make sure that all symbols are exported correctly from the
1659 cmd.export_symbols(tmpdir, crate_type);
1662 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1665 add_local_crate_allocator_objects(cmd, codegen_results);
1667 // OBJECT-FILES-NO, AUDIT-ORDER
1668 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1669 // Try to strip as much out of the generated object by removing unused
1670 // sections if possible. See more comments in linker.rs
1671 if sess.opts.cg.link_dead_code != Some(true) {
1672 let keep_metadata = crate_type == CrateType::Dylib;
1673 cmd.gc_sections(keep_metadata);
1676 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1677 cmd.set_output_kind(link_output_kind, out_filename);
1679 // OBJECT-FILES-NO, AUDIT-ORDER
1680 add_relro_args(cmd, sess);
1682 // OBJECT-FILES-NO, AUDIT-ORDER
1683 // Pass optimization flags down to the linker.
1686 // OBJECT-FILES-NO, AUDIT-ORDER
1687 // Pass debuginfo and strip flags down to the linker.
1688 cmd.debuginfo(sess.opts.debugging_opts.strip);
1690 // OBJECT-FILES-NO, AUDIT-ORDER
1691 // We want to prevent the compiler from accidentally leaking in any system libraries,
1692 // so by default we tell linkers not to link to any default libraries.
1693 if !sess.opts.cg.default_linker_libraries && sess.target.target.options.no_default_libraries {
1694 cmd.no_default_libraries();
1698 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1706 // OBJECT-FILES-NO, AUDIT-ORDER
1707 if sess.opts.cg.profile_generate.enabled() || sess.opts.debugging_opts.instrument_coverage {
1711 // OBJECT-FILES-NO, AUDIT-ORDER
1712 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1713 cmd.control_flow_guard();
1716 // OBJECT-FILES-NO, AUDIT-ORDER
1717 add_rpath_args(cmd, sess, codegen_results, out_filename);
1719 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1720 add_user_defined_link_args(cmd, sess, codegen_results);
1722 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1725 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1726 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1728 // NO-OPT-OUT, OBJECT-FILES-YES
1729 add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1731 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1732 add_post_link_args(cmd, sess, flavor);
1737 // # Native library linking
1739 // User-supplied library search paths (-L on the command line). These are
1740 // the same paths used to find Rust crates, so some of them may have been
1741 // added already by the previous crate linking code. This only allows them
1742 // to be found at compile time so it is still entirely up to outside
1743 // forces to make sure that library can be found at runtime.
1745 // Also note that the native libraries linked here are only the ones located
1746 // in the current crate. Upstream crates with native library dependencies
1747 // may have their native library pulled in above.
1748 fn add_local_native_libraries(
1749 cmd: &mut dyn Linker,
1751 codegen_results: &CodegenResults,
1753 let filesearch = sess.target_filesearch(PathKind::All);
1754 for search_path in filesearch.search_paths() {
1755 match search_path.kind {
1756 PathKind::Framework => {
1757 cmd.framework_path(&search_path.dir);
1760 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1766 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1768 let search_path = archive_search_paths(sess);
1769 for lib in relevant_libs {
1770 let name = match lib.name {
1775 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1776 NativeLibKind::Framework => cmd.link_framework(name),
1777 NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1778 NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1779 NativeLibKind::RawDylib => {
1780 // FIXME(#58713): Proper handling for raw dylibs.
1781 bug!("raw_dylib feature not yet implemented
");
1787 // # Rust Crate linking
1789 // Rust crates are not considered at all when creating an rlib output. All
1790 // dependencies will be linked when producing the final output (instead of
1791 // the intermediate rlib version)
1792 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1793 cmd: &mut dyn Linker,
1795 codegen_results: &CodegenResults,
1796 crate_type: CrateType,
1799 // All of the heavy lifting has previously been accomplished by the
1800 // dependency_format module of the compiler. This is just crawling the
1801 // output of that module, adding crates as necessary.
1803 // Linking to a rlib involves just passing it to the linker (the linker
1804 // will slurp up the object files inside), and linking to a dynamic library
1805 // involves just passing the right -l flag.
1807 let (_, data) = codegen_results
1811 .find(|(ty, _)| *ty == crate_type)
1812 .expect("failed to find
crate type in dependency format list
");
1814 // Invoke get_used_crates to ensure that we get a topological sorting of
1816 let deps = &codegen_results.crate_info.used_crates_dynamic;
1818 // There's a few internal crates in the standard library (aka libcore and
1819 // libstd) which actually have a circular dependence upon one another. This
1820 // currently arises through "weak lang items
" where libcore requires things
1821 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1822 // circular dependence to work correctly in all situations we'll need to be
1823 // sure to correctly apply the `--start-group` and `--end-group` options to
1824 // GNU linkers, otherwise if we don't use any other symbol from the standard
1825 // library it'll get discarded and the whole application won't link.
1827 // In this loop we're calculating the `group_end`, after which crate to
1828 // pass `--end-group` and `group_start`, before which crate to pass
1829 // `--start-group`. We currently do this by passing `--end-group` after
1830 // the first crate (when iterating backwards) that requires a lang item
1831 // defined somewhere else. Once that's set then when we've defined all the
1832 // necessary lang items we'll pass `--start-group`.
1834 // Note that this isn't amazing logic for now but it should do the trick
1835 // for the current implementation of the standard library.
1836 let mut group_end = None;
1837 let mut group_start = None;
1838 // Crates available for linking thus far.
1839 let mut available = FxHashSet::default();
1840 // Crates required to satisfy dependencies discovered so far.
1841 let mut required = FxHashSet::default();
1843 let info = &codegen_results.crate_info;
1844 for &(cnum, _) in deps.iter().rev() {
1845 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1846 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1847 required.extend(missing_crates);
1850 required.insert(Some(cnum));
1851 available.insert(Some(cnum));
1853 if required.len() > available.len() && group_end.is_none() {
1854 group_end = Some(cnum);
1856 if required.len() == available.len() && group_end.is_some() {
1857 group_start = Some(cnum);
1862 // If we didn't end up filling in all lang items from upstream crates then
1863 // we'll be filling it in with our crate. This probably means we're the
1864 // standard library itself, so skip this for now.
1865 if group_end.is_some() && group_start.is_none() {
1869 let mut compiler_builtins = None;
1871 for &(cnum, _) in deps.iter() {
1872 if group_start == Some(cnum) {
1876 // We may not pass all crates through to the linker. Some crates may
1877 // appear statically in an existing dylib, meaning we'll pick up all the
1878 // symbols from the dylib.
1879 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1880 match data[cnum.as_usize() - 1] {
1881 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1882 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1884 // compiler-builtins are always placed last to ensure that they're
1885 // linked correctly.
1886 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1887 assert!(compiler_builtins.is_none());
1888 compiler_builtins = Some(cnum);
1890 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1891 Linkage::Static => {
1892 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1894 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1897 if group_end == Some(cnum) {
1902 // compiler-builtins are always placed last to ensure that they're
1903 // linked correctly.
1904 // We must always link the `compiler_builtins` crate statically. Even if it
1905 // was already "included
" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1907 if let Some(cnum) = compiler_builtins {
1908 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1911 // Converts a library file-stem into a cc -l argument
1912 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1913 if stem.starts_with("lib
") && !config.target.options.is_like_windows {
1920 // Adds the static "rlib
" versions of all crates to the command line.
1921 // There's a bit of magic which happens here specifically related to LTO and
1922 // dynamic libraries. Specifically:
1924 // * For LTO, we remove upstream object files.
1925 // * For dylibs we remove metadata and bytecode from upstream rlibs
1927 // When performing LTO, almost(*) all of the bytecode from the upstream
1928 // libraries has already been included in our object file output. As a
1929 // result we need to remove the object files in the upstream libraries so
1930 // the linker doesn't try to include them twice (or whine about duplicate
1931 // symbols). We must continue to include the rest of the rlib, however, as
1932 // it may contain static native libraries which must be linked in.
1934 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1935 // their bytecode wasn't included. The object files in those libraries must
1936 // still be passed to the linker.
1938 // When making a dynamic library, linkers by default don't include any
1939 // object files in an archive if they're not necessary to resolve the link.
1940 // We basically want to convert the archive (rlib) to a dylib, though, so we
1941 // *do* want everything included in the output, regardless of whether the
1942 // linker thinks it's needed or not. As a result we must use the
1943 // --whole-archive option (or the platform equivalent). When using this
1944 // option the linker will fail if there are non-objects in the archive (such
1945 // as our own metadata and/or bytecode). All in all, for rlibs to be
1946 // entirely included in dylibs, we need to remove all non-object files.
1948 // Note, however, that if we're not doing LTO or we're not producing a dylib
1949 // (aka we're making an executable), we can just pass the rlib blindly to
1950 // the linker (fast) because it's fine if it's not actually included as
1951 // we're at the end of the dependency chain.
1952 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1953 cmd: &mut dyn Linker,
1955 codegen_results: &CodegenResults,
1957 crate_type: CrateType,
1960 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1961 let cratepath = &src.rlib.as_ref().unwrap().0;
1963 // See the comment above in `link_staticlib` and `link_rlib` for why if
1964 // there's a static library that's not relevant we skip all object
1966 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1967 let skip_native = native_libs
1969 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1971 if (!are_upstream_rust_objects_already_included(sess)
1972 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1973 && crate_type != CrateType::Dylib
1976 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1980 let dst = tmpdir.join(cratepath.file_name().unwrap());
1981 let name = cratepath.file_name().unwrap().to_str().unwrap();
1982 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1984 sess.prof.generic_activity_with_arg("link_altering_rlib
", name).run(|| {
1985 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1986 archive.update_symbols();
1988 let mut any_objects = false;
1989 for f in archive.src_files() {
1990 if f == METADATA_FILENAME {
1991 archive.remove_file(&f);
1995 let canonical = f.replace("-", "_
");
1996 let canonical_name = name.replace("-", "_
");
1998 let is_rust_object =
1999 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2001 // If we've been requested to skip all native object files
2002 // (those not generated by the rust compiler) then we can skip
2003 // this file. See above for why we may want to do this.
2004 let skip_because_cfg_say_so = skip_native && !is_rust_object;
2006 // If we're performing LTO and this is a rust-generated object
2007 // file, then we don't need the object file as it's part of the
2008 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2009 // though, so we let that object file slide.
2010 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
2012 && (sess.target.target.options.no_builtins
2013 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
2015 if skip_because_cfg_say_so || skip_because_lto {
2016 archive.remove_file(&f);
2027 // If we're creating a dylib, then we need to include the
2028 // whole of each object in our archive into that artifact. This is
2029 // because a `dylib` can be reused as an intermediate artifact.
2031 // Note, though, that we don't want to include the whole of a
2032 // compiler-builtins crate (e.g., compiler-rt) because it'll get
2033 // repeatedly linked anyway.
2034 if crate_type == CrateType::Dylib
2035 && codegen_results.crate_info.compiler_builtins != Some(cnum)
2037 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
2039 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
2044 // Same thing as above, but for dynamic crates instead of static crates.
2045 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2046 // Just need to tell the linker about where the library lives and
2048 let parent = cratepath.parent();
2049 if let Some(dir) = parent {
2050 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2052 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2053 cmd.link_rust_dylib(
2054 Symbol::intern(&unlib(&sess.target, filestem)),
2055 parent.unwrap_or(Path::new("")),
2060 // Link in all of our upstream crates' native dependencies. Remember that
2061 // all of these upstream native dependencies are all non-static
2062 // dependencies. We've got two cases then:
2064 // 1. The upstream crate is an rlib. In this case we *must* link in the
2065 // native dependency because the rlib is just an archive.
2067 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
2068 // have the dependency present on the system somewhere. Thus, we don't
2069 // gain a whole lot from not linking in the dynamic dependency to this
2072 // The use case for this is a little subtle. In theory the native
2073 // dependencies of a crate are purely an implementation detail of the crate
2074 // itself, but the problem arises with generic and inlined functions. If a
2075 // generic function calls a native function, then the generic function must
2076 // be instantiated in the target crate, meaning that the native symbol must
2077 // also be resolved in the target crate.
2078 fn add_upstream_native_libraries(
2079 cmd: &mut dyn Linker,
2081 codegen_results: &CodegenResults,
2082 crate_type: CrateType,
2084 // Be sure to use a topological sorting of crates because there may be
2085 // interdependencies between native libraries. When passing -nodefaultlibs,
2086 // for example, almost all native libraries depend on libc, so we have to
2087 // make sure that's all the way at the right (liblibc is near the base of
2088 // the dependency chain).
2090 // This passes RequireStatic, but the actual requirement doesn't matter,
2091 // we're just getting an ordering of crate numbers, we're not worried about
2093 let (_, data) = codegen_results
2097 .find(|(ty, _)| *ty == crate_type)
2098 .expect("failed to find
crate type in dependency format list
");
2100 let crates = &codegen_results.crate_info.used_crates_static;
2101 for &(cnum, _) in crates {
2102 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2103 let name = match lib.name {
2107 if !relevant_lib(sess, &lib) {
2111 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2112 NativeLibKind::Framework => cmd.link_framework(name),
2113 NativeLibKind::StaticNoBundle => {
2114 // Link "static-nobundle
" native libs only if the crate they originate from
2115 // is being linked statically to the current crate. If it's linked dynamically
2116 // or is an rlib already included via some other dylib crate, the symbols from
2117 // native libs will have already been included in that dylib.
2118 if data[cnum.as_usize() - 1] == Linkage::Static {
2119 cmd.link_staticlib(name)
2122 // ignore statically included native libraries here as we've
2123 // already included them when we included the rust library
2125 NativeLibKind::StaticBundle => {}
2126 NativeLibKind::RawDylib => {
2127 // FIXME(#58713): Proper handling for raw dylibs.
2128 bug!("raw_dylib feature not yet implemented
");
2135 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2137 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2142 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2144 config::Lto::Fat => true,
2145 config::Lto::Thin => {
2146 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2147 // any upstream object files have not been copied yet.
2148 !sess.opts.cg.linker_plugin_lto.enabled()
2150 config::Lto::No | config::Lto::ThinLocal => false,