1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::temp_dir::MaybeTempDir;
3 use rustc_errors::Handler;
4 use rustc_fs_util::fix_windows_verbatim_for_gcc;
5 use rustc_hir::def_id::CrateNum;
6 use rustc_middle::middle::cstore::LibSource;
7 use rustc_middle::middle::dependency_format::Linkage;
8 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo};
9 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest};
10 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
11 use rustc_session::search_paths::PathKind;
12 use rustc_session::utils::NativeLibKind;
13 /// For all the linkers we support, and information they might
14 /// need out of the shared crate context before we get rid of it.
15 use rustc_session::{filesearch, Session};
16 use rustc_span::symbol::Symbol;
17 use rustc_target::abi::Endian;
18 use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
19 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor, SplitDebuginfo};
20 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, SanitizerSet, Target};
22 use super::archive::ArchiveBuilder;
23 use super::command::Command;
24 use super::linker::{self, Linker};
25 use super::rpath::{self, RPathConfig};
27 looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib,
31 use cc::windows_registry;
33 use object::write::Object;
34 use object::{Architecture, BinaryFormat, Endianness, FileFlags, SectionFlags, SectionKind};
35 use tempfile::Builder as TempFileBuilder;
37 use std::ffi::OsString;
38 use std::path::{Path, PathBuf};
39 use std::process::{ExitStatus, Output, Stdio};
40 use std::{ascii, char, env, fmt, fs, io, mem, str};
42 pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
43 if let Err(e) = fs::remove_file(path) {
44 if e.kind() != io::ErrorKind::NotFound {
45 diag_handler.err(&format!("failed to remove {}: {}", path.display(), e));
50 /// Performs the linkage portion of the compilation phase. This will generate all
51 /// of the requested outputs for this compilation session.
52 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
54 codegen_results: &CodegenResults,
55 outputs: &OutputFilenames,
58 let _timer = sess.timer("link_binary");
59 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
60 for &crate_type in sess.crate_types().iter() {
61 // Ignore executable crates if we have -Z no-codegen, as they will error.
62 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
64 && crate_type == CrateType::Executable
69 if invalid_output_for_target(sess, crate_type) {
71 "invalid output type `{:?}` for target os `{}`",
73 sess.opts.target_triple
77 sess.time("link_binary_check_files_are_writeable", || {
78 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
79 check_file_is_writeable(obj, sess);
83 if outputs.outputs.should_link() {
84 let tmpdir = TempFileBuilder::new()
87 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
88 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
89 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
92 let _timer = sess.timer("link_rlib");
93 link_rlib::<B>(sess, codegen_results, RlibFlavor::Normal, &out_filename, &path)
96 CrateType::Staticlib => {
97 link_staticlib::<B>(sess, codegen_results, &out_filename, &path);
109 if sess.opts.json_artifact_notifications {
110 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
115 // Remove the temporary object file and metadata if we aren't saving temps
116 sess.time("link_binary_remove_temps", || {
117 if !sess.opts.cg.save_temps {
118 let remove_temps_from_module = |module: &CompiledModule| {
119 if let Some(ref obj) = module.object {
120 ensure_removed(sess.diagnostic(), obj);
123 if let Some(ref obj) = module.dwarf_object {
124 ensure_removed(sess.diagnostic(), obj);
128 if sess.opts.output_types.should_link() && !preserve_objects_for_their_debuginfo(sess) {
129 for module in &codegen_results.modules {
130 remove_temps_from_module(module);
134 if let Some(ref metadata_module) = codegen_results.metadata_module {
135 remove_temps_from_module(metadata_module);
138 if let Some(ref allocator_module) = codegen_results.allocator_module {
139 remove_temps_from_module(allocator_module);
145 // The third parameter is for env vars, used on windows to set up the
146 // path for MSVC to find its DLLs, and gcc to find its bundled
151 flavor: LinkerFlavor,
152 self_contained: bool,
154 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
156 // If our linker looks like a batch script on Windows then to execute this
157 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
158 // emscripten where the linker is `emcc.bat` and needs to be spawned as
159 // `cmd /c emcc.bat ...`.
161 // This worked historically but is needed manually since #42436 (regression
162 // was tagged as #42791) and some more info can be found on #44443 for
163 // emscripten itself.
164 let mut cmd = match linker.to_str() {
165 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
167 LinkerFlavor::Lld(f) => Command::lld(linker, f),
168 LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
169 Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
171 _ => Command::new(linker),
175 // UWP apps have API restrictions enforced during Store submissions.
176 // To comply with the Windows App Certification Kit,
177 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
178 let t = &sess.target;
179 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
182 if let Some(ref tool) = msvc_tool {
183 let original_path = tool.path();
184 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
185 let arch = match t.arch.as_str() {
186 "x86_64" => Some("x64"),
187 "x86" => Some("x86"),
188 "aarch64" => Some("arm64"),
189 "arm" => Some("arm"),
192 if let Some(ref a) = arch {
193 // FIXME: Move this to `fn linker_with_args`.
194 let mut arg = OsString::from("/LIBPATH:");
195 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
198 warn!("arch is not supported");
201 warn!("MSVC root path lib location not found");
204 warn!("link.exe not found");
208 // The compiler's sysroot often has some bundled tools, so add it to the
209 // PATH for the child.
210 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(self_contained);
211 let mut msvc_changed_path = false;
212 if sess.target.is_like_msvc {
213 if let Some(ref tool) = msvc_tool {
214 cmd.args(tool.args());
215 for &(ref k, ref v) in tool.env() {
217 new_path.extend(env::split_paths(v));
218 msvc_changed_path = true;
226 if !msvc_changed_path {
227 if let Some(path) = env::var_os("PATH") {
228 new_path.extend(env::split_paths(&path));
231 cmd.env("PATH", env::join_paths(new_path).unwrap());
236 pub fn each_linked_rlib(
238 f: &mut dyn FnMut(CrateNum, &Path),
239 ) -> Result<(), String> {
240 let crates = info.used_crates_static.iter();
242 for (ty, list) in info.dependency_formats.iter() {
244 CrateType::Executable
245 | CrateType::Staticlib
247 | CrateType::ProcMacro => {
254 let fmts = match fmts {
256 None => return Err("could not find formats for rlibs".to_string()),
258 for &(cnum, ref path) in crates {
259 match fmts.get(cnum.as_usize() - 1) {
260 Some(&Linkage::NotLinked | &Linkage::IncludedFromDylib) => continue,
262 None => return Err("could not find formats for rlibs".to_string()),
264 let name = &info.crate_name[&cnum];
265 let path = match *path {
266 LibSource::Some(ref p) => p,
267 LibSource::MetadataOnly => {
269 "could not find rlib for: `{}`, found rmeta (metadata) file",
273 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
280 /// We use a temp directory here to avoid races between concurrent rustc processes,
281 /// such as builds in the same directory using the same filename for metadata while
282 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
283 /// directory being searched for `extern crate` (observing an incomplete file).
284 /// The returned path is the temporary file containing the complete metadata.
285 pub fn emit_metadata(sess: &Session, metadata: &[u8], tmpdir: &MaybeTempDir) -> PathBuf {
286 let out_filename = tmpdir.as_ref().join(METADATA_FILENAME);
287 let result = fs::write(&out_filename, metadata);
289 if let Err(e) = result {
290 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
296 /// Create an 'rlib'.
298 /// An rlib in its current incarnation is essentially a renamed .a file. The rlib primarily contains
299 /// the object file of the crate, but it also contains all of the object files from native
300 /// libraries. This is done by unzipping native libraries and inserting all of the contents into
302 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
304 codegen_results: &CodegenResults,
307 tmpdir: &MaybeTempDir,
309 info!("preparing rlib to {:?}", out_filename);
310 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
312 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
316 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
317 // we may not be configured to actually include a static library if we're
318 // adding it here. That's because later when we consume this rlib we'll
319 // decide whether we actually needed the static library or not.
321 // To do this "correctly" we'd need to keep track of which libraries added
322 // which object files to the archive. We don't do that here, however. The
323 // #[link(cfg(..))] feature is unstable, though, and only intended to get
324 // liblibc working. In that sense the check below just indicates that if
325 // there are any libraries we want to omit object files for at link time we
326 // just exclude all custom object files.
328 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
329 // feature then we'll need to figure out how to record what objects were
330 // loaded from the libraries found here and then encode that into the
331 // metadata of the rlib we're generating somehow.
332 for lib in codegen_results.crate_info.used_libraries.iter() {
334 NativeLibKind::Static { bundle: None | Some(true), .. } => {}
335 NativeLibKind::Static { bundle: Some(false), .. }
336 | NativeLibKind::Dylib { .. }
337 | NativeLibKind::Framework { .. }
338 | NativeLibKind::RawDylib
339 | NativeLibKind::Unspecified => continue,
341 if let Some(name) = lib.name {
342 ab.add_native_library(name, lib.verbatim.unwrap_or(false));
346 // After adding all files to the archive, we need to update the
347 // symbol table of the archive.
350 // Note that it is important that we add all of our non-object "magical
351 // files" *after* all of the object files in the archive. The reason for
352 // this is as follows:
354 // * When performing LTO, this archive will be modified to remove
355 // objects from above. The reason for this is described below.
357 // * When the system linker looks at an archive, it will attempt to
358 // determine the architecture of the archive in order to see whether its
361 // The algorithm for this detection is: iterate over the files in the
362 // archive. Skip magical SYMDEF names. Interpret the first file as an
363 // object file. Read architecture from the object file.
365 // * As one can probably see, if "metadata" and "foo.bc" were placed
366 // before all of the objects, then the architecture of this archive would
367 // not be correctly inferred once 'foo.o' is removed.
369 // Basically, all this means is that this code should not move above the
372 RlibFlavor::Normal => {
373 // metadata in rlib files is wrapped in a "dummy" object file for
374 // the target platform so the rlib can be processed entirely by
375 // normal linkers for the platform.
376 let metadata = create_metadata_file(sess, &codegen_results.metadata.raw_data);
377 ab.add_file(&emit_metadata(sess, &metadata, tmpdir));
379 // After adding all files to the archive, we need to update the
380 // symbol table of the archive. This currently dies on macOS (see
381 // #11162), and isn't necessary there anyway
382 if !sess.target.is_like_osx {
387 RlibFlavor::StaticlibBase => {
388 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
389 if let Some(obj) = obj {
396 // For rlibs we "pack" rustc metadata into a dummy object file. When rustc
397 // creates a dylib crate type it will pass `--whole-archive` (or the
398 // platform equivalent) to include all object files from an rlib into the
399 // final dylib itself. This causes linkers to iterate and try to include all
400 // files located in an archive, so if metadata is stored in an archive then
401 // it needs to be of a form that the linker will be able to process.
403 // Note, though, that we don't actually want this metadata to show up in any
404 // final output of the compiler. Instead this is purely for rustc's own
405 // metadata tracking purposes.
407 // With the above in mind, each "flavor" of object format gets special
408 // handling here depending on the target:
410 // * MachO - macos-like targets will insert the metadata into a section that
411 // is sort of fake dwarf debug info. Inspecting the source of the macos
412 // linker this causes these sections to be skipped automatically because
413 // it's not in an allowlist of otherwise well known dwarf section names to
414 // go into the final artifact.
416 // * WebAssembly - we actually don't have any container format for this
417 // target. WebAssembly doesn't support the `dylib` crate type anyway so
418 // there's no need for us to support this at this time. Consequently the
419 // metadata bytes are simply stored as-is into an rlib.
421 // * COFF - Windows-like targets create an object with a section that has
422 // the `IMAGE_SCN_LNK_REMOVE` flag set which ensures that if the linker
423 // ever sees the section it doesn't process it and it's removed.
425 // * ELF - All other targets are similar to Windows in that there's a
426 // `SHF_EXCLUDE` flag we can set on sections in an object file to get
427 // automatically removed from the final output.
429 // Note that this metdata format is kept in sync with
430 // `rustc_codegen_ssa/src/back/metadata.rs`.
431 fn create_metadata_file(sess: &Session, metadata: &[u8]) -> Vec<u8> {
432 let endianness = match sess.target.options.endian {
433 Endian::Little => Endianness::Little,
434 Endian::Big => Endianness::Big,
436 let architecture = match &sess.target.arch[..] {
437 "arm" => Architecture::Arm,
438 "aarch64" => Architecture::Aarch64,
439 "x86" => Architecture::I386,
440 "s390x" => Architecture::S390x,
441 "mips" => Architecture::Mips,
442 "mips64" => Architecture::Mips64,
444 if sess.target.pointer_width == 32 {
445 Architecture::X86_64_X32
450 "powerpc" => Architecture::PowerPc,
451 "powerpc64" => Architecture::PowerPc64,
452 "riscv32" => Architecture::Riscv32,
453 "riscv64" => Architecture::Riscv64,
454 "sparc64" => Architecture::Sparc64,
456 // This is used to handle all "other" targets. This includes targets
457 // in two categories:
459 // * Some targets don't have support in the `object` crate just yet
460 // to write an object file. These targets are likely to get filled
463 // * Targets like WebAssembly don't support dylibs, so the purpose
464 // of putting metadata in object files, to support linking rlibs
465 // into dylibs, is moot.
467 // In both of these cases it means that linking into dylibs will
468 // not be supported by rustc. This doesn't matter for targets like
469 // WebAssembly and for targets not supported by the `object` crate
470 // yet it means that work will need to be done in the `object` crate
471 // to add a case above.
472 _ => return metadata.to_vec(),
475 if sess.target.is_like_osx {
476 let mut file = Object::new(BinaryFormat::MachO, architecture, endianness);
479 file.add_section(b"__DWARF".to_vec(), b".rmeta".to_vec(), SectionKind::Debug);
480 file.append_section_data(section, metadata, 1);
481 file.write().unwrap()
482 } else if sess.target.is_like_windows {
483 const IMAGE_SCN_LNK_REMOVE: u32 = 0;
484 let mut file = Object::new(BinaryFormat::Coff, architecture, endianness);
486 let section = file.add_section(Vec::new(), b".rmeta".to_vec(), SectionKind::Debug);
487 file.section_mut(section).flags =
488 SectionFlags::Coff { characteristics: IMAGE_SCN_LNK_REMOVE };
489 file.append_section_data(section, metadata, 1);
490 file.write().unwrap()
492 const SHF_EXCLUDE: u64 = 0x80000000;
493 let mut file = Object::new(BinaryFormat::Elf, architecture, endianness);
495 match &sess.target.arch[..] {
496 // copied from `mipsel-linux-gnu-gcc foo.c -c` and
497 // inspecting the resulting `e_flags` field.
499 let e_flags = elf::EF_MIPS_ARCH_32R2 | elf::EF_MIPS_CPIC | elf::EF_MIPS_PIC;
500 file.flags = FileFlags::Elf { e_flags };
502 // copied from `mips64el-linux-gnuabi64-gcc foo.c -c`
504 let e_flags = elf::EF_MIPS_ARCH_64R2 | elf::EF_MIPS_CPIC | elf::EF_MIPS_PIC;
505 file.flags = FileFlags::Elf { e_flags };
508 // copied from `riscv64-linux-gnu-gcc foo.c -c`, note though
509 // that the `+d` target feature represents whether the double
510 // float abi is enabled.
511 "riscv64" if sess.target.options.features.contains("+d") => {
512 let e_flags = elf::EF_RISCV_RVC | elf::EF_RISCV_FLOAT_ABI_DOUBLE;
513 file.flags = FileFlags::Elf { e_flags };
519 let section = file.add_section(Vec::new(), b".rmeta".to_vec(), SectionKind::Debug);
520 file.section_mut(section).flags = SectionFlags::Elf { sh_flags: SHF_EXCLUDE };
521 file.append_section_data(section, metadata, 1);
522 file.write().unwrap()
527 /// Create a static archive.
529 /// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
530 /// crates' objects into the archive. This will slurp in all of the native libraries of upstream
531 /// dependencies as well.
533 /// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
534 /// library dependencies that they're not linked in.
536 /// There's no need to include metadata in a static archive, so ensure to not link in the metadata
537 /// object file (and also don't prepare the archive with a metadata file).
538 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
540 codegen_results: &CodegenResults,
542 tempdir: &MaybeTempDir,
545 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
546 let mut all_native_libs = vec![];
548 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
549 let name = &codegen_results.crate_info.crate_name[&cnum];
550 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
552 // Here when we include the rlib into our staticlib we need to make a
553 // decision whether to include the extra object files along the way.
554 // These extra object files come from statically included native
555 // libraries, but they may be cfg'd away with #[link(cfg(..))].
557 // This unstable feature, though, only needs liblibc to work. The only
558 // use case there is where musl is statically included in liblibc.rlib,
559 // so if we don't want the included version we just need to skip it. As
560 // a result the logic here is that if *any* linked library is cfg'd away
561 // we just skip all object files.
563 // Clearly this is not sufficient for a general purpose feature, and
564 // we'd want to read from the library's metadata to determine which
565 // object files come from where and selectively skip them.
566 let skip_object_files = native_libs.iter().any(|lib| {
567 matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
568 && !relevant_lib(sess, lib)
573 are_upstream_rust_objects_already_included(sess)
574 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
579 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
581 if let Err(e) = res {
588 if !all_native_libs.is_empty() {
589 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
590 print_native_static_libs(sess, &all_native_libs);
595 fn escape_stdout_stderr_string(s: &[u8]) -> String {
596 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
597 let mut x = "Non-UTF-8 output: ".to_string();
598 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
603 const LLVM_DWP_EXECUTABLE: &'static str = "rust-llvm-dwp";
605 /// Invoke `llvm-dwp` (shipped alongside rustc) to link `dwo` files from Split DWARF into a `dwp`
607 fn link_dwarf_object<'a>(sess: &'a Session, executable_out_filename: &Path) {
608 info!("preparing dwp to {}.dwp", executable_out_filename.to_str().unwrap());
610 let dwp_out_filename = executable_out_filename.with_extension("dwp");
611 let mut cmd = Command::new(LLVM_DWP_EXECUTABLE);
613 cmd.arg(executable_out_filename);
615 cmd.arg(&dwp_out_filename);
617 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false);
618 if let Some(path) = env::var_os("PATH") {
619 new_path.extend(env::split_paths(&path));
621 let new_path = env::join_paths(new_path).unwrap();
622 cmd.env("PATH", new_path);
625 match sess.time("run_dwp", || cmd.output()) {
626 Ok(prog) if !prog.status.success() => {
627 sess.struct_err(&format!(
628 "linking dwarf objects with `{}` failed: {}",
629 LLVM_DWP_EXECUTABLE, prog.status
631 .note(&format!("{:?}", &cmd))
632 .note(&escape_stdout_stderr_string(&prog.stdout))
633 .note(&escape_stdout_stderr_string(&prog.stderr))
635 info!("linker stderr:\n{}", escape_stdout_stderr_string(&prog.stderr));
636 info!("linker stdout:\n{}", escape_stdout_stderr_string(&prog.stdout));
640 let dwp_not_found = e.kind() == io::ErrorKind::NotFound;
641 let mut err = if dwp_not_found {
642 sess.struct_err(&format!("linker `{}` not found", LLVM_DWP_EXECUTABLE))
644 sess.struct_err(&format!("could not exec the linker `{}`", LLVM_DWP_EXECUTABLE))
647 err.note(&e.to_string());
650 err.note(&format!("{:?}", &cmd));
658 /// Create a dynamic library or executable.
660 /// This will invoke the system linker/cc to create the resulting file. This links to all upstream
662 fn link_natively<'a, B: ArchiveBuilder<'a>>(
664 crate_type: CrateType,
666 codegen_results: &CodegenResults,
669 info!("preparing {:?} to {:?}", crate_type, out_filename);
670 let (linker_path, flavor) = linker_and_flavor(sess);
671 let mut cmd = linker_with_args::<B>(
681 linker::disable_localization(&mut cmd);
683 for &(ref k, ref v) in &sess.target.link_env {
686 for k in &sess.target.link_env_remove {
690 if sess.opts.debugging_opts.print_link_args {
691 println!("{:?}", &cmd);
694 // May have not found libraries in the right formats.
695 sess.abort_if_errors();
697 // Invoke the system linker
699 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
704 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
705 let output = match prog {
706 Ok(ref output) => output,
709 if output.status.success() {
712 let mut out = output.stderr.clone();
713 out.extend(&output.stdout);
714 let out = String::from_utf8_lossy(&out);
716 // Check to see if the link failed with "unrecognized command line option:
717 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
718 // reperform the link step without the -no-pie option. This is safe because
719 // if the linker doesn't support -no-pie then it should not default to
720 // linking executables as pie. Different versions of gcc seem to use
721 // different quotes in the error message so don't check for them.
722 if sess.target.linker_is_gnu
723 && flavor != LinkerFlavor::Ld
724 && (out.contains("unrecognized command line option")
725 || out.contains("unknown argument"))
726 && out.contains("-no-pie")
727 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
729 info!("linker output: {:?}", out);
730 warn!("Linker does not support -no-pie command line option. Retrying without.");
731 for arg in cmd.take_args() {
732 if arg.to_string_lossy() != "-no-pie" {
740 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
741 // Fallback from '-static-pie' to '-static' in that case.
742 if sess.target.linker_is_gnu
743 && flavor != LinkerFlavor::Ld
744 && (out.contains("unrecognized command line option")
745 || out.contains("unknown argument"))
746 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
747 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
749 info!("linker output: {:?}", out);
751 "Linker does not support -static-pie command line option. Retrying with -static instead."
753 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
754 let self_contained = crt_objects_fallback(sess, crate_type);
755 let opts = &sess.target;
756 let pre_objects = if self_contained {
757 &opts.pre_link_objects_fallback
759 &opts.pre_link_objects
761 let post_objects = if self_contained {
762 &opts.post_link_objects_fallback
764 &opts.post_link_objects
766 let get_objects = |objects: &CrtObjects, kind| {
772 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
775 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
776 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
777 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
778 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
779 // Assume that we know insertion positions for the replacement arguments from replaced
780 // arguments, which is true for all supported targets.
781 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
782 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
783 for arg in cmd.take_args() {
784 if arg.to_string_lossy() == "-static-pie" {
785 // Replace the output kind.
787 } else if pre_objects_static_pie.contains(&arg) {
788 // Replace the pre-link objects (replace the first and remove the rest).
789 cmd.args(mem::take(&mut pre_objects_static));
790 } else if post_objects_static_pie.contains(&arg) {
791 // Replace the post-link objects (replace the first and remove the rest).
792 cmd.args(mem::take(&mut post_objects_static));
801 // Here's a terribly awful hack that really shouldn't be present in any
802 // compiler. Here an environment variable is supported to automatically
803 // retry the linker invocation if the linker looks like it segfaulted.
805 // Gee that seems odd, normally segfaults are things we want to know
806 // about! Unfortunately though in rust-lang/rust#38878 we're
807 // experiencing the linker segfaulting on Travis quite a bit which is
808 // causing quite a bit of pain to land PRs when they spuriously fail
809 // due to a segfault.
811 // The issue #38878 has some more debugging information on it as well,
812 // but this unfortunately looks like it's just a race condition in
813 // macOS's linker with some thread pool working in the background. It
814 // seems that no one currently knows a fix for this so in the meantime
815 // we're left with this...
816 if !retry_on_segfault || i > 3 {
819 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
820 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
821 if out.contains(msg_segv) || out.contains(msg_bus) {
823 "looks like the linker segfaulted when we tried to call it, \
824 automatically retrying again. cmd = {:?}, out = {}.",
830 if is_illegal_instruction(&output.status) {
832 "looks like the linker hit an illegal instruction when we \
833 tried to call it, automatically retrying again. cmd = {:?}, ]\
834 out = {}, status = {}.",
835 cmd, out, output.status,
841 fn is_illegal_instruction(status: &ExitStatus) -> bool {
842 use std::os::unix::prelude::*;
843 status.signal() == Some(libc::SIGILL)
847 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
852 fn escape_string(s: &[u8]) -> String {
853 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
854 let mut x = "Non-UTF-8 output: ".to_string();
855 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
862 if !prog.status.success() {
863 let mut output = prog.stderr.clone();
864 output.extend_from_slice(&prog.stdout);
865 sess.struct_err(&format!(
866 "linking with `{}` failed: {}",
867 linker_path.display(),
870 .note(&format!("{:?}", &cmd))
871 .note(&escape_stdout_stderr_string(&output))
874 // If MSVC's `link.exe` was expected but the return code
875 // is not a Microsoft LNK error then suggest a way to fix or
876 // install the Visual Studio build tools.
877 if let Some(code) = prog.status.code() {
878 if sess.target.is_like_msvc
879 && flavor == LinkerFlavor::Msvc
880 // Respect the command line override
881 && sess.opts.cg.linker.is_none()
882 // Match exactly "link.exe"
883 && linker_path.to_str() == Some("link.exe")
884 // All Microsoft `link.exe` linking error codes are
885 // four digit numbers in the range 1000 to 9999 inclusive
886 && (code < 1000 || code > 9999)
888 let is_vs_installed = windows_registry::find_vs_version().is_ok();
889 let has_linker = windows_registry::find_tool(
890 &sess.opts.target_triple.triple(),
895 sess.note_without_error("`link.exe` returned an unexpected error");
896 if is_vs_installed && has_linker {
897 // the linker is broken
898 sess.note_without_error(
899 "the Visual Studio build tools may need to be repaired \
900 using the Visual Studio installer",
902 sess.note_without_error(
903 "or a necessary component may be missing from the \
904 \"C++ build tools\" workload",
906 } else if is_vs_installed {
907 // the linker is not installed
908 sess.note_without_error(
909 "in the Visual Studio installer, ensure the \
910 \"C++ build tools\" workload is selected",
913 // visual studio is not installed
914 sess.note_without_error(
915 "you may need to install Visual Studio build tools with the \
916 \"C++ build tools\" workload",
922 sess.abort_if_errors();
924 info!("linker stderr:\n{}", escape_stdout_stderr_string(&prog.stderr));
925 info!("linker stdout:\n{}", escape_stdout_stderr_string(&prog.stdout));
928 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
930 let mut linker_error = {
931 if linker_not_found {
932 sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
934 sess.struct_err(&format!(
935 "could not exec the linker `{}`",
936 linker_path.display()
941 linker_error.note(&e.to_string());
943 if !linker_not_found {
944 linker_error.note(&format!("{:?}", &cmd));
949 if sess.target.is_like_msvc && linker_not_found {
950 sess.note_without_error(
951 "the msvc targets depend on the msvc linker \
952 but `link.exe` was not found",
954 sess.note_without_error(
955 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
956 was installed with the Visual C++ option",
959 sess.abort_if_errors();
963 match sess.split_debuginfo() {
964 // If split debug information is disabled or located in individual files
965 // there's nothing to do here.
966 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
968 // If packed split-debuginfo is requested, but the final compilation
969 // doesn't actually have any debug information, then we skip this step.
970 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
972 // On macOS the external `dsymutil` tool is used to create the packed
973 // debug information. Note that this will read debug information from
974 // the objects on the filesystem which we'll clean up later.
975 SplitDebuginfo::Packed if sess.target.is_like_osx => {
976 let prog = Command::new("dsymutil").arg(out_filename).output();
979 if !prog.status.success() {
980 let mut output = prog.stderr.clone();
981 output.extend_from_slice(&prog.stdout);
982 sess.struct_warn(&format!(
983 "processing debug info with `dsymutil` failed: {}",
986 .note(&escape_string(&output))
990 Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
994 // On MSVC packed debug information is produced by the linker itself so
995 // there's no need to do anything else here.
996 SplitDebuginfo::Packed if sess.target.is_like_msvc => {}
998 // ... and otherwise we're processing a `*.dwp` packed dwarf file.
999 SplitDebuginfo::Packed => link_dwarf_object(sess, &out_filename),
1003 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
1004 // On macOS the runtimes are distributed as dylibs which should be linked to
1005 // both executables and dynamic shared objects. Everywhere else the runtimes
1006 // are currently distributed as static liraries which should be linked to
1007 // executables only.
1008 let needs_runtime = match crate_type {
1009 CrateType::Executable => true,
1010 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
1011 CrateType::Rlib | CrateType::Staticlib => false,
1018 let sanitizer = sess.opts.debugging_opts.sanitizer;
1019 if sanitizer.contains(SanitizerSet::ADDRESS) {
1020 link_sanitizer_runtime(sess, linker, "asan");
1022 if sanitizer.contains(SanitizerSet::LEAK) {
1023 link_sanitizer_runtime(sess, linker, "lsan");
1025 if sanitizer.contains(SanitizerSet::MEMORY) {
1026 link_sanitizer_runtime(sess, linker, "msan");
1028 if sanitizer.contains(SanitizerSet::THREAD) {
1029 link_sanitizer_runtime(sess, linker, "tsan");
1031 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1032 link_sanitizer_runtime(sess, linker, "hwasan");
1036 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
1037 fn find_sanitizer_runtime(sess: &Session, filename: &String) -> PathBuf {
1039 filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
1040 let path = session_tlib.join(&filename);
1042 return session_tlib;
1044 let default_sysroot = filesearch::get_or_default_sysroot();
1045 let default_tlib = filesearch::make_target_lib_path(
1047 sess.opts.target_triple.triple(),
1049 return default_tlib;
1053 let channel = option_env!("CFG_RELEASE_CHANNEL")
1054 .map(|channel| format!("-{}", channel))
1055 .unwrap_or_default();
1057 if sess.target.is_like_osx {
1058 // On Apple platforms, the sanitizer is always built as a dylib, and
1059 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1060 // rpath to the library as well (the rpath should be absolute, see
1061 // PR #41352 for details).
1062 let filename = format!("rustc{}_rt.{}", channel, name);
1063 let path = find_sanitizer_runtime(&sess, &filename);
1064 let rpath = path.to_str().expect("non-utf8 component in path");
1065 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
1066 linker.link_dylib(Symbol::intern(&filename), false, true);
1068 let filename = format!("librustc{}_rt.{}.a", channel, name);
1069 let path = find_sanitizer_runtime(&sess, &filename).join(&filename);
1070 linker.link_whole_rlib(&path);
1074 /// Returns a boolean indicating whether the specified crate should be ignored
1077 /// Crates ignored during LTO are not lumped together in the "massive object
1078 /// file" that we create and are linked in their normal rlib states. See
1079 /// comments below for what crates do not participate in LTO.
1081 /// It's unusual for a crate to not participate in LTO. Typically only
1082 /// compiler-specific and unstable crates have a reason to not participate in
1084 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1085 // If our target enables builtin function lowering in LLVM then the
1086 // crates providing these functions don't participate in LTO (e.g.
1087 // no_builtins or compiler builtins crates).
1088 !sess.target.no_builtins
1089 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1092 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1095 linker: Option<PathBuf>,
1096 flavor: Option<LinkerFlavor>,
1097 ) -> Option<(PathBuf, LinkerFlavor)> {
1098 match (linker, flavor) {
1099 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1100 // only the linker flavor is known; use the default linker for the selected flavor
1101 (None, Some(flavor)) => Some((
1102 PathBuf::from(match flavor {
1103 LinkerFlavor::Em => {
1110 LinkerFlavor::Gcc => {
1111 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1112 // On historical Solaris systems, "cc" may have
1113 // been Sun Studio, which is not flag-compatible
1114 // with "gcc". This history casts a long shadow,
1115 // and many modern illumos distributions today
1116 // ship GCC as "gcc" without also making it
1117 // available as "cc".
1123 LinkerFlavor::Ld => "ld",
1124 LinkerFlavor::Msvc => "link.exe",
1125 LinkerFlavor::Lld(_) => "lld",
1126 LinkerFlavor::PtxLinker => "rust-ptx-linker",
1130 (Some(linker), None) => {
1131 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1132 sess.fatal("couldn't extract file stem from specified linker")
1135 let flavor = if stem == "emcc" {
1137 } else if stem == "gcc"
1138 || stem.ends_with("-gcc")
1140 || stem.ends_with("-clang")
1143 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
1145 } else if stem == "link" || stem == "lld-link" {
1147 } else if stem == "lld" || stem == "rust-lld" {
1148 LinkerFlavor::Lld(sess.target.lld_flavor)
1150 // fall back to the value in the target spec
1151 sess.target.linker_flavor
1154 Some((linker, flavor))
1156 (None, None) => None,
1160 // linker and linker flavor specified via command line have precedence over what the target
1161 // specification specifies
1162 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
1166 if let Some(ret) = infer_from(
1168 sess.target.linker.clone().map(PathBuf::from),
1169 Some(sess.target.linker_flavor),
1174 bug!("Not enough information provided to determine how to invoke the linker");
1177 /// Returns a boolean indicating whether we should preserve the object files on
1178 /// the filesystem for their debug information. This is often useful with
1179 /// split-dwarf like schemes.
1180 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
1181 // If the objects don't have debuginfo there's nothing to preserve.
1182 if sess.opts.debuginfo == config::DebugInfo::None {
1186 // If we're only producing artifacts that are archives, no need to preserve
1187 // the objects as they're losslessly contained inside the archives.
1189 sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
1194 // "unpacked" split debuginfo means that we leave object files as the
1195 // debuginfo is found in the original object files themselves
1196 sess.split_debuginfo() == SplitDebuginfo::Unpacked
1199 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
1200 sess.target_filesearch(PathKind::Native).search_path_dirs()
1208 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
1209 let lib_args: Vec<_> = all_native_libs
1211 .filter(|l| relevant_lib(sess, l))
1213 let name = lib.name?;
1215 NativeLibKind::Static { bundle: Some(false), .. }
1216 | NativeLibKind::Dylib { .. }
1217 | NativeLibKind::Unspecified => {
1218 let verbatim = lib.verbatim.unwrap_or(false);
1219 if sess.target.is_like_msvc {
1220 Some(format!("{}{}", name, if verbatim { "" } else { ".lib" }))
1221 } else if sess.target.linker_is_gnu {
1222 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1224 Some(format!("-l{}", name))
1227 NativeLibKind::Framework { .. } => {
1228 // ld-only syntax, since there are no frameworks in MSVC
1229 Some(format!("-framework {}", name))
1231 // These are included, no need to print them
1232 NativeLibKind::Static { bundle: None | Some(true), .. }
1233 | NativeLibKind::RawDylib => None,
1237 if !lib_args.is_empty() {
1238 sess.note_without_error(
1239 "Link against the following native artifacts when linking \
1240 against this static library. The order and any duplication \
1241 can be significant on some platforms.",
1243 // Prefix for greppability
1244 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1248 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1249 let fs = sess.target_filesearch(PathKind::Native);
1250 let file_path = fs.get_lib_path().join(name);
1251 if file_path.exists() {
1254 // Special directory with objects used only in self-contained linkage mode
1256 let file_path = fs.get_self_contained_lib_path().join(name);
1257 if file_path.exists() {
1261 for search_path in fs.search_paths() {
1262 let file_path = search_path.dir.join(name);
1263 if file_path.exists() {
1273 out_filename: &Path,
1275 ) -> io::Result<Output> {
1276 // When attempting to spawn the linker we run a risk of blowing out the
1277 // size limits for spawning a new process with respect to the arguments
1278 // we pass on the command line.
1280 // Here we attempt to handle errors from the OS saying "your list of
1281 // arguments is too big" by reinvoking the linker again with an `@`-file
1282 // that contains all the arguments. The theory is that this is then
1283 // accepted on all linkers and the linker will read all its options out of
1284 // there instead of looking at the command line.
1285 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1286 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1288 let output = child.wait_with_output();
1289 flush_linked_file(&output, out_filename)?;
1292 Err(ref e) if command_line_too_big(e) => {
1293 info!("command line to linker was too big: {}", e);
1295 Err(e) => return Err(e),
1299 info!("falling back to passing arguments to linker via an @-file");
1300 let mut cmd2 = cmd.clone();
1301 let mut args = String::new();
1302 for arg in cmd2.take_args() {
1304 &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1309 let file = tmpdir.join("linker-arguments");
1310 let bytes = if sess.target.is_like_msvc {
1311 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1312 // start the stream with a UTF-16 BOM
1313 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1314 // encode in little endian
1316 out.push((c >> 8) as u8);
1322 fs::write(&file, &bytes)?;
1323 cmd2.arg(format!("@{}", file.display()));
1324 info!("invoking linker {:?}", cmd2);
1325 let output = cmd2.output();
1326 flush_linked_file(&output, out_filename)?;
1329 #[cfg(not(windows))]
1330 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1335 fn flush_linked_file(
1336 command_output: &io::Result<Output>,
1337 out_filename: &Path,
1338 ) -> io::Result<()> {
1339 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1340 // even long after process exit, causing nasty, non-reproducible output bugs.
1342 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1344 // А full writeup of the original Chrome bug can be found at
1345 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1347 if let &Ok(ref out) = command_output {
1348 if out.status.success() {
1349 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1359 fn command_line_too_big(err: &io::Error) -> bool {
1360 err.raw_os_error() == Some(::libc::E2BIG)
1364 fn command_line_too_big(err: &io::Error) -> bool {
1365 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1366 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1369 #[cfg(not(any(unix, windows)))]
1370 fn command_line_too_big(_: &io::Error) -> bool {
1379 impl<'a> fmt::Display for Escape<'a> {
1380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1381 if self.is_like_msvc {
1382 // This is "documented" at
1383 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1385 // Unfortunately there's not a great specification of the
1386 // syntax I could find online (at least) but some local
1387 // testing showed that this seemed sufficient-ish to catch
1388 // at least a few edge cases.
1390 for c in self.arg.chars() {
1392 '"' => write!(f, "\\{}", c)?,
1393 c => write!(f, "{}", c)?,
1398 // This is documented at https://linux.die.net/man/1/ld, namely:
1400 // > Options in file are separated by whitespace. A whitespace
1401 // > character may be included in an option by surrounding the
1402 // > entire option in either single or double quotes. Any
1403 // > character (including a backslash) may be included by
1404 // > prefixing the character to be included with a backslash.
1406 // We put an argument on each line, so all we need to do is
1407 // ensure the line is interpreted as one whole argument.
1408 for c in self.arg.chars() {
1410 '\\' | ' ' => write!(f, "\\{}", c)?,
1411 c => write!(f, "{}", c)?,
1420 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1421 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1422 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1423 (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1424 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1425 (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1426 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1427 (_, true, _) => LinkOutputKind::StaticDylib,
1428 (_, false, _) => LinkOutputKind::DynamicDylib,
1431 // Adjust the output kind to target capabilities.
1432 let opts = &sess.target;
1433 let pic_exe_supported = opts.position_independent_executables;
1434 let static_pic_exe_supported = opts.static_position_independent_executables;
1435 let static_dylib_supported = opts.crt_static_allows_dylibs;
1437 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1438 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1439 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1444 // Returns true if linker is located within sysroot
1445 fn detect_self_contained_mingw(sess: &Session) -> bool {
1446 let (linker, _) = linker_and_flavor(&sess);
1447 // Assume `-C linker=rust-lld` as self-contained mode
1448 if linker == Path::new("rust-lld") {
1451 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1452 linker.with_extension("exe")
1456 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1457 let full_path = dir.join(&linker_with_extension);
1458 // If linker comes from sysroot assume self-contained mode
1459 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1466 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1467 /// We only provide such support for a very limited number of targets.
1468 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1469 if let Some(self_contained) = sess.opts.cg.link_self_contained {
1470 return self_contained;
1473 match sess.target.crt_objects_fallback {
1474 // FIXME: Find a better heuristic for "native musl toolchain is available",
1475 // based on host and linker path, for example.
1476 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1477 Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1478 Some(CrtObjectsFallback::Mingw) => {
1479 sess.host == sess.target
1480 && sess.target.vendor != "uwp"
1481 && detect_self_contained_mingw(&sess)
1483 // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1484 Some(CrtObjectsFallback::Wasm) => true,
1489 /// Add pre-link object files defined by the target spec.
1490 fn add_pre_link_objects(
1491 cmd: &mut dyn Linker,
1493 link_output_kind: LinkOutputKind,
1494 self_contained: bool,
1496 let opts = &sess.target;
1498 if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1499 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1500 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1504 /// Add post-link object files defined by the target spec.
1505 fn add_post_link_objects(
1506 cmd: &mut dyn Linker,
1508 link_output_kind: LinkOutputKind,
1509 self_contained: bool,
1511 let opts = &sess.target;
1513 if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1514 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1515 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1519 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1520 /// FIXME: Determine where exactly these args need to be inserted.
1521 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1522 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1525 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1528 /// Add a link script embedded in the target, if applicable.
1529 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1530 match (crate_type, &sess.target.link_script) {
1531 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1532 if !sess.target.linker_is_gnu {
1533 sess.fatal("can only use link script when linking with GNU-like linker");
1536 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1538 let path = tmpdir.join(file_name);
1539 if let Err(e) = fs::write(&path, script) {
1540 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1543 cmd.arg("--script");
1550 /// Add arbitrary "user defined" args defined from command line.
1551 /// FIXME: Determine where exactly these args need to be inserted.
1552 fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1553 cmd.args(&sess.opts.cg.link_args);
1556 /// Add arbitrary "late link" args defined by the target spec.
1557 /// FIXME: Determine where exactly these args need to be inserted.
1558 fn add_late_link_args(
1559 cmd: &mut dyn Linker,
1561 flavor: LinkerFlavor,
1562 crate_type: CrateType,
1563 codegen_results: &CodegenResults,
1565 let any_dynamic_crate = crate_type == CrateType::Dylib
1566 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1567 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1569 if any_dynamic_crate {
1570 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1574 if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1578 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1583 /// Add arbitrary "post-link" args defined by the target spec.
1584 /// FIXME: Determine where exactly these args need to be inserted.
1585 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1586 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1591 /// Add object files containing code from the current crate.
1592 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1593 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1594 cmd.add_object(obj);
1598 /// Add object files for allocator code linked once for the whole crate tree.
1599 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1600 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1601 cmd.add_object(obj);
1605 /// Add object files containing metadata for the current crate.
1606 fn add_local_crate_metadata_objects(
1607 cmd: &mut dyn Linker,
1608 crate_type: CrateType,
1609 codegen_results: &CodegenResults,
1611 // When linking a dynamic library, we put the metadata into a section of the
1612 // executable. This metadata is in a separate object file from the main
1613 // object file, so we link that in here.
1614 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1615 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1617 cmd.add_object(obj);
1622 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1623 /// all its dependency crates.
1624 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1625 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1626 cmd: &mut dyn Linker,
1628 crate_type: CrateType,
1629 codegen_results: &CodegenResults,
1632 // Take careful note of the ordering of the arguments we pass to the linker
1633 // here. Linkers will assume that things on the left depend on things to the
1634 // right. Things on the right cannot depend on things on the left. This is
1635 // all formally implemented in terms of resolving symbols (libs on the right
1636 // resolve unknown symbols of libs on the left, but not vice versa).
1638 // For this reason, we have organized the arguments we pass to the linker as
1641 // 1. The local object that LLVM just generated
1642 // 2. Local native libraries
1643 // 3. Upstream rust libraries
1644 // 4. Upstream native libraries
1646 // The rationale behind this ordering is that those items lower down in the
1647 // list can't depend on items higher up in the list. For example nothing can
1648 // depend on what we just generated (e.g., that'd be a circular dependency).
1649 // Upstream rust libraries are not allowed to depend on our local native
1650 // libraries as that would violate the structure of the DAG, in that
1651 // scenario they are required to link to them as well in a shared fashion.
1653 // Note that upstream rust libraries may contain native dependencies as
1654 // well, but they also can't depend on what we just started to add to the
1655 // link line. And finally upstream native libraries can't depend on anything
1656 // in this DAG so far because they're only dylibs and dylibs can only depend
1657 // on other dylibs (e.g., other native deps).
1659 // If -Zlink-native-libraries=false is set, then the assumption is that an
1660 // external build system already has the native dependencies defined, and it
1661 // will provide them to the linker itself.
1662 if sess.opts.debugging_opts.link_native_libraries {
1663 add_local_native_libraries(cmd, sess, codegen_results);
1665 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1666 if sess.opts.debugging_opts.link_native_libraries {
1667 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1671 /// Add sysroot and other globally set directories to the directory search list.
1672 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1673 // The default library location, we need this to find the runtime.
1674 // The location of crates will be determined as needed.
1675 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1676 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1678 // Special directory with libraries used only in self-contained linkage mode
1680 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1681 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1685 /// Add options making relocation sections in the produced ELF files read-only
1686 /// and suppressing lazy binding.
1687 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1688 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.relro_level) {
1689 RelroLevel::Full => cmd.full_relro(),
1690 RelroLevel::Partial => cmd.partial_relro(),
1691 RelroLevel::Off => cmd.no_relro(),
1692 RelroLevel::None => {}
1696 /// Add library search paths used at runtime by dynamic linkers.
1698 cmd: &mut dyn Linker,
1700 codegen_results: &CodegenResults,
1701 out_filename: &Path,
1703 // FIXME (#2397): At some point we want to rpath our guesses as to
1704 // where extern libraries might live, based on the
1705 // addl_lib_search_paths
1706 if sess.opts.cg.rpath {
1707 let target_triple = sess.opts.target_triple.triple();
1708 let mut get_install_prefix_lib_path = || {
1709 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1710 let tlib = rustc_target::target_rustlib_path(&sess.sysroot, target_triple).join("lib");
1711 let mut path = PathBuf::from(install_prefix);
1716 let mut rpath_config = RPathConfig {
1717 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1718 out_filename: out_filename.to_path_buf(),
1719 has_rpath: sess.target.has_rpath,
1720 is_like_osx: sess.target.is_like_osx,
1721 linker_is_gnu: sess.target.linker_is_gnu,
1722 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1724 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1728 /// Produce the linker command line containing linker path and arguments.
1729 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1730 /// by the user without creating a custom target specification.
1731 /// `OBJECT-FILES` specify whether the arguments can add object files.
1732 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1733 /// or by the target spec can be inserted here.
1734 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1735 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1737 flavor: LinkerFlavor,
1739 crate_type: CrateType,
1741 out_filename: &Path,
1742 codegen_results: &CodegenResults,
1744 let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1745 let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1746 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1747 // to the linker args construction.
1748 assert!(base_cmd.get_args().is_empty() || sess.target.vendor == "uwp");
1749 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor);
1750 let link_output_kind = link_output_kind(sess, crate_type);
1752 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1753 add_pre_link_args(cmd, sess, flavor);
1755 // NO-OPT-OUT, OBJECT-FILES-NO
1756 add_apple_sdk(cmd, sess, flavor);
1759 add_link_script(cmd, sess, tmpdir, crate_type);
1761 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1762 if sess.target.is_like_fuchsia && crate_type == CrateType::Executable {
1763 let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1768 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1771 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1772 if sess.target.eh_frame_header {
1773 cmd.add_eh_frame_header();
1776 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1777 // Make the binary compatible with data execution prevention schemes.
1780 // NO-OPT-OUT, OBJECT-FILES-NO
1781 // Avoid linking to dynamic libraries unless they satisfy some undefined symbols
1782 // at the point at which they are specified on the command line.
1783 // Must be passed before any dynamic libraries.
1784 cmd.add_as_needed();
1786 // NO-OPT-OUT, OBJECT-FILES-NO
1787 if crt_objects_fallback {
1788 cmd.no_crt_objects();
1791 // NO-OPT-OUT, OBJECT-FILES-YES
1792 add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1794 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1795 if sess.target.is_like_emscripten {
1797 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1798 "DISABLE_EXCEPTION_CATCHING=1"
1800 "DISABLE_EXCEPTION_CATCHING=0"
1804 // OBJECT-FILES-YES, AUDIT-ORDER
1805 link_sanitizers(sess, crate_type, cmd);
1807 // OBJECT-FILES-NO, AUDIT-ORDER
1808 // Linker plugins should be specified early in the list of arguments
1809 // FIXME: How "early" exactly?
1810 cmd.linker_plugin_lto();
1812 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1813 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1814 add_library_search_dirs(cmd, sess, crt_objects_fallback);
1817 add_local_crate_regular_objects(cmd, codegen_results);
1819 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1820 cmd.output_filename(out_filename);
1822 // OBJECT-FILES-NO, AUDIT-ORDER
1823 if crate_type == CrateType::Executable && sess.target.is_like_windows {
1824 if let Some(ref s) = codegen_results.windows_subsystem {
1829 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1830 // If we're building something like a dynamic library then some platforms
1831 // need to make sure that all symbols are exported correctly from the
1833 cmd.export_symbols(tmpdir, crate_type);
1836 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1839 add_local_crate_allocator_objects(cmd, codegen_results);
1841 // OBJECT-FILES-NO, AUDIT-ORDER
1842 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1843 // Try to strip as much out of the generated object by removing unused
1844 // sections if possible. See more comments in linker.rs
1845 if !sess.link_dead_code() {
1846 let keep_metadata = crate_type == CrateType::Dylib;
1847 cmd.gc_sections(keep_metadata);
1850 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1851 cmd.set_output_kind(link_output_kind, out_filename);
1853 // OBJECT-FILES-NO, AUDIT-ORDER
1854 add_relro_args(cmd, sess);
1856 // OBJECT-FILES-NO, AUDIT-ORDER
1857 // Pass optimization flags down to the linker.
1860 // OBJECT-FILES-NO, AUDIT-ORDER
1861 // Pass debuginfo and strip flags down to the linker.
1862 cmd.debuginfo(sess.opts.debugging_opts.strip);
1864 // OBJECT-FILES-NO, AUDIT-ORDER
1865 // We want to prevent the compiler from accidentally leaking in any system libraries,
1866 // so by default we tell linkers not to link to any default libraries.
1867 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
1868 cmd.no_default_libraries();
1872 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1880 // OBJECT-FILES-NO, AUDIT-ORDER
1881 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
1885 // OBJECT-FILES-NO, AUDIT-ORDER
1886 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1887 cmd.control_flow_guard();
1890 // OBJECT-FILES-NO, AUDIT-ORDER
1891 add_rpath_args(cmd, sess, codegen_results, out_filename);
1893 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1894 add_user_defined_link_args(cmd, sess);
1896 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1899 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1900 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1902 // NO-OPT-OUT, OBJECT-FILES-YES
1903 add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1905 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1906 add_post_link_args(cmd, sess, flavor);
1911 /// # Native library linking
1913 /// User-supplied library search paths (-L on the command line). These are the same paths used to
1914 /// find Rust crates, so some of them may have been added already by the previous crate linking
1915 /// code. This only allows them to be found at compile time so it is still entirely up to outside
1916 /// forces to make sure that library can be found at runtime.
1918 /// Also note that the native libraries linked here are only the ones located in the current crate.
1919 /// Upstream crates with native library dependencies may have their native library pulled in above.
1920 fn add_local_native_libraries(
1921 cmd: &mut dyn Linker,
1923 codegen_results: &CodegenResults,
1925 let filesearch = sess.target_filesearch(PathKind::All);
1926 for search_path in filesearch.search_paths() {
1927 match search_path.kind {
1928 PathKind::Framework => {
1929 cmd.framework_path(&search_path.dir);
1932 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1938 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1940 let search_path = archive_search_paths(sess);
1941 let mut last = (NativeLibKind::Unspecified, None);
1942 for lib in relevant_libs {
1943 let name = match lib.name {
1948 // Skip if this library is the same as the last.
1949 last = if (lib.kind, lib.name) == last { continue } else { (lib.kind, lib.name) };
1951 let verbatim = lib.verbatim.unwrap_or(false);
1953 NativeLibKind::Dylib { as_needed } => {
1954 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
1956 NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
1957 NativeLibKind::Framework { as_needed } => {
1958 cmd.link_framework(name, as_needed.unwrap_or(true))
1960 NativeLibKind::Static { bundle: None | Some(true), .. }
1961 | NativeLibKind::Static { whole_archive: Some(true), .. } => {
1962 cmd.link_whole_staticlib(name, verbatim, &search_path);
1964 NativeLibKind::Static { .. } => cmd.link_staticlib(name, verbatim),
1965 NativeLibKind::RawDylib => {
1966 // FIXME(#58713): Proper handling for raw dylibs.
1967 bug!("raw_dylib feature not yet implemented");
1973 /// # Rust Crate linking
1975 /// Rust crates are not considered at all when creating an rlib output. All dependencies will be
1976 /// linked when producing the final output (instead of the intermediate rlib version).
1977 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1978 cmd: &mut dyn Linker,
1980 codegen_results: &CodegenResults,
1981 crate_type: CrateType,
1984 // All of the heavy lifting has previously been accomplished by the
1985 // dependency_format module of the compiler. This is just crawling the
1986 // output of that module, adding crates as necessary.
1988 // Linking to a rlib involves just passing it to the linker (the linker
1989 // will slurp up the object files inside), and linking to a dynamic library
1990 // involves just passing the right -l flag.
1992 let (_, data) = codegen_results
1996 .find(|(ty, _)| *ty == crate_type)
1997 .expect("failed to find crate type in dependency format list");
1999 // Invoke get_used_crates to ensure that we get a topological sorting of
2001 let deps = &codegen_results.crate_info.used_crates_dynamic;
2003 // There's a few internal crates in the standard library (aka libcore and
2004 // libstd) which actually have a circular dependence upon one another. This
2005 // currently arises through "weak lang items" where libcore requires things
2006 // like `rust_begin_unwind` but libstd ends up defining it. To get this
2007 // circular dependence to work correctly in all situations we'll need to be
2008 // sure to correctly apply the `--start-group` and `--end-group` options to
2009 // GNU linkers, otherwise if we don't use any other symbol from the standard
2010 // library it'll get discarded and the whole application won't link.
2012 // In this loop we're calculating the `group_end`, after which crate to
2013 // pass `--end-group` and `group_start`, before which crate to pass
2014 // `--start-group`. We currently do this by passing `--end-group` after
2015 // the first crate (when iterating backwards) that requires a lang item
2016 // defined somewhere else. Once that's set then when we've defined all the
2017 // necessary lang items we'll pass `--start-group`.
2019 // Note that this isn't amazing logic for now but it should do the trick
2020 // for the current implementation of the standard library.
2021 let mut group_end = None;
2022 let mut group_start = None;
2023 // Crates available for linking thus far.
2024 let mut available = FxHashSet::default();
2025 // Crates required to satisfy dependencies discovered so far.
2026 let mut required = FxHashSet::default();
2028 let info = &codegen_results.crate_info;
2029 for &(cnum, _) in deps.iter().rev() {
2030 if let Some(missing) = info.missing_lang_items.get(&cnum) {
2031 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
2032 required.extend(missing_crates);
2035 required.insert(Some(cnum));
2036 available.insert(Some(cnum));
2038 if required.len() > available.len() && group_end.is_none() {
2039 group_end = Some(cnum);
2041 if required.len() == available.len() && group_end.is_some() {
2042 group_start = Some(cnum);
2047 // If we didn't end up filling in all lang items from upstream crates then
2048 // we'll be filling it in with our crate. This probably means we're the
2049 // standard library itself, so skip this for now.
2050 if group_end.is_some() && group_start.is_none() {
2054 let mut compiler_builtins = None;
2056 for &(cnum, _) in deps.iter() {
2057 if group_start == Some(cnum) {
2061 // We may not pass all crates through to the linker. Some crates may
2062 // appear statically in an existing dylib, meaning we'll pick up all the
2063 // symbols from the dylib.
2064 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2065 match data[cnum.as_usize() - 1] {
2066 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
2067 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
2069 // compiler-builtins are always placed last to ensure that they're
2070 // linked correctly.
2071 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
2072 assert!(compiler_builtins.is_none());
2073 compiler_builtins = Some(cnum);
2075 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
2076 Linkage::Static => {
2077 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
2079 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
2082 if group_end == Some(cnum) {
2087 // compiler-builtins are always placed last to ensure that they're
2088 // linked correctly.
2089 // We must always link the `compiler_builtins` crate statically. Even if it
2090 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
2092 if let Some(cnum) = compiler_builtins {
2093 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
2096 // Converts a library file-stem into a cc -l argument
2097 fn unlib<'a>(target: &Target, stem: &'a str) -> &'a str {
2098 if stem.starts_with("lib") && !target.is_like_windows { &stem[3..] } else { stem }
2101 // Adds the static "rlib" versions of all crates to the command line.
2102 // There's a bit of magic which happens here specifically related to LTO,
2103 // namely that we remove upstream object files.
2105 // When performing LTO, almost(*) all of the bytecode from the upstream
2106 // libraries has already been included in our object file output. As a
2107 // result we need to remove the object files in the upstream libraries so
2108 // the linker doesn't try to include them twice (or whine about duplicate
2109 // symbols). We must continue to include the rest of the rlib, however, as
2110 // it may contain static native libraries which must be linked in.
2112 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
2113 // their bytecode wasn't included. The object files in those libraries must
2114 // still be passed to the linker.
2116 // Note, however, that if we're not doing LTO we can just pass the rlib
2117 // blindly to the linker (fast) because it's fine if it's not actually
2118 // included as we're at the end of the dependency chain.
2119 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
2120 cmd: &mut dyn Linker,
2122 codegen_results: &CodegenResults,
2124 crate_type: CrateType,
2127 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2128 let cratepath = &src.rlib.as_ref().unwrap().0;
2130 let mut link_upstream = |path: &Path| {
2131 // If we're creating a dylib, then we need to include the
2132 // whole of each object in our archive into that artifact. This is
2133 // because a `dylib` can be reused as an intermediate artifact.
2135 // Note, though, that we don't want to include the whole of a
2136 // compiler-builtins crate (e.g., compiler-rt) because it'll get
2137 // repeatedly linked anyway.
2138 let path = fix_windows_verbatim_for_gcc(path);
2139 if crate_type == CrateType::Dylib
2140 && codegen_results.crate_info.compiler_builtins != Some(cnum)
2142 cmd.link_whole_rlib(&path);
2144 cmd.link_rlib(&path);
2148 // See the comment above in `link_staticlib` and `link_rlib` for why if
2149 // there's a static library that's not relevant we skip all object
2151 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
2152 let skip_native = native_libs.iter().any(|lib| {
2153 matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
2154 && !relevant_lib(sess, lib)
2157 if (!are_upstream_rust_objects_already_included(sess)
2158 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
2161 link_upstream(cratepath);
2165 let dst = tmpdir.join(cratepath.file_name().unwrap());
2166 let name = cratepath.file_name().unwrap().to_str().unwrap();
2167 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2169 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2170 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
2171 archive.update_symbols();
2173 let mut any_objects = false;
2174 for f in archive.src_files() {
2175 if f == METADATA_FILENAME {
2176 archive.remove_file(&f);
2180 let canonical = f.replace("-", "_");
2181 let canonical_name = name.replace("-", "_");
2183 let is_rust_object =
2184 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2186 // If we've been requested to skip all native object files
2187 // (those not generated by the rust compiler) then we can skip
2188 // this file. See above for why we may want to do this.
2189 let skip_because_cfg_say_so = skip_native && !is_rust_object;
2191 // If we're performing LTO and this is a rust-generated object
2192 // file, then we don't need the object file as it's part of the
2193 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2194 // though, so we let that object file slide.
2195 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
2197 && (sess.target.no_builtins
2198 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
2200 if skip_because_cfg_say_so || skip_because_lto {
2201 archive.remove_file(&f);
2211 link_upstream(&dst);
2215 // Same thing as above, but for dynamic crates instead of static crates.
2216 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2217 // Just need to tell the linker about where the library lives and
2219 let parent = cratepath.parent();
2220 if let Some(dir) = parent {
2221 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2223 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2224 cmd.link_rust_dylib(
2225 Symbol::intern(&unlib(&sess.target, filestem)),
2226 parent.unwrap_or_else(|| Path::new("")),
2231 /// Link in all of our upstream crates' native dependencies. Remember that all of these upstream
2232 /// native dependencies are all non-static dependencies. We've got two cases then:
2234 /// 1. The upstream crate is an rlib. In this case we *must* link in the native dependency because
2235 /// the rlib is just an archive.
2237 /// 2. The upstream crate is a dylib. In order to use the dylib, we have to have the dependency
2238 /// present on the system somewhere. Thus, we don't gain a whole lot from not linking in the
2239 /// dynamic dependency to this crate as well.
2241 /// The use case for this is a little subtle. In theory the native dependencies of a crate are
2242 /// purely an implementation detail of the crate itself, but the problem arises with generic and
2243 /// inlined functions. If a generic function calls a native function, then the generic function
2244 /// must be instantiated in the target crate, meaning that the native symbol must also be resolved
2245 /// in the target crate.
2246 fn add_upstream_native_libraries(
2247 cmd: &mut dyn Linker,
2249 codegen_results: &CodegenResults,
2250 crate_type: CrateType,
2252 // Be sure to use a topological sorting of crates because there may be
2253 // interdependencies between native libraries. When passing -nodefaultlibs,
2254 // for example, almost all native libraries depend on libc, so we have to
2255 // make sure that's all the way at the right (liblibc is near the base of
2256 // the dependency chain).
2258 // This passes RequireStatic, but the actual requirement doesn't matter,
2259 // we're just getting an ordering of crate numbers, we're not worried about
2261 let (_, data) = codegen_results
2265 .find(|(ty, _)| *ty == crate_type)
2266 .expect("failed to find crate type in dependency format list");
2268 let crates = &codegen_results.crate_info.used_crates_static;
2269 let mut last = (NativeLibKind::Unspecified, None);
2270 for &(cnum, _) in crates {
2271 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2272 let name = match lib.name {
2276 if !relevant_lib(sess, &lib) {
2280 // Skip if this library is the same as the last.
2281 last = if (lib.kind, lib.name) == last { continue } else { (lib.kind, lib.name) };
2283 let verbatim = lib.verbatim.unwrap_or(false);
2285 NativeLibKind::Dylib { as_needed } => {
2286 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2288 NativeLibKind::Unspecified => cmd.link_dylib(name, verbatim, true),
2289 NativeLibKind::Framework { as_needed } => {
2290 cmd.link_framework(name, as_needed.unwrap_or(true))
2292 NativeLibKind::Static { bundle: Some(false), .. } => {
2293 // Link "static-nobundle" native libs only if the crate they originate from
2294 // is being linked statically to the current crate. If it's linked dynamically
2295 // or is an rlib already included via some other dylib crate, the symbols from
2296 // native libs will have already been included in that dylib.
2297 if data[cnum.as_usize() - 1] == Linkage::Static {
2298 cmd.link_staticlib(name, verbatim)
2301 // ignore statically included native libraries here as we've
2302 // already included them when we included the rust library
2304 NativeLibKind::Static { bundle: None | Some(true), .. } => {}
2305 NativeLibKind::RawDylib => {
2306 // FIXME(#58713): Proper handling for raw dylibs.
2307 bug!("raw_dylib feature not yet implemented");
2314 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2316 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2321 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2323 config::Lto::Fat => true,
2324 config::Lto::Thin => {
2325 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2326 // any upstream object files have not been copied yet.
2327 !sess.opts.cg.linker_plugin_lto.enabled()
2329 config::Lto::No | config::Lto::ThinLocal => false,
2333 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2334 let arch = &sess.target.arch;
2335 let os = &sess.target.os;
2336 let llvm_target = &sess.target.llvm_target;
2337 if sess.target.vendor != "apple"
2338 || !matches!(os.as_str(), "ios" | "tvos")
2339 || flavor != LinkerFlavor::Gcc
2343 let sdk_name = match (arch.as_str(), os.as_str()) {
2344 ("aarch64", "tvos") => "appletvos",
2345 ("x86_64", "tvos") => "appletvsimulator",
2346 ("arm", "ios") => "iphoneos",
2347 ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2348 ("aarch64", "ios") if llvm_target.contains("sim") => "iphonesimulator",
2349 ("aarch64", "ios") => "iphoneos",
2350 ("x86", "ios") => "iphonesimulator",
2351 ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2352 ("x86_64", "ios") => "iphonesimulator",
2354 sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2358 let sdk_root = match get_apple_sdk_root(sdk_name) {
2365 if llvm_target.contains("macabi") {
2366 cmd.args(&["-target", llvm_target])
2368 let arch_name = llvm_target.split('-').next().expect("LLVM target must have a hyphen");
2369 cmd.args(&["-arch", arch_name])
2371 cmd.args(&["-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2374 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2375 // Following what clang does
2376 // (https://github.com/llvm/llvm-project/blob/
2377 // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2378 // to allow the SDK path to be set. (For clang, xcrun sets
2379 // SDKROOT; for rustc, the user or build system can set it, or we
2380 // can fall back to checking for xcrun on PATH.)
2381 if let Ok(sdkroot) = env::var("SDKROOT") {
2382 let p = Path::new(&sdkroot);
2384 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2386 if sdkroot.contains("TVSimulator.platform")
2387 || sdkroot.contains("MacOSX.platform") => {}
2389 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2391 if sdkroot.contains("iPhoneSimulator.platform")
2392 || sdkroot.contains("MacOSX.platform") => {}
2394 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2397 if sdkroot.contains("iPhoneOS.platform")
2398 || sdkroot.contains("iPhoneSimulator.platform") => {}
2399 // Ignore `SDKROOT` if it's not a valid path.
2400 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2401 _ => return Ok(sdkroot),
2405 Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2407 if output.status.success() {
2408 Ok(String::from_utf8(output.stdout).unwrap())
2410 let error = String::from_utf8(output.stderr);
2411 let error = format!("process exit with error: {}", error.unwrap());
2412 Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2418 Ok(output) => Ok(output.trim().to_string()),
2419 Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),