1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_fs_util::fix_windows_verbatim_for_gcc;
3 use rustc_hir::def_id::CrateNum;
4 use rustc_middle::middle::cstore::{EncodedMetadata, LibSource, NativeLibrary, NativeLibraryKind};
5 use rustc_middle::middle::dependency_format::Linkage;
6 use rustc_session::config::{
7 self, CFGuard, DebugInfo, OutputFilenames, OutputType, PrintRequest, Sanitizer,
9 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
10 use rustc_session::search_paths::PathKind;
11 /// For all the linkers we support, and information they might
12 /// need out of the shared crate context before we get rid of it.
13 use rustc_session::{filesearch, Session};
14 use rustc_span::symbol::Symbol;
15 use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, RelroLevel};
17 use super::archive::ArchiveBuilder;
18 use super::command::Command;
19 use super::linker::Linker;
20 use super::rpath::{self, RPathConfig};
21 use crate::{looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME};
23 use cc::windows_registry;
24 use tempfile::{Builder as TempFileBuilder, TempDir};
29 use std::ffi::OsString;
33 use std::path::{Path, PathBuf};
34 use std::process::{ExitStatus, Output, Stdio};
37 pub fn remove(sess: &Session, path: &Path) {
38 if let Err(e) = fs::remove_file(path) {
39 sess.err(&format!("failed to remove {}: {}", path.display(), e));
43 /// Performs the linkage portion of the compilation phase. This will generate all
44 /// of the requested outputs for this compilation session.
45 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
47 codegen_results: &CodegenResults,
48 outputs: &OutputFilenames,
52 let _timer = sess.timer("link_binary");
53 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
54 for &crate_type in sess.crate_types.borrow().iter() {
55 // Ignore executable crates if we have -Z no-codegen, as they will error.
56 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
58 && crate_type == config::CrateType::Executable
63 if invalid_output_for_target(sess, crate_type) {
65 "invalid output type `{:?}` for target os `{}`",
67 sess.opts.target_triple
71 sess.time("link_binary_check_files_are_writeable", || {
72 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
73 check_file_is_writeable(obj, sess);
77 let tmpdir = TempFileBuilder::new()
80 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
82 if outputs.outputs.should_codegen() {
83 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
85 config::CrateType::Rlib => {
86 let _timer = sess.timer("link_rlib");
96 config::CrateType::Staticlib => {
97 link_staticlib::<B>(sess, codegen_results, &out_filename, &tmpdir);
110 if sess.opts.json_artifact_notifications {
111 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
115 if sess.opts.cg.save_temps {
116 let _ = tmpdir.into_path();
120 // Remove the temporary object file and metadata if we aren't saving temps
121 sess.time("link_binary_remove_temps", || {
122 if !sess.opts.cg.save_temps {
123 if sess.opts.output_types.should_codegen()
124 && !preserve_objects_for_their_debuginfo(sess)
126 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
130 if let Some(ref metadata_module) = codegen_results.metadata_module {
131 if let Some(ref obj) = metadata_module.object {
135 if let Some(ref allocator_module) = codegen_results.allocator_module {
136 if let Some(ref obj) = allocator_module.object {
144 // The third parameter is for env vars, used on windows to set up the
145 // path for MSVC to find its DLLs, and gcc to find its bundled
147 fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> Command {
148 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
150 // If our linker looks like a batch script on Windows then to execute this
151 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
152 // emscripten where the linker is `emcc.bat` and needs to be spawned as
153 // `cmd /c emcc.bat ...`.
155 // This worked historically but is needed manually since #42436 (regression
156 // was tagged as #42791) and some more info can be found on #44443 for
157 // emscripten itself.
158 let mut cmd = match linker.to_str() {
159 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
161 LinkerFlavor::Lld(f) => Command::lld(linker, f),
163 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
165 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
167 _ => Command::new(linker),
171 // UWP apps have API restrictions enforced during Store submissions.
172 // To comply with the Windows App Certification Kit,
173 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
174 let t = &sess.target.target;
175 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
176 && t.target_vendor == "uwp"
178 if let Some(ref tool) = msvc_tool {
179 let original_path = tool.path();
180 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
181 let arch = match t.arch.as_str() {
182 "x86_64" => Some("x64".to_string()),
183 "x86" => Some("x86".to_string()),
184 "aarch64" => Some("arm64".to_string()),
187 if let Some(ref a) = arch {
188 // FIXME: Move this to `fn linker_with_args`.
189 let mut arg = OsString::from("/LIBPATH:");
190 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
193 warn!("arch is not supported");
196 warn!("MSVC root path lib location not found");
199 warn!("link.exe not found");
203 // The compiler's sysroot often has some bundled tools, so add it to the
204 // PATH for the child.
205 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
206 let mut msvc_changed_path = false;
207 if sess.target.target.options.is_like_msvc {
208 if let Some(ref tool) = msvc_tool {
209 cmd.args(tool.args());
210 for &(ref k, ref v) in tool.env() {
212 new_path.extend(env::split_paths(v));
213 msvc_changed_path = true;
221 if !msvc_changed_path {
222 if let Some(path) = env::var_os("PATH") {
223 new_path.extend(env::split_paths(&path));
226 cmd.env("PATH", env::join_paths(new_path).unwrap());
231 pub fn each_linked_rlib(
233 f: &mut dyn FnMut(CrateNum, &Path),
234 ) -> Result<(), String> {
235 let crates = info.used_crates_static.iter();
237 for (ty, list) in info.dependency_formats.iter() {
239 config::CrateType::Executable
240 | config::CrateType::Staticlib
241 | config::CrateType::Cdylib
242 | config::CrateType::ProcMacro => {
249 let fmts = match fmts {
251 None => return Err("could not find formats for rlibs".to_string()),
253 for &(cnum, ref path) in crates {
254 match fmts.get(cnum.as_usize() - 1) {
255 Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
257 None => return Err("could not find formats for rlibs".to_string()),
259 let name = &info.crate_name[&cnum];
260 let path = match *path {
261 LibSource::Some(ref p) => p,
262 LibSource::MetadataOnly => {
264 "could not find rlib for: `{}`, found rmeta (metadata) file",
268 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
275 /// We use a temp directory here to avoid races between concurrent rustc processes,
276 /// such as builds in the same directory using the same filename for metadata while
277 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
278 /// directory being searched for `extern crate` (observing an incomplete file).
279 /// The returned path is the temporary file containing the complete metadata.
280 pub fn emit_metadata(sess: &Session, metadata: &EncodedMetadata, tmpdir: &TempDir) -> PathBuf {
281 let out_filename = tmpdir.path().join(METADATA_FILENAME);
282 let result = fs::write(&out_filename, &metadata.raw_data);
284 if let Err(e) = result {
285 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
293 // An rlib in its current incarnation is essentially a renamed .a file. The
294 // rlib primarily contains the object file of the crate, but it also contains
295 // all of the object files from native libraries. This is done by unzipping
296 // native libraries and inserting all of the contents into this archive.
297 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
299 codegen_results: &CodegenResults,
304 info!("preparing rlib to {:?}", out_filename);
305 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
307 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
311 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
312 // we may not be configured to actually include a static library if we're
313 // adding it here. That's because later when we consume this rlib we'll
314 // decide whether we actually needed the static library or not.
316 // To do this "correctly" we'd need to keep track of which libraries added
317 // which object files to the archive. We don't do that here, however. The
318 // #[link(cfg(..))] feature is unstable, though, and only intended to get
319 // liblibc working. In that sense the check below just indicates that if
320 // there are any libraries we want to omit object files for at link time we
321 // just exclude all custom object files.
323 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
324 // feature then we'll need to figure out how to record what objects were
325 // loaded from the libraries found here and then encode that into the
326 // metadata of the rlib we're generating somehow.
327 for lib in codegen_results.crate_info.used_libraries.iter() {
329 NativeLibraryKind::NativeStatic => {}
330 NativeLibraryKind::NativeStaticNobundle
331 | NativeLibraryKind::NativeFramework
332 | NativeLibraryKind::NativeRawDylib
333 | NativeLibraryKind::NativeUnknown => continue,
335 if let Some(name) = lib.name {
336 ab.add_native_library(name);
340 // After adding all files to the archive, we need to update the
341 // symbol table of the archive.
344 // Note that it is important that we add all of our non-object "magical
345 // files" *after* all of the object files in the archive. The reason for
346 // this is as follows:
348 // * When performing LTO, this archive will be modified to remove
349 // objects from above. The reason for this is described below.
351 // * When the system linker looks at an archive, it will attempt to
352 // determine the architecture of the archive in order to see whether its
355 // The algorithm for this detection is: iterate over the files in the
356 // archive. Skip magical SYMDEF names. Interpret the first file as an
357 // object file. Read architecture from the object file.
359 // * As one can probably see, if "metadata" and "foo.bc" were placed
360 // before all of the objects, then the architecture of this archive would
361 // not be correctly inferred once 'foo.o' is removed.
363 // Basically, all this means is that this code should not move above the
366 RlibFlavor::Normal => {
367 // Instead of putting the metadata in an object file section, rlibs
368 // contain the metadata in a separate file.
369 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
371 // After adding all files to the archive, we need to update the
372 // symbol table of the archive. This currently dies on macOS (see
373 // #11162), and isn't necessary there anyway
374 if !sess.target.target.options.is_like_osx {
379 RlibFlavor::StaticlibBase => {
380 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
381 if let Some(obj) = obj {
390 // Create a static archive
392 // This is essentially the same thing as an rlib, but it also involves adding
393 // all of the upstream crates' objects into the archive. This will slurp in
394 // all of the native libraries of upstream dependencies as well.
396 // Additionally, there's no way for us to link dynamic libraries, so we warn
397 // about all dynamic library dependencies that they're not linked in.
399 // There's no need to include metadata in a static archive, so ensure to not
400 // link in the metadata object file (and also don't prepare the archive with a
402 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
404 codegen_results: &CodegenResults,
409 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
410 let mut all_native_libs = vec![];
412 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
413 let name = &codegen_results.crate_info.crate_name[&cnum];
414 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
416 // Here when we include the rlib into our staticlib we need to make a
417 // decision whether to include the extra object files along the way.
418 // These extra object files come from statically included native
419 // libraries, but they may be cfg'd away with #[link(cfg(..))].
421 // This unstable feature, though, only needs liblibc to work. The only
422 // use case there is where musl is statically included in liblibc.rlib,
423 // so if we don't want the included version we just need to skip it. As
424 // a result the logic here is that if *any* linked library is cfg'd away
425 // we just skip all object files.
427 // Clearly this is not sufficient for a general purpose feature, and
428 // we'd want to read from the library's metadata to determine which
429 // object files come from where and selectively skip them.
430 let skip_object_files = native_libs
432 .any(|lib| lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib));
436 are_upstream_rust_objects_already_included(sess)
437 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
442 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
444 if let Err(e) = res {
451 if !all_native_libs.is_empty() {
452 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
453 print_native_static_libs(sess, &all_native_libs);
458 // Create a dynamic library or executable
460 // This will invoke the system linker/cc to create the resulting file. This
461 // links to all upstream files as well.
462 fn link_natively<'a, B: ArchiveBuilder<'a>>(
464 crate_type: config::CrateType,
466 codegen_results: &CodegenResults,
470 info!("preparing {:?} to {:?}", crate_type, out_filename);
471 let (linker_path, flavor) = linker_and_flavor(sess);
472 let mut cmd = linker_with_args::<B>(
483 for &(ref k, ref v) in &sess.target.target.options.link_env {
486 for k in &sess.target.target.options.link_env_remove {
490 if sess.opts.debugging_opts.print_link_args {
491 println!("{:?}", &cmd);
494 // May have not found libraries in the right formats.
495 sess.abort_if_errors();
497 // Invoke the system linker
499 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
504 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
505 let output = match prog {
506 Ok(ref output) => output,
509 if output.status.success() {
512 let mut out = output.stderr.clone();
513 out.extend(&output.stdout);
514 let out = String::from_utf8_lossy(&out);
516 // Check to see if the link failed with "unrecognized command line option:
517 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
518 // reperform the link step without the -no-pie option. This is safe because
519 // if the linker doesn't support -no-pie then it should not default to
520 // linking executables as pie. Different versions of gcc seem to use
521 // different quotes in the error message so don't check for them.
522 if sess.target.target.options.linker_is_gnu
523 && flavor != LinkerFlavor::Ld
524 && (out.contains("unrecognized command line option")
525 || out.contains("unknown argument"))
526 && out.contains("-no-pie")
527 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
529 info!("linker output: {:?}", out);
530 warn!("Linker does not support -no-pie command line option. Retrying without.");
531 for arg in cmd.take_args() {
532 if arg.to_string_lossy() != "-no-pie" {
540 // Here's a terribly awful hack that really shouldn't be present in any
541 // compiler. Here an environment variable is supported to automatically
542 // retry the linker invocation if the linker looks like it segfaulted.
544 // Gee that seems odd, normally segfaults are things we want to know
545 // about! Unfortunately though in rust-lang/rust#38878 we're
546 // experiencing the linker segfaulting on Travis quite a bit which is
547 // causing quite a bit of pain to land PRs when they spuriously fail
548 // due to a segfault.
550 // The issue #38878 has some more debugging information on it as well,
551 // but this unfortunately looks like it's just a race condition in
552 // macOS's linker with some thread pool working in the background. It
553 // seems that no one currently knows a fix for this so in the meantime
554 // we're left with this...
555 if !retry_on_segfault || i > 3 {
558 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
559 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
560 if out.contains(msg_segv) || out.contains(msg_bus) {
562 "looks like the linker segfaulted when we tried to call it, \
563 automatically retrying again. cmd = {:?}, out = {}.",
569 if is_illegal_instruction(&output.status) {
571 "looks like the linker hit an illegal instruction when we \
572 tried to call it, automatically retrying again. cmd = {:?}, ]\
573 out = {}, status = {}.",
574 cmd, out, output.status,
580 fn is_illegal_instruction(status: &ExitStatus) -> bool {
581 use std::os::unix::prelude::*;
582 status.signal() == Some(libc::SIGILL)
586 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
593 fn escape_string(s: &[u8]) -> String {
594 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
595 let mut x = "Non-UTF-8 output: ".to_string();
596 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
600 if !prog.status.success() {
601 let mut output = prog.stderr.clone();
602 output.extend_from_slice(&prog.stdout);
603 sess.struct_err(&format!(
604 "linking with `{}` failed: {}",
605 linker_path.display(),
608 .note(&format!("{:?}", &cmd))
609 .note(&escape_string(&output))
611 sess.abort_if_errors();
613 info!("linker stderr:\n{}", escape_string(&prog.stderr));
614 info!("linker stdout:\n{}", escape_string(&prog.stdout));
617 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
619 let mut linker_error = {
620 if linker_not_found {
621 sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
623 sess.struct_err(&format!(
624 "could not exec the linker `{}`",
625 linker_path.display()
630 linker_error.note(&e.to_string());
632 if !linker_not_found {
633 linker_error.note(&format!("{:?}", &cmd));
638 if sess.target.target.options.is_like_msvc && linker_not_found {
639 sess.note_without_error(
640 "the msvc targets depend on the msvc linker \
641 but `link.exe` was not found",
643 sess.note_without_error(
644 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
645 was installed with the Visual C++ option",
648 sess.abort_if_errors();
652 // On macOS, debuggers need this utility to get run to do some munging of
653 // the symbols. Note, though, that if the object files are being preserved
654 // for their debug information there's no need for us to run dsymutil.
655 if sess.target.target.options.is_like_osx
656 && sess.opts.debuginfo != DebugInfo::None
657 && !preserve_objects_for_their_debuginfo(sess)
659 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
660 sess.fatal(&format!("failed to run dsymutil: {}", e))
665 fn link_sanitizer_runtime(sess: &Session, crate_type: config::CrateType, linker: &mut dyn Linker) {
666 let sanitizer = match &sess.opts.debugging_opts.sanitizer {
671 if crate_type != config::CrateType::Executable {
675 let name = match sanitizer {
676 Sanitizer::Address => "asan",
677 Sanitizer::Leak => "lsan",
678 Sanitizer::Memory => "msan",
679 Sanitizer::Thread => "tsan",
682 let default_sysroot = filesearch::get_or_default_sysroot();
684 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
685 let channel = option_env!("CFG_RELEASE_CHANNEL")
686 .map(|channel| format!("-{}", channel))
687 .unwrap_or_default();
689 match sess.opts.target_triple.triple() {
690 "x86_64-apple-darwin" => {
691 // On Apple platforms, the sanitizer is always built as a dylib, and
692 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
693 // rpath to the library as well (the rpath should be absolute, see
694 // PR #41352 for details).
695 let libname = format!("rustc{}_rt.{}", channel, name);
696 let rpath = default_tlib.to_str().expect("non-utf8 component in path");
697 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
698 linker.link_dylib(Symbol::intern(&libname));
700 "x86_64-unknown-linux-gnu" | "x86_64-fuchsia" | "aarch64-fuchsia" => {
701 let filename = format!("librustc{}_rt.{}.a", channel, name);
702 let path = default_tlib.join(&filename);
703 linker.link_whole_rlib(&path);
709 /// Returns a boolean indicating whether the specified crate should be ignored
712 /// Crates ignored during LTO are not lumped together in the "massive object
713 /// file" that we create and are linked in their normal rlib states. See
714 /// comments below for what crates do not participate in LTO.
716 /// It's unusual for a crate to not participate in LTO. Typically only
717 /// compiler-specific and unstable crates have a reason to not participate in
719 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
720 // If our target enables builtin function lowering in LLVM then the
721 // crates providing these functions don't participate in LTO (e.g.
722 // no_builtins or compiler builtins crates).
723 !sess.target.target.options.no_builtins
724 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
727 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
730 linker: Option<PathBuf>,
731 flavor: Option<LinkerFlavor>,
732 ) -> Option<(PathBuf, LinkerFlavor)> {
733 match (linker, flavor) {
734 (Some(linker), Some(flavor)) => Some((linker, flavor)),
735 // only the linker flavor is known; use the default linker for the selected flavor
736 (None, Some(flavor)) => Some((
737 PathBuf::from(match flavor {
738 LinkerFlavor::Em => {
745 LinkerFlavor::Gcc => {
746 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
747 // On historical Solaris systems, "cc" may have
748 // been Sun Studio, which is not flag-compatible
749 // with "gcc". This history casts a long shadow,
750 // and many modern illumos distributions today
751 // ship GCC as "gcc" without also making it
752 // available as "cc".
758 LinkerFlavor::Ld => "ld",
759 LinkerFlavor::Msvc => "link.exe",
760 LinkerFlavor::Lld(_) => "lld",
761 LinkerFlavor::PtxLinker => "rust-ptx-linker",
765 (Some(linker), None) => {
766 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
767 sess.fatal("couldn't extract file stem from specified linker")
770 let flavor = if stem == "emcc" {
772 } else if stem == "gcc"
773 || stem.ends_with("-gcc")
775 || stem.ends_with("-clang")
778 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
780 } else if stem == "link" || stem == "lld-link" {
782 } else if stem == "lld" || stem == "rust-lld" {
783 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
785 // fall back to the value in the target spec
786 sess.target.target.linker_flavor
789 Some((linker, flavor))
791 (None, None) => None,
795 // linker and linker flavor specified via command line have precedence over what the target
796 // specification specifies
797 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
801 if let Some(ret) = infer_from(
803 sess.target.target.options.linker.clone().map(PathBuf::from),
804 Some(sess.target.target.linker_flavor),
809 bug!("Not enough information provided to determine how to invoke the linker");
812 /// Returns a boolean indicating whether we should preserve the object files on
813 /// the filesystem for their debug information. This is often useful with
814 /// split-dwarf like schemes.
815 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
816 // If the objects don't have debuginfo there's nothing to preserve.
817 if sess.opts.debuginfo == config::DebugInfo::None {
821 // If we're only producing artifacts that are archives, no need to preserve
822 // the objects as they're losslessly contained inside the archives.
823 let output_linked = sess
827 .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib);
832 // If we're on OSX then the equivalent of split dwarf is turned on by
833 // default. The final executable won't actually have any debug information
834 // except it'll have pointers to elsewhere. Historically we've always run
835 // `dsymutil` to "link all the dwarf together" but this is actually sort of
836 // a bummer for incremental compilation! (the whole point of split dwarf is
837 // that you don't do this sort of dwarf link).
839 // Basically as a result this just means that if we're on OSX and we're
840 // *not* running dsymutil then the object files are the only source of truth
841 // for debug information, so we must preserve them.
842 if sess.target.target.options.is_like_osx {
843 return !sess.opts.debugging_opts.run_dsymutil;
849 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
850 sess.target_filesearch(PathKind::Native).search_path_dirs()
858 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
859 let lib_args: Vec<_> = all_native_libs
861 .filter(|l| relevant_lib(sess, l))
863 let name = lib.name?;
865 NativeLibraryKind::NativeStaticNobundle | NativeLibraryKind::NativeUnknown => {
866 if sess.target.target.options.is_like_msvc {
867 Some(format!("{}.lib", name))
869 Some(format!("-l{}", name))
872 NativeLibraryKind::NativeFramework => {
873 // ld-only syntax, since there are no frameworks in MSVC
874 Some(format!("-framework {}", name))
876 // These are included, no need to print them
877 NativeLibraryKind::NativeStatic | NativeLibraryKind::NativeRawDylib => None,
881 if !lib_args.is_empty() {
882 sess.note_without_error(
883 "Link against the following native artifacts when linking \
884 against this static library. The order and any duplication \
885 can be significant on some platforms.",
887 // Prefix for greppability
888 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
892 // Because windows-gnu target is meant to be self-contained for pure Rust code it bundles
893 // own mingw-w64 libraries. These libraries are usually not compatible with mingw-w64
894 // installed in the system. This breaks many cases where Rust is mixed with other languages
895 // (e.g. *-sys crates).
896 // We prefer system mingw-w64 libraries if they are available to avoid this issue.
897 fn get_crt_libs_path(sess: &Session) -> Option<PathBuf> {
898 fn find_exe_in_path<P>(exe_name: P) -> Option<PathBuf>
902 for dir in env::split_paths(&env::var_os("PATH")?) {
903 let full_path = dir.join(&exe_name);
904 if full_path.is_file() {
905 return Some(fix_windows_verbatim_for_gcc(&full_path));
911 fn probe(sess: &Session) -> Option<PathBuf> {
912 if let (linker, LinkerFlavor::Gcc) = linker_and_flavor(&sess) {
913 let linker_path = if cfg!(windows) && linker.extension().is_none() {
914 linker.with_extension("exe")
918 if let Some(linker_path) = find_exe_in_path(linker_path) {
919 let mingw_arch = match &sess.target.target.arch {
920 x if x == "x86" => "i686",
923 let mingw_bits = &sess.target.target.target_pointer_width;
924 let mingw_dir = format!("{}-w64-mingw32", mingw_arch);
925 // Here we have path/bin/gcc but we need path/
926 let mut path = linker_path;
929 // Loosely based on Clang MinGW driver
930 let probe_paths = vec![
931 path.join(&mingw_dir).join("lib"), // Typical path
932 path.join(&mingw_dir).join("sys-root/mingw/lib"), // Rare path
934 "lib/mingw/tools/install/mingw{}/{}/lib",
935 &mingw_bits, &mingw_dir
936 )), // Chocolatey is creative
938 for probe_path in probe_paths {
939 if probe_path.join("crt2.o").exists() {
940 return Some(probe_path);
948 let mut system_library_path = sess.system_library_path.borrow_mut();
949 match &*system_library_path {
950 Some(Some(compiler_libs_path)) => Some(compiler_libs_path.clone()),
953 let path = probe(sess);
954 *system_library_path = Some(path.clone());
960 fn get_object_file_path(sess: &Session, name: &str) -> PathBuf {
961 // prefer system {,dll}crt2.o libs, see get_crt_libs_path comment for more details
962 if sess.target.target.llvm_target.contains("windows-gnu") {
963 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
964 let file_path = compiler_libs_path.join(name);
965 if file_path.exists() {
970 let fs = sess.target_filesearch(PathKind::Native);
971 let file_path = fs.get_lib_path().join(name);
972 if file_path.exists() {
975 for search_path in fs.search_paths() {
976 let file_path = search_path.dir.join(name);
977 if file_path.exists() {
989 ) -> io::Result<Output> {
990 // When attempting to spawn the linker we run a risk of blowing out the
991 // size limits for spawning a new process with respect to the arguments
992 // we pass on the command line.
994 // Here we attempt to handle errors from the OS saying "your list of
995 // arguments is too big" by reinvoking the linker again with an `@`-file
996 // that contains all the arguments. The theory is that this is then
997 // accepted on all linkers and the linker will read all its options out of
998 // there instead of looking at the command line.
999 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1000 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1002 let output = child.wait_with_output();
1003 flush_linked_file(&output, out_filename)?;
1006 Err(ref e) if command_line_too_big(e) => {
1007 info!("command line to linker was too big: {}", e);
1009 Err(e) => return Err(e),
1013 info!("falling back to passing arguments to linker via an @-file");
1014 let mut cmd2 = cmd.clone();
1015 let mut args = String::new();
1016 for arg in cmd2.take_args() {
1019 arg: arg.to_str().unwrap(),
1020 is_like_msvc: sess.target.target.options.is_like_msvc,
1024 args.push_str("\n");
1026 let file = tmpdir.join("linker-arguments");
1027 let bytes = if sess.target.target.options.is_like_msvc {
1028 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1029 // start the stream with a UTF-16 BOM
1030 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1031 // encode in little endian
1033 out.push((c >> 8) as u8);
1039 fs::write(&file, &bytes)?;
1040 cmd2.arg(format!("@{}", file.display()));
1041 info!("invoking linker {:?}", cmd2);
1042 let output = cmd2.output();
1043 flush_linked_file(&output, out_filename)?;
1047 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1052 fn flush_linked_file(
1053 command_output: &io::Result<Output>,
1054 out_filename: &Path,
1055 ) -> io::Result<()> {
1056 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1057 // even long after process exit, causing nasty, non-reproducible output bugs.
1059 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1061 // А full writeup of the original Chrome bug can be found at
1062 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1064 if let &Ok(ref out) = command_output {
1065 if out.status.success() {
1066 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1076 fn command_line_too_big(err: &io::Error) -> bool {
1077 err.raw_os_error() == Some(::libc::E2BIG)
1081 fn command_line_too_big(err: &io::Error) -> bool {
1082 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1083 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1091 impl<'a> fmt::Display for Escape<'a> {
1092 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1093 if self.is_like_msvc {
1094 // This is "documented" at
1095 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1097 // Unfortunately there's not a great specification of the
1098 // syntax I could find online (at least) but some local
1099 // testing showed that this seemed sufficient-ish to catch
1100 // at least a few edge cases.
1102 for c in self.arg.chars() {
1104 '"' => write!(f, "\\{}", c)?,
1105 c => write!(f, "{}", c)?,
1110 // This is documented at https://linux.die.net/man/1/ld, namely:
1112 // > Options in file are separated by whitespace. A whitespace
1113 // > character may be included in an option by surrounding the
1114 // > entire option in either single or double quotes. Any
1115 // > character (including a backslash) may be included by
1116 // > prefixing the character to be included with a backslash.
1118 // We put an argument on each line, so all we need to do is
1119 // ensure the line is interpreted as one whole argument.
1120 for c in self.arg.chars() {
1122 '\\' | ' ' => write!(f, "\\{}", c)?,
1123 c => write!(f, "{}", c)?,
1132 /// Add begin object files defined by the target spec.
1133 fn add_pre_link_objects(cmd: &mut dyn Linker, sess: &Session, crate_type: config::CrateType) {
1134 let pre_link_objects = if crate_type == config::CrateType::Executable {
1135 &sess.target.target.options.pre_link_objects_exe
1137 &sess.target.target.options.pre_link_objects_dll
1139 for obj in pre_link_objects {
1140 cmd.add_object(&get_object_file_path(sess, obj));
1143 if crate_type == config::CrateType::Executable && sess.crt_static(Some(crate_type)) {
1144 for obj in &sess.target.target.options.pre_link_objects_exe_crt {
1145 cmd.add_object(&get_object_file_path(sess, obj));
1150 /// Add end object files defined by the target spec.
1151 fn add_post_link_objects(cmd: &mut dyn Linker, sess: &Session, crate_type: config::CrateType) {
1152 for obj in &sess.target.target.options.post_link_objects {
1153 cmd.add_object(&get_object_file_path(sess, obj));
1155 if sess.crt_static(Some(crate_type)) {
1156 for obj in &sess.target.target.options.post_link_objects_crt {
1157 cmd.add_object(&get_object_file_path(sess, obj));
1162 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1163 /// FIXME: Determine where exactly these args need to be inserted.
1164 fn add_pre_link_args(
1165 cmd: &mut dyn Linker,
1167 flavor: LinkerFlavor,
1168 crate_type: config::CrateType,
1170 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
1173 if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) {
1174 if sess.crt_static(Some(crate_type)) {
1178 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1181 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1182 /// FIXME: Determine where exactly these args need to be inserted.
1183 fn add_user_defined_link_args(
1184 cmd: &mut dyn Linker,
1186 codegen_results: &CodegenResults,
1188 cmd.args(&sess.opts.cg.link_args);
1189 cmd.args(&*codegen_results.crate_info.link_args);
1192 /// Add arbitrary "late link" args defined by the target spec.
1193 /// FIXME: Determine where exactly these args need to be inserted.
1194 fn add_late_link_args(
1195 cmd: &mut dyn Linker,
1197 flavor: LinkerFlavor,
1198 crate_type: config::CrateType,
1199 codegen_results: &CodegenResults,
1201 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
1204 let any_dynamic_crate = crate_type == config::CrateType::Dylib
1205 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1206 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1208 if any_dynamic_crate {
1209 if let Some(args) = sess.target.target.options.late_link_args_dynamic.get(&flavor) {
1213 if let Some(args) = sess.target.target.options.late_link_args_static.get(&flavor) {
1219 /// Add arbitrary "post-link" args defined by the target spec.
1220 /// FIXME: Determine where exactly these args need to be inserted.
1221 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1222 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
1227 /// Add object files containing code from the current crate.
1228 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1229 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1230 cmd.add_object(obj);
1234 /// Add object files for allocator code linked once for the whole crate tree.
1235 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1236 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1237 cmd.add_object(obj);
1241 /// Add object files containing metadata for the current crate.
1242 fn add_local_crate_metadata_objects(
1243 cmd: &mut dyn Linker,
1244 crate_type: config::CrateType,
1245 codegen_results: &CodegenResults,
1247 // When linking a dynamic library, we put the metadata into a section of the
1248 // executable. This metadata is in a separate object file from the main
1249 // object file, so we link that in here.
1250 if crate_type == config::CrateType::Dylib || crate_type == config::CrateType::ProcMacro {
1251 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1253 cmd.add_object(obj);
1258 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1259 /// all its dependency crates.
1260 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1261 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1262 cmd: &mut dyn Linker,
1264 crate_type: config::CrateType,
1265 codegen_results: &CodegenResults,
1268 // Take careful note of the ordering of the arguments we pass to the linker
1269 // here. Linkers will assume that things on the left depend on things to the
1270 // right. Things on the right cannot depend on things on the left. This is
1271 // all formally implemented in terms of resolving symbols (libs on the right
1272 // resolve unknown symbols of libs on the left, but not vice versa).
1274 // For this reason, we have organized the arguments we pass to the linker as
1277 // 1. The local object that LLVM just generated
1278 // 2. Local native libraries
1279 // 3. Upstream rust libraries
1280 // 4. Upstream native libraries
1282 // The rationale behind this ordering is that those items lower down in the
1283 // list can't depend on items higher up in the list. For example nothing can
1284 // depend on what we just generated (e.g., that'd be a circular dependency).
1285 // Upstream rust libraries are not allowed to depend on our local native
1286 // libraries as that would violate the structure of the DAG, in that
1287 // scenario they are required to link to them as well in a shared fashion.
1289 // Note that upstream rust libraries may contain native dependencies as
1290 // well, but they also can't depend on what we just started to add to the
1291 // link line. And finally upstream native libraries can't depend on anything
1292 // in this DAG so far because they're only dylibs and dylibs can only depend
1293 // on other dylibs (e.g., other native deps).
1295 // If -Zlink-native-libraries=false is set, then the assumption is that an
1296 // external build system already has the native dependencies defined, and it
1297 // will provide them to the linker itself.
1298 if sess.opts.debugging_opts.link_native_libraries {
1299 add_local_native_libraries(cmd, sess, codegen_results);
1301 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1302 if sess.opts.debugging_opts.link_native_libraries {
1303 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1307 /// Add sysroot and other globally set directories to the directory search list.
1308 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session) {
1309 // Prefer system mingw-w64 libs, see get_crt_libs_path comment for more details.
1310 if cfg!(windows) && sess.target.target.llvm_target.contains("windows-gnu") {
1311 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1312 cmd.include_path(&compiler_libs_path);
1316 // The default library location, we need this to find the runtime.
1317 // The location of crates will be determined as needed.
1318 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1319 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1322 /// Add options requesting executables to be position-independent or not position-independent.
1323 fn add_position_independent_executable_args(
1324 cmd: &mut dyn Linker,
1326 flavor: LinkerFlavor,
1327 crate_type: config::CrateType,
1328 codegen_results: &CodegenResults,
1330 if crate_type != config::CrateType::Executable {
1334 if sess.target.target.options.position_independent_executables {
1335 let attr_link_args = &*codegen_results.crate_info.link_args;
1336 let mut user_defined_link_args = sess.opts.cg.link_args.iter().chain(attr_link_args);
1337 if sess.relocation_model() == RelocModel::Pic
1338 && !sess.crt_static(Some(crate_type))
1339 && !user_defined_link_args.any(|x| x == "-static")
1341 cmd.position_independent_executable();
1346 // Recent versions of gcc can be configured to generate position
1347 // independent executables by default. We have to pass -no-pie to
1348 // explicitly turn that off. Not applicable to ld.
1349 if sess.target.target.options.linker_is_gnu && flavor != LinkerFlavor::Ld {
1350 cmd.no_position_independent_executable();
1354 /// Add options making relocation sections in the produced ELF files read-only
1355 /// and suppressing lazy binding.
1356 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1357 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.target.options.relro_level) {
1358 RelroLevel::Full => cmd.full_relro(),
1359 RelroLevel::Partial => cmd.partial_relro(),
1360 RelroLevel::Off => cmd.no_relro(),
1361 RelroLevel::None => {}
1365 /// Add library search paths used at runtime by dynamic linkers.
1367 cmd: &mut dyn Linker,
1369 codegen_results: &CodegenResults,
1370 out_filename: &Path,
1372 // FIXME (#2397): At some point we want to rpath our guesses as to
1373 // where extern libraries might live, based on the
1374 // addl_lib_search_paths
1375 if sess.opts.cg.rpath {
1376 let target_triple = sess.opts.target_triple.triple();
1377 let mut get_install_prefix_lib_path = || {
1378 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1379 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1380 let mut path = PathBuf::from(install_prefix);
1385 let mut rpath_config = RPathConfig {
1386 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1387 out_filename: out_filename.to_path_buf(),
1388 has_rpath: sess.target.target.options.has_rpath,
1389 is_like_osx: sess.target.target.options.is_like_osx,
1390 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1391 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1393 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1397 /// Produce the linker command line containing linker path and arguments.
1398 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1399 /// by the user without creating a custom target specification.
1400 /// `OBJECT-FILES` specify whether the arguments can add object files.
1401 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1402 /// or by the target spec can be inserted here.
1403 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1404 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1406 flavor: LinkerFlavor,
1408 crate_type: config::CrateType,
1410 out_filename: &Path,
1411 codegen_results: &CodegenResults,
1414 let base_cmd = get_linker(sess, path, flavor);
1415 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1416 // to the linker args construction.
1417 assert!(base_cmd.get_args().is_empty() || sess.target.target.target_vendor == "uwp");
1418 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1420 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1421 add_pre_link_args(cmd, sess, flavor, crate_type);
1423 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1424 if sess.target.target.options.is_like_fuchsia {
1425 let prefix = match sess.opts.debugging_opts.sanitizer {
1426 Some(Sanitizer::Address) => "asan/",
1429 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1432 // NO-OPT-OUT, OBJECT-FILES-YES
1433 add_pre_link_objects(cmd, sess, crate_type);
1435 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1436 if sess.target.target.options.is_like_emscripten {
1438 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1439 "DISABLE_EXCEPTION_CATCHING=1"
1441 "DISABLE_EXCEPTION_CATCHING=0"
1445 // OBJECT-FILES-YES, AUDIT-ORDER
1446 link_sanitizer_runtime(sess, crate_type, cmd);
1448 // OBJECT-FILES-NO, AUDIT-ORDER
1449 // Linker plugins should be specified early in the list of arguments
1450 // FIXME: How "early" exactly?
1451 cmd.linker_plugin_lto();
1453 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1454 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1455 add_library_search_dirs(cmd, sess);
1458 add_local_crate_regular_objects(cmd, codegen_results);
1460 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1461 cmd.output_filename(out_filename);
1463 // OBJECT-FILES-NO, AUDIT-ORDER
1464 if crate_type == config::CrateType::Executable && sess.target.target.options.is_like_windows {
1465 if let Some(ref s) = codegen_results.windows_subsystem {
1470 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1471 // If we're building something like a dynamic library then some platforms
1472 // need to make sure that all symbols are exported correctly from the
1474 cmd.export_symbols(tmpdir, crate_type);
1477 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1480 add_local_crate_allocator_objects(cmd, codegen_results);
1482 // OBJECT-FILES-NO, AUDIT-ORDER
1483 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1484 // Try to strip as much out of the generated object by removing unused
1485 // sections if possible. See more comments in linker.rs
1486 if !sess.opts.cg.link_dead_code {
1487 let keep_metadata = crate_type == config::CrateType::Dylib;
1488 cmd.gc_sections(keep_metadata);
1491 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1492 add_position_independent_executable_args(cmd, sess, flavor, crate_type, codegen_results);
1494 // OBJECT-FILES-NO, AUDIT-ORDER
1495 add_relro_args(cmd, sess);
1497 // OBJECT-FILES-NO, AUDIT-ORDER
1498 // Pass optimization flags down to the linker.
1501 // OBJECT-FILES-NO, AUDIT-ORDER
1502 // Pass debuginfo flags down to the linker.
1505 // OBJECT-FILES-NO, AUDIT-ORDER
1506 // We want to prevent the compiler from accidentally leaking in any system libraries,
1507 // so by default we tell linkers not to link to any default libraries.
1508 if !sess.opts.cg.default_linker_libraries && sess.target.target.options.no_default_libraries {
1509 cmd.no_default_libraries();
1513 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1521 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1522 // Tell the linker what we're doing.
1523 if crate_type != config::CrateType::Executable {
1524 cmd.build_dylib(out_filename);
1526 if crate_type == config::CrateType::Executable && sess.crt_static(Some(crate_type)) {
1527 cmd.build_static_executable();
1530 // OBJECT-FILES-NO, AUDIT-ORDER
1531 if sess.opts.cg.profile_generate.enabled() {
1535 // OBJECT-FILES-NO, AUDIT-ORDER
1536 if sess.opts.debugging_opts.control_flow_guard != CFGuard::Disabled {
1537 cmd.control_flow_guard();
1540 // OBJECT-FILES-NO, AUDIT-ORDER
1541 add_rpath_args(cmd, sess, codegen_results, out_filename);
1543 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1544 add_user_defined_link_args(cmd, sess, codegen_results);
1546 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1549 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1550 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1552 // NO-OPT-OUT, OBJECT-FILES-YES
1553 add_post_link_objects(cmd, sess, crate_type);
1555 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1556 add_post_link_args(cmd, sess, flavor);
1561 // # Native library linking
1563 // User-supplied library search paths (-L on the command line). These are
1564 // the same paths used to find Rust crates, so some of them may have been
1565 // added already by the previous crate linking code. This only allows them
1566 // to be found at compile time so it is still entirely up to outside
1567 // forces to make sure that library can be found at runtime.
1569 // Also note that the native libraries linked here are only the ones located
1570 // in the current crate. Upstream crates with native library dependencies
1571 // may have their native library pulled in above.
1572 fn add_local_native_libraries(
1573 cmd: &mut dyn Linker,
1575 codegen_results: &CodegenResults,
1577 let filesearch = sess.target_filesearch(PathKind::All);
1578 for search_path in filesearch.search_paths() {
1579 match search_path.kind {
1580 PathKind::Framework => {
1581 cmd.framework_path(&search_path.dir);
1584 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1590 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1592 let search_path = archive_search_paths(sess);
1593 for lib in relevant_libs {
1594 let name = match lib.name {
1599 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1600 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1601 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(name),
1602 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(name, &search_path),
1603 NativeLibraryKind::NativeRawDylib => {
1604 // FIXME(#58713): Proper handling for raw dylibs.
1605 bug!("raw_dylib feature not yet implemented");
1611 // # Rust Crate linking
1613 // Rust crates are not considered at all when creating an rlib output. All
1614 // dependencies will be linked when producing the final output (instead of
1615 // the intermediate rlib version)
1616 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1617 cmd: &mut dyn Linker,
1619 codegen_results: &CodegenResults,
1620 crate_type: config::CrateType,
1623 // All of the heavy lifting has previously been accomplished by the
1624 // dependency_format module of the compiler. This is just crawling the
1625 // output of that module, adding crates as necessary.
1627 // Linking to a rlib involves just passing it to the linker (the linker
1628 // will slurp up the object files inside), and linking to a dynamic library
1629 // involves just passing the right -l flag.
1631 let (_, data) = codegen_results
1635 .find(|(ty, _)| *ty == crate_type)
1636 .expect("failed to find crate type in dependency format list");
1638 // Invoke get_used_crates to ensure that we get a topological sorting of
1640 let deps = &codegen_results.crate_info.used_crates_dynamic;
1642 // There's a few internal crates in the standard library (aka libcore and
1643 // libstd) which actually have a circular dependence upon one another. This
1644 // currently arises through "weak lang items" where libcore requires things
1645 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1646 // circular dependence to work correctly in all situations we'll need to be
1647 // sure to correctly apply the `--start-group` and `--end-group` options to
1648 // GNU linkers, otherwise if we don't use any other symbol from the standard
1649 // library it'll get discarded and the whole application won't link.
1651 // In this loop we're calculating the `group_end`, after which crate to
1652 // pass `--end-group` and `group_start`, before which crate to pass
1653 // `--start-group`. We currently do this by passing `--end-group` after
1654 // the first crate (when iterating backwards) that requires a lang item
1655 // defined somewhere else. Once that's set then when we've defined all the
1656 // necessary lang items we'll pass `--start-group`.
1658 // Note that this isn't amazing logic for now but it should do the trick
1659 // for the current implementation of the standard library.
1660 let mut group_end = None;
1661 let mut group_start = None;
1662 // Crates available for linking thus far.
1663 let mut available = FxHashSet::default();
1664 // Crates required to satisfy dependencies discovered so far.
1665 let mut required = FxHashSet::default();
1667 let info = &codegen_results.crate_info;
1668 for &(cnum, _) in deps.iter().rev() {
1669 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1670 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1671 required.extend(missing_crates);
1674 required.insert(Some(cnum));
1675 available.insert(Some(cnum));
1677 if required.len() > available.len() && group_end.is_none() {
1678 group_end = Some(cnum);
1680 if required.len() == available.len() && group_end.is_some() {
1681 group_start = Some(cnum);
1686 // If we didn't end up filling in all lang items from upstream crates then
1687 // we'll be filling it in with our crate. This probably means we're the
1688 // standard library itself, so skip this for now.
1689 if group_end.is_some() && group_start.is_none() {
1693 let mut compiler_builtins = None;
1695 for &(cnum, _) in deps.iter() {
1696 if group_start == Some(cnum) {
1700 // We may not pass all crates through to the linker. Some crates may
1701 // appear statically in an existing dylib, meaning we'll pick up all the
1702 // symbols from the dylib.
1703 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1704 match data[cnum.as_usize() - 1] {
1705 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1706 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1708 // compiler-builtins are always placed last to ensure that they're
1709 // linked correctly.
1710 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1711 assert!(compiler_builtins.is_none());
1712 compiler_builtins = Some(cnum);
1714 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1715 Linkage::Static => {
1716 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1718 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1721 if group_end == Some(cnum) {
1726 // compiler-builtins are always placed last to ensure that they're
1727 // linked correctly.
1728 // We must always link the `compiler_builtins` crate statically. Even if it
1729 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1731 if let Some(cnum) = compiler_builtins {
1732 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1735 // Converts a library file-stem into a cc -l argument
1736 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1737 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1744 // Adds the static "rlib" versions of all crates to the command line.
1745 // There's a bit of magic which happens here specifically related to LTO and
1746 // dynamic libraries. Specifically:
1748 // * For LTO, we remove upstream object files.
1749 // * For dylibs we remove metadata and bytecode from upstream rlibs
1751 // When performing LTO, almost(*) all of the bytecode from the upstream
1752 // libraries has already been included in our object file output. As a
1753 // result we need to remove the object files in the upstream libraries so
1754 // the linker doesn't try to include them twice (or whine about duplicate
1755 // symbols). We must continue to include the rest of the rlib, however, as
1756 // it may contain static native libraries which must be linked in.
1758 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1759 // their bytecode wasn't included. The object files in those libraries must
1760 // still be passed to the linker.
1762 // When making a dynamic library, linkers by default don't include any
1763 // object files in an archive if they're not necessary to resolve the link.
1764 // We basically want to convert the archive (rlib) to a dylib, though, so we
1765 // *do* want everything included in the output, regardless of whether the
1766 // linker thinks it's needed or not. As a result we must use the
1767 // --whole-archive option (or the platform equivalent). When using this
1768 // option the linker will fail if there are non-objects in the archive (such
1769 // as our own metadata and/or bytecode). All in all, for rlibs to be
1770 // entirely included in dylibs, we need to remove all non-object files.
1772 // Note, however, that if we're not doing LTO or we're not producing a dylib
1773 // (aka we're making an executable), we can just pass the rlib blindly to
1774 // the linker (fast) because it's fine if it's not actually included as
1775 // we're at the end of the dependency chain.
1776 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1777 cmd: &mut dyn Linker,
1779 codegen_results: &CodegenResults,
1781 crate_type: config::CrateType,
1784 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1785 let cratepath = &src.rlib.as_ref().unwrap().0;
1787 // See the comment above in `link_staticlib` and `link_rlib` for why if
1788 // there's a static library that's not relevant we skip all object
1790 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1791 let skip_native = native_libs
1793 .any(|lib| lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib));
1795 if (!are_upstream_rust_objects_already_included(sess)
1796 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1797 && crate_type != config::CrateType::Dylib
1800 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1804 let dst = tmpdir.join(cratepath.file_name().unwrap());
1805 let name = cratepath.file_name().unwrap().to_str().unwrap();
1806 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1808 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1809 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1810 archive.update_symbols();
1812 let mut any_objects = false;
1813 for f in archive.src_files() {
1814 if f == METADATA_FILENAME {
1815 archive.remove_file(&f);
1819 let canonical = f.replace("-", "_");
1820 let canonical_name = name.replace("-", "_");
1822 let is_rust_object =
1823 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
1825 // If we've been requested to skip all native object files
1826 // (those not generated by the rust compiler) then we can skip
1827 // this file. See above for why we may want to do this.
1828 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1830 // If we're performing LTO and this is a rust-generated object
1831 // file, then we don't need the object file as it's part of the
1832 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1833 // though, so we let that object file slide.
1834 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
1836 && (sess.target.target.options.no_builtins
1837 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
1839 if skip_because_cfg_say_so || skip_because_lto {
1840 archive.remove_file(&f);
1851 // If we're creating a dylib, then we need to include the
1852 // whole of each object in our archive into that artifact. This is
1853 // because a `dylib` can be reused as an intermediate artifact.
1855 // Note, though, that we don't want to include the whole of a
1856 // compiler-builtins crate (e.g., compiler-rt) because it'll get
1857 // repeatedly linked anyway.
1858 if crate_type == config::CrateType::Dylib
1859 && codegen_results.crate_info.compiler_builtins != Some(cnum)
1861 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1863 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1868 // Same thing as above, but for dynamic crates instead of static crates.
1869 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
1870 // Just need to tell the linker about where the library lives and
1872 let parent = cratepath.parent();
1873 if let Some(dir) = parent {
1874 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1876 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1877 cmd.link_rust_dylib(
1878 Symbol::intern(&unlib(&sess.target, filestem)),
1879 parent.unwrap_or(Path::new("")),
1884 // Link in all of our upstream crates' native dependencies. Remember that
1885 // all of these upstream native dependencies are all non-static
1886 // dependencies. We've got two cases then:
1888 // 1. The upstream crate is an rlib. In this case we *must* link in the
1889 // native dependency because the rlib is just an archive.
1891 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1892 // have the dependency present on the system somewhere. Thus, we don't
1893 // gain a whole lot from not linking in the dynamic dependency to this
1896 // The use case for this is a little subtle. In theory the native
1897 // dependencies of a crate are purely an implementation detail of the crate
1898 // itself, but the problem arises with generic and inlined functions. If a
1899 // generic function calls a native function, then the generic function must
1900 // be instantiated in the target crate, meaning that the native symbol must
1901 // also be resolved in the target crate.
1902 fn add_upstream_native_libraries(
1903 cmd: &mut dyn Linker,
1905 codegen_results: &CodegenResults,
1906 crate_type: config::CrateType,
1908 // Be sure to use a topological sorting of crates because there may be
1909 // interdependencies between native libraries. When passing -nodefaultlibs,
1910 // for example, almost all native libraries depend on libc, so we have to
1911 // make sure that's all the way at the right (liblibc is near the base of
1912 // the dependency chain).
1914 // This passes RequireStatic, but the actual requirement doesn't matter,
1915 // we're just getting an ordering of crate numbers, we're not worried about
1917 let (_, data) = codegen_results
1921 .find(|(ty, _)| *ty == crate_type)
1922 .expect("failed to find crate type in dependency format list");
1924 let crates = &codegen_results.crate_info.used_crates_static;
1925 for &(cnum, _) in crates {
1926 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
1927 let name = match lib.name {
1931 if !relevant_lib(sess, &lib) {
1935 NativeLibraryKind::NativeUnknown => cmd.link_dylib(name),
1936 NativeLibraryKind::NativeFramework => cmd.link_framework(name),
1937 NativeLibraryKind::NativeStaticNobundle => {
1938 // Link "static-nobundle" native libs only if the crate they originate from
1939 // is being linked statically to the current crate. If it's linked dynamically
1940 // or is an rlib already included via some other dylib crate, the symbols from
1941 // native libs will have already been included in that dylib.
1942 if data[cnum.as_usize() - 1] == Linkage::Static {
1943 cmd.link_staticlib(name)
1946 // ignore statically included native libraries here as we've
1947 // already included them when we included the rust library
1949 NativeLibraryKind::NativeStatic => {}
1950 NativeLibraryKind::NativeRawDylib => {
1951 // FIXME(#58713): Proper handling for raw dylibs.
1952 bug!("raw_dylib feature not yet implemented");
1959 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1961 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
1966 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
1968 config::Lto::Fat => true,
1969 config::Lto::Thin => {
1970 // If we defer LTO to the linker, we haven't run LTO ourselves, so
1971 // any upstream object files have not been copied yet.
1972 !sess.opts.cg.linker_plugin_lto.enabled()
1974 config::Lto::No | config::Lto::ThinLocal => false,