2 use super::command::Command;
3 use super::symbol_export;
4 use rustc_span::symbol::sym;
6 use std::ffi::{OsStr, OsString};
7 use std::fs::{self, File};
8 use std::io::prelude::*;
9 use std::io::{self, BufWriter};
10 use std::path::{Path, PathBuf};
11 use std::{env, mem, str};
13 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
14 use rustc_middle::middle::dependency_format::Linkage;
15 use rustc_middle::ty::TyCtxt;
16 use rustc_serialize::{json, Encoder};
17 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
18 use rustc_session::Session;
19 use rustc_span::symbol::Symbol;
20 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
22 use cc::windows_registry;
24 /// Disables non-English messages from localized linkers.
25 /// Such messages may cause issues with text encoding on Windows (#35785)
26 /// and prevent inspection of linker output in case of errors, which we occasionally do.
27 /// This should be acceptable because other messages from rustc are in English anyway,
28 /// and may also be desirable to improve searchability of the linker diagnostics.
29 pub fn disable_localization(linker: &mut Command) {
30 // No harm in setting both env vars simultaneously.
31 // Unix-style linkers.
32 linker.env("LC_ALL", "C");
34 linker.env("VSLANG", "1033");
37 // The third parameter is for env vars, used on windows to set up the
38 // path for MSVC to find its DLLs, and gcc to find its bundled
40 pub fn get_linker<'a>(
46 ) -> Box<dyn Linker + 'a> {
47 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
49 // If our linker looks like a batch script on Windows then to execute this
50 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
51 // emscripten where the linker is `emcc.bat` and needs to be spawned as
52 // `cmd /c emcc.bat ...`.
54 // This worked historically but is needed manually since #42436 (regression
55 // was tagged as #42791) and some more info can be found on #44443 for
57 let mut cmd = match linker.to_str() {
58 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
60 LinkerFlavor::Lld(f) => Command::lld(linker, f),
61 LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
62 Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
64 _ => Command::new(linker),
68 // UWP apps have API restrictions enforced during Store submissions.
69 // To comply with the Windows App Certification Kit,
70 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
72 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
75 if let Some(ref tool) = msvc_tool {
76 let original_path = tool.path();
77 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
78 let arch = match t.arch.as_str() {
79 "x86_64" => Some("x64"),
81 "aarch64" => Some("arm64"),
85 if let Some(ref a) = arch {
86 // FIXME: Move this to `fn linker_with_args`.
87 let mut arg = OsString::from("/LIBPATH:");
88 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
91 warn!("arch is not supported");
94 warn!("MSVC root path lib location not found");
97 warn!("link.exe not found");
101 // The compiler's sysroot often has some bundled tools, so add it to the
102 // PATH for the child.
103 let mut new_path = sess.get_tools_search_paths(self_contained);
104 let mut msvc_changed_path = false;
105 if sess.target.is_like_msvc {
106 if let Some(ref tool) = msvc_tool {
107 cmd.args(tool.args());
108 for &(ref k, ref v) in tool.env() {
110 new_path.extend(env::split_paths(v));
111 msvc_changed_path = true;
119 if !msvc_changed_path {
120 if let Some(path) = env::var_os("PATH") {
121 new_path.extend(env::split_paths(&path));
124 cmd.env("PATH", env::join_paths(new_path).unwrap());
126 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
127 // to the linker args construction.
128 assert!(cmd.get_args().is_empty() || sess.target.vendor == "uwp");
131 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
132 Box::new(MsvcLinker { cmd, sess }) as Box<dyn Linker>
134 LinkerFlavor::Em => Box::new(EmLinker { cmd, sess }) as Box<dyn Linker>,
135 LinkerFlavor::Gcc => {
136 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: false })
140 LinkerFlavor::Lld(LldFlavor::Ld)
141 | LinkerFlavor::Lld(LldFlavor::Ld64)
142 | LinkerFlavor::Ld => {
143 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: true })
147 LinkerFlavor::Lld(LldFlavor::Wasm) => Box::new(WasmLd::new(cmd, sess)) as Box<dyn Linker>,
149 LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
151 LinkerFlavor::BpfLinker => Box::new(BpfLinker { cmd, sess }) as Box<dyn Linker>,
155 /// Linker abstraction used by `back::link` to build up the command to invoke a
158 /// This trait is the total list of requirements needed by `back::link` and
159 /// represents the meaning of each option being passed down. This trait is then
160 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
161 /// MSVC linker (e.g., `link.exe`) is being used.
163 fn cmd(&mut self) -> &mut Command;
164 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
165 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, as_needed: bool);
166 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
167 fn link_framework(&mut self, framework: Symbol, as_needed: bool);
168 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool);
169 fn link_rlib(&mut self, lib: &Path);
170 fn link_whole_rlib(&mut self, lib: &Path);
171 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, search_path: &[PathBuf]);
172 fn include_path(&mut self, path: &Path);
173 fn framework_path(&mut self, path: &Path);
174 fn output_filename(&mut self, path: &Path);
175 fn add_object(&mut self, path: &Path);
176 fn gc_sections(&mut self, keep_metadata: bool);
177 fn no_gc_sections(&mut self);
178 fn full_relro(&mut self);
179 fn partial_relro(&mut self);
180 fn no_relro(&mut self);
181 fn optimize(&mut self);
182 fn pgo_gen(&mut self);
183 fn control_flow_guard(&mut self);
184 fn debuginfo(&mut self, strip: Strip);
185 fn no_crt_objects(&mut self);
186 fn no_default_libraries(&mut self);
187 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]);
188 fn subsystem(&mut self, subsystem: &str);
189 fn group_start(&mut self);
190 fn group_end(&mut self);
191 fn linker_plugin_lto(&mut self);
192 fn add_eh_frame_header(&mut self) {}
193 fn add_no_exec(&mut self) {}
194 fn add_as_needed(&mut self) {}
195 fn reset_per_library_state(&mut self) {}
198 impl dyn Linker + '_ {
199 pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
203 pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
204 self.cmd().args(args);
207 pub fn take_cmd(&mut self) -> Command {
208 mem::replace(self.cmd(), Command::new(""))
212 pub struct GccLinker<'a> {
216 hinted_static: bool, // Keeps track of the current hinting mode.
221 impl<'a> GccLinker<'a> {
222 /// Argument that must be passed *directly* to the linker
224 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
225 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
230 let mut os = OsString::from("-Wl,");
231 os.push(arg.as_ref());
239 fn takes_hints(&self) -> bool {
240 // Really this function only returns true if the underlying linker
241 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
242 // don't really have a foolproof way to detect that, so rule out some
243 // platforms where currently this is guaranteed to *not* be the case:
245 // * On OSX they have their own linker, not binutils'
246 // * For WebAssembly the only functional linker is LLD, which doesn't
247 // support hint flags
248 !self.sess.target.is_like_osx && !self.sess.target.is_like_wasm
251 // Some platforms take hints about whether a library is static or dynamic.
252 // For those that support this, we ensure we pass the option if the library
253 // was flagged "static" (most defaults are dynamic) to ensure that if
254 // libfoo.a and libfoo.so both exist that the right one is chosen.
255 fn hint_static(&mut self) {
256 if !self.takes_hints() {
259 if !self.hinted_static {
260 self.linker_arg("-Bstatic");
261 self.hinted_static = true;
265 fn hint_dynamic(&mut self) {
266 if !self.takes_hints() {
269 if self.hinted_static {
270 self.linker_arg("-Bdynamic");
271 self.hinted_static = false;
275 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
276 if let Some(plugin_path) = plugin_path {
277 let mut arg = OsString::from("-plugin=");
278 arg.push(plugin_path);
279 self.linker_arg(&arg);
282 let opt_level = match self.sess.opts.optimize {
283 config::OptLevel::No => "O0",
284 config::OptLevel::Less => "O1",
285 config::OptLevel::Default | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
286 config::OptLevel::Aggressive => "O3",
289 self.linker_arg(&format!("-plugin-opt={}", opt_level));
290 self.linker_arg(&format!("-plugin-opt=mcpu={}", self.target_cpu));
293 fn build_dylib(&mut self, out_filename: &Path) {
294 // On mac we need to tell the linker to let this library be rpathed
295 if self.sess.target.is_like_osx {
296 self.cmd.arg("-dynamiclib");
297 self.linker_arg("-dylib");
299 // Note that the `osx_rpath_install_name` option here is a hack
300 // purely to support rustbuild right now, we should get a more
301 // principled solution at some point to force the compiler to pass
302 // the right `-Wl,-install_name` with an `@rpath` in it.
303 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
304 self.linker_arg("-install_name");
305 let mut v = OsString::from("@rpath/");
306 v.push(out_filename.file_name().unwrap());
310 self.cmd.arg("-shared");
311 if self.sess.target.is_like_windows {
312 // The output filename already contains `dll_suffix` so
313 // the resulting import library will have a name in the
314 // form of libfoo.dll.a
316 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
319 self.sess.target.staticlib_prefix,
321 self.sess.target.staticlib_suffix
324 if let Some(implib_name) = implib_name {
325 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
326 if let Some(implib) = implib {
327 self.linker_arg(&format!("--out-implib={}", (*implib).to_str().unwrap()));
335 impl<'a> Linker for GccLinker<'a> {
336 fn cmd(&mut self) -> &mut Command {
340 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
342 LinkOutputKind::DynamicNoPicExe => {
343 if !self.is_ld && self.sess.target.linker_is_gnu {
344 self.cmd.arg("-no-pie");
347 LinkOutputKind::DynamicPicExe => {
348 // noop on windows w/ gcc & ld, error w/ lld
349 if !self.sess.target.is_like_windows {
350 // `-pie` works for both gcc wrapper and ld.
351 self.cmd.arg("-pie");
354 LinkOutputKind::StaticNoPicExe => {
355 // `-static` works for both gcc wrapper and ld.
356 self.cmd.arg("-static");
357 if !self.is_ld && self.sess.target.linker_is_gnu {
358 self.cmd.arg("-no-pie");
361 LinkOutputKind::StaticPicExe => {
363 // Note that combination `-static -pie` doesn't work as expected
364 // for the gcc wrapper, `-static` in that case suppresses `-pie`.
365 self.cmd.arg("-static-pie");
367 // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
368 // a static pie, but currently passed because gcc and clang pass them.
369 // The former suppresses the `INTERP` ELF header specifying dynamic linker,
370 // which is otherwise implicitly injected by ld (but not lld).
371 // The latter doesn't change anything, only ensures that everything is pic.
372 self.cmd.args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
375 LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
376 LinkOutputKind::StaticDylib => {
377 self.cmd.arg("-static");
378 self.build_dylib(out_filename);
380 LinkOutputKind::WasiReactorExe => {
381 self.linker_arg("--entry");
382 self.linker_arg("_initialize");
385 // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
386 // it switches linking for libc and similar system libraries to static without using
387 // any `#[link]` attributes in the `libc` crate, see #72782 for details.
388 // FIXME: Switch to using `#[link]` attributes in the `libc` crate
389 // similarly to other targets.
390 if self.sess.target.os == "vxworks"
393 LinkOutputKind::StaticNoPicExe
394 | LinkOutputKind::StaticPicExe
395 | LinkOutputKind::StaticDylib
398 self.cmd.arg("--static-crt");
402 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, as_needed: bool) {
403 if self.sess.target.os == "illumos" && lib.as_str() == "c" {
404 // libc will be added via late_link_args on illumos so that it will
405 // appear last in the library search order.
406 // FIXME: This should be replaced by a more complete and generic
407 // mechanism for controlling the order of library arguments passed
412 if self.sess.target.is_like_osx {
413 // FIXME(81490): ld64 doesn't support these flags but macOS 11
414 // has -needed-l{} / -needed_library {}
415 // but we have no way to detect that here.
416 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
417 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
418 self.linker_arg("--no-as-needed");
420 self.sess.warn("`as-needed` modifier not supported for current linker");
424 self.cmd.arg(format!("-l{}{}", if verbatim { ":" } else { "" }, lib));
426 if self.sess.target.is_like_osx {
427 // See above FIXME comment
428 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
429 self.linker_arg("--as-needed");
433 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool) {
435 self.cmd.arg(format!("-l{}{}", if verbatim { ":" } else { "" }, lib));
437 fn link_rlib(&mut self, lib: &Path) {
441 fn include_path(&mut self, path: &Path) {
442 self.cmd.arg("-L").arg(path);
444 fn framework_path(&mut self, path: &Path) {
445 self.cmd.arg("-F").arg(path);
447 fn output_filename(&mut self, path: &Path) {
448 self.cmd.arg("-o").arg(path);
450 fn add_object(&mut self, path: &Path) {
453 fn full_relro(&mut self) {
454 self.linker_arg("-zrelro");
455 self.linker_arg("-znow");
457 fn partial_relro(&mut self) {
458 self.linker_arg("-zrelro");
460 fn no_relro(&mut self) {
461 self.linker_arg("-znorelro");
464 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
466 self.cmd.arg(format!("-l{}", lib));
469 fn link_framework(&mut self, framework: Symbol, as_needed: bool) {
472 // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
473 // flag but we have no way to detect that here.
474 // self.cmd.arg("-needed_framework").sym_arg(framework);
475 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
477 self.cmd.arg("-framework").sym_arg(framework);
480 // Here we explicitly ask that the entire archive is included into the
481 // result artifact. For more details see #15460, but the gist is that
482 // the linker will strip away any unused objects in the archive if we
483 // don't otherwise explicitly reference them. This can occur for
484 // libraries which are just providing bindings, libraries with generic
486 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, search_path: &[PathBuf]) {
488 let target = &self.sess.target;
489 if !target.is_like_osx {
490 self.linker_arg("--whole-archive").cmd.arg(format!(
492 if verbatim { ":" } else { "" },
495 self.linker_arg("--no-whole-archive");
497 // -force_load is the macOS equivalent of --whole-archive, but it
498 // involves passing the full path to the library to link.
499 self.linker_arg("-force_load");
500 let lib = archive::find_library(lib, verbatim, search_path, &self.sess);
501 self.linker_arg(&lib);
505 fn link_whole_rlib(&mut self, lib: &Path) {
507 if self.sess.target.is_like_osx {
508 self.linker_arg("-force_load");
509 self.linker_arg(&lib);
511 self.linker_arg("--whole-archive").cmd.arg(lib);
512 self.linker_arg("--no-whole-archive");
516 fn gc_sections(&mut self, keep_metadata: bool) {
517 // The dead_strip option to the linker specifies that functions and data
518 // unreachable by the entry point will be removed. This is quite useful
519 // with Rust's compilation model of compiling libraries at a time into
520 // one object file. For example, this brings hello world from 1.7MB to
523 // Note that this is done for both executables and dynamic libraries. We
524 // won't get much benefit from dylibs because LLVM will have already
525 // stripped away as much as it could. This has not been seen to impact
526 // link times negatively.
528 // -dead_strip can't be part of the pre_link_args because it's also used
529 // for partial linking when using multiple codegen units (-r). So we
531 if self.sess.target.is_like_osx {
532 self.linker_arg("-dead_strip");
534 // If we're building a dylib, we don't use --gc-sections because LLVM
535 // has already done the best it can do, and we also don't want to
536 // eliminate the metadata. If we're building an executable, however,
537 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
539 } else if (self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm)
542 self.linker_arg("--gc-sections");
546 fn no_gc_sections(&mut self) {
547 if self.sess.target.is_like_osx {
548 self.linker_arg("-no_dead_strip");
549 } else if self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm {
550 self.linker_arg("--no-gc-sections");
554 fn optimize(&mut self) {
555 if !self.sess.target.linker_is_gnu && !self.sess.target.is_like_wasm {
559 // GNU-style linkers support optimization with -O. GNU ld doesn't
560 // need a numeric argument, but other linkers do.
561 if self.sess.opts.optimize == config::OptLevel::Default
562 || self.sess.opts.optimize == config::OptLevel::Aggressive
564 self.linker_arg("-O1");
568 fn pgo_gen(&mut self) {
569 if !self.sess.target.linker_is_gnu {
573 // If we're doing PGO generation stuff and on a GNU-like linker, use the
574 // "-u" flag to properly pull in the profiler runtime bits.
576 // This is because LLVM otherwise won't add the needed initialization
577 // for us on Linux (though the extra flag should be harmless if it
580 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
582 // Though it may be worth to try to revert those changes upstream, since
583 // the overhead of the initialization should be minor.
585 self.cmd.arg("__llvm_profile_runtime");
588 fn control_flow_guard(&mut self) {}
590 fn debuginfo(&mut self, strip: Strip) {
591 // MacOS linker doesn't support stripping symbols directly anymore.
592 if self.sess.target.is_like_osx {
598 Strip::Debuginfo => {
599 self.linker_arg("--strip-debug");
602 self.linker_arg("--strip-all");
607 fn no_crt_objects(&mut self) {
609 self.cmd.arg("-nostartfiles");
613 fn no_default_libraries(&mut self) {
615 self.cmd.arg("-nodefaultlibs");
619 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
620 // Symbol visibility in object files typically takes care of this.
621 if crate_type == CrateType::Executable && self.sess.target.override_export_symbols.is_none()
626 // We manually create a list of exported symbols to ensure we don't expose any more.
627 // The object files have far more public symbols than we actually want to export,
628 // so we hide them all here.
630 if !self.sess.target.limit_rdylib_exports {
634 if crate_type == CrateType::ProcMacro {
638 let is_windows = self.sess.target.is_like_windows;
639 let mut arg = OsString::new();
640 let path = tmpdir.join(if is_windows { "list.def" } else { "list" });
642 debug!("EXPORTED SYMBOLS:");
644 if self.sess.target.is_like_osx {
645 // Write a plain, newline-separated list of symbols
646 let res: io::Result<()> = try {
647 let mut f = BufWriter::new(File::create(&path)?);
650 writeln!(f, "_{}", sym)?;
653 if let Err(e) = res {
654 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
656 } else if is_windows {
657 let res: io::Result<()> = try {
658 let mut f = BufWriter::new(File::create(&path)?);
660 // .def file similar to MSVC one but without LIBRARY section
661 // because LD doesn't like when it's empty
662 writeln!(f, "EXPORTS")?;
663 for symbol in symbols {
664 debug!(" _{}", symbol);
665 writeln!(f, " {}", symbol)?;
668 if let Err(e) = res {
669 self.sess.fatal(&format!("failed to write list.def file: {}", e));
672 // Write an LD version script
673 let res: io::Result<()> = try {
674 let mut f = BufWriter::new(File::create(&path)?);
676 if !symbols.is_empty() {
677 writeln!(f, " global:")?;
680 writeln!(f, " {};", sym)?;
683 writeln!(f, "\n local:\n *;\n}};")?;
685 if let Err(e) = res {
686 self.sess.fatal(&format!("failed to write version script: {}", e));
690 if self.sess.target.is_like_osx {
694 arg.push("-exported_symbols_list,");
695 } else if self.sess.target.is_like_solaris {
704 // Both LD and LLD accept export list in *.def file form, there are no flags required
706 arg.push("--version-script=")
714 fn subsystem(&mut self, subsystem: &str) {
715 self.linker_arg("--subsystem");
716 self.linker_arg(&subsystem);
719 fn reset_per_library_state(&mut self) {
720 self.hint_dynamic(); // Reset to default before returning the composed command line.
723 fn group_start(&mut self) {
724 if self.takes_hints() {
725 self.linker_arg("--start-group");
729 fn group_end(&mut self) {
730 if self.takes_hints() {
731 self.linker_arg("--end-group");
735 fn linker_plugin_lto(&mut self) {
736 match self.sess.opts.cg.linker_plugin_lto {
737 LinkerPluginLto::Disabled => {
740 LinkerPluginLto::LinkerPluginAuto => {
741 self.push_linker_plugin_lto_args(None);
743 LinkerPluginLto::LinkerPlugin(ref path) => {
744 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
749 // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
750 // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
751 // so we just always add it.
752 fn add_eh_frame_header(&mut self) {
753 self.linker_arg("--eh-frame-hdr");
756 fn add_no_exec(&mut self) {
757 if self.sess.target.is_like_windows {
758 self.linker_arg("--nxcompat");
759 } else if self.sess.target.linker_is_gnu {
760 self.linker_arg("-znoexecstack");
764 fn add_as_needed(&mut self) {
765 if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
766 self.linker_arg("--as-needed");
767 } else if self.sess.target.is_like_solaris {
768 // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
769 self.linker_arg("-z");
770 self.linker_arg("ignore");
775 pub struct MsvcLinker<'a> {
780 impl<'a> Linker for MsvcLinker<'a> {
781 fn cmd(&mut self) -> &mut Command {
785 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
787 LinkOutputKind::DynamicNoPicExe
788 | LinkOutputKind::DynamicPicExe
789 | LinkOutputKind::StaticNoPicExe
790 | LinkOutputKind::StaticPicExe => {}
791 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
792 self.cmd.arg("/DLL");
793 let mut arg: OsString = "/IMPLIB:".into();
794 arg.push(out_filename.with_extension("dll.lib"));
797 LinkOutputKind::WasiReactorExe => {
798 panic!("can't link as reactor on non-wasi target");
803 fn link_rlib(&mut self, lib: &Path) {
806 fn add_object(&mut self, path: &Path) {
810 fn gc_sections(&mut self, _keep_metadata: bool) {
811 // MSVC's ICF (Identical COMDAT Folding) link optimization is
812 // slow for Rust and thus we disable it by default when not in
813 // optimization build.
814 if self.sess.opts.optimize != config::OptLevel::No {
815 self.cmd.arg("/OPT:REF,ICF");
817 // It is necessary to specify NOICF here, because /OPT:REF
818 // implies ICF by default.
819 self.cmd.arg("/OPT:REF,NOICF");
823 fn no_gc_sections(&mut self) {
824 self.cmd.arg("/OPT:NOREF,NOICF");
827 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, _as_needed: bool) {
828 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
831 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
832 // When producing a dll, the MSVC linker may not actually emit a
833 // `foo.lib` file if the dll doesn't actually export any symbols, so we
834 // check to see if the file is there and just omit linking to it if it's
836 let name = format!("{}.dll.lib", lib);
837 if path.join(&name).exists() {
842 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool) {
843 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
846 fn full_relro(&mut self) {
850 fn partial_relro(&mut self) {
854 fn no_relro(&mut self) {
858 fn no_crt_objects(&mut self) {
862 fn no_default_libraries(&mut self) {
863 self.cmd.arg("/NODEFAULTLIB");
866 fn include_path(&mut self, path: &Path) {
867 let mut arg = OsString::from("/LIBPATH:");
872 fn output_filename(&mut self, path: &Path) {
873 let mut arg = OsString::from("/OUT:");
878 fn framework_path(&mut self, _path: &Path) {
879 bug!("frameworks are not supported on windows")
881 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
882 bug!("frameworks are not supported on windows")
885 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, _search_path: &[PathBuf]) {
886 self.cmd.arg(format!("/WHOLEARCHIVE:{}{}", lib, if verbatim { "" } else { ".lib" }));
888 fn link_whole_rlib(&mut self, path: &Path) {
889 let mut arg = OsString::from("/WHOLEARCHIVE:");
893 fn optimize(&mut self) {
894 // Needs more investigation of `/OPT` arguments
897 fn pgo_gen(&mut self) {
898 // Nothing needed here.
901 fn control_flow_guard(&mut self) {
902 self.cmd.arg("/guard:cf");
905 fn debuginfo(&mut self, strip: Strip) {
908 // This will cause the Microsoft linker to generate a PDB file
909 // from the CodeView line tables in the object files.
910 self.cmd.arg("/DEBUG");
912 // This will cause the Microsoft linker to embed .natvis info into the PDB file
913 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
914 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
915 for entry in natvis_dir {
918 let path = entry.path();
919 if path.extension() == Some("natvis".as_ref()) {
920 let mut arg = OsString::from("/NATVIS:");
927 .warn(&format!("error enumerating natvis directory: {}", err));
933 Strip::Debuginfo | Strip::Symbols => {
934 self.cmd.arg("/DEBUG:NONE");
939 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
940 // export symbols from a dynamic library. When building a dynamic library,
941 // however, we're going to want some symbols exported, so this function
942 // generates a DEF file which lists all the symbols.
944 // The linker will read this `*.def` file and export all the symbols from
945 // the dynamic library. Note that this is not as simple as just exporting
946 // all the symbols in the current crate (as specified by `codegen.reachable`)
947 // but rather we also need to possibly export the symbols of upstream
948 // crates. Upstream rlibs may be linked statically to this dynamic library,
949 // in which case they may continue to transitively be used and hence need
950 // their symbols exported.
951 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
952 // Symbol visibility takes care of this typically
953 if crate_type == CrateType::Executable {
957 let path = tmpdir.join("lib.def");
958 let res: io::Result<()> = try {
959 let mut f = BufWriter::new(File::create(&path)?);
961 // Start off with the standard module name header and then go
962 // straight to exports.
963 writeln!(f, "LIBRARY")?;
964 writeln!(f, "EXPORTS")?;
965 for symbol in symbols {
966 debug!(" _{}", symbol);
967 writeln!(f, " {}", symbol)?;
970 if let Err(e) = res {
971 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
973 let mut arg = OsString::from("/DEF:");
978 fn subsystem(&mut self, subsystem: &str) {
979 // Note that previous passes of the compiler validated this subsystem,
980 // so we just blindly pass it to the linker.
981 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
983 // Windows has two subsystems we're interested in right now, the console
984 // and windows subsystems. These both implicitly have different entry
985 // points (starting symbols). The console entry point starts with
986 // `mainCRTStartup` and the windows entry point starts with
987 // `WinMainCRTStartup`. These entry points, defined in system libraries,
988 // will then later probe for either `main` or `WinMain`, respectively to
989 // start the application.
991 // In Rust we just always generate a `main` function so we want control
992 // to always start there, so we force the entry point on the windows
993 // subsystem to be `mainCRTStartup` to get everything booted up
996 // For more information see RFC #1665
997 if subsystem == "windows" {
998 self.cmd.arg("/ENTRY:mainCRTStartup");
1002 // MSVC doesn't need group indicators
1003 fn group_start(&mut self) {}
1004 fn group_end(&mut self) {}
1006 fn linker_plugin_lto(&mut self) {
1010 fn add_no_exec(&mut self) {
1011 self.cmd.arg("/NXCOMPAT");
1015 pub struct EmLinker<'a> {
1020 impl<'a> Linker for EmLinker<'a> {
1021 fn cmd(&mut self) -> &mut Command {
1025 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1027 fn include_path(&mut self, path: &Path) {
1028 self.cmd.arg("-L").arg(path);
1031 fn link_staticlib(&mut self, lib: Symbol, _verbatim: bool) {
1032 self.cmd.arg("-l").sym_arg(lib);
1035 fn output_filename(&mut self, path: &Path) {
1036 self.cmd.arg("-o").arg(path);
1039 fn add_object(&mut self, path: &Path) {
1043 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, _as_needed: bool) {
1044 // Emscripten always links statically
1045 self.link_staticlib(lib, verbatim);
1048 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, _search_path: &[PathBuf]) {
1050 self.link_staticlib(lib, verbatim);
1053 fn link_whole_rlib(&mut self, lib: &Path) {
1055 self.link_rlib(lib);
1058 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1059 self.link_dylib(lib, false, true);
1062 fn link_rlib(&mut self, lib: &Path) {
1063 self.add_object(lib);
1066 fn full_relro(&mut self) {
1070 fn partial_relro(&mut self) {
1074 fn no_relro(&mut self) {
1078 fn framework_path(&mut self, _path: &Path) {
1079 bug!("frameworks are not supported on Emscripten")
1082 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1083 bug!("frameworks are not supported on Emscripten")
1086 fn gc_sections(&mut self, _keep_metadata: bool) {
1090 fn no_gc_sections(&mut self) {
1094 fn optimize(&mut self) {
1095 // Emscripten performs own optimizations
1096 self.cmd.arg(match self.sess.opts.optimize {
1097 OptLevel::No => "-O0",
1098 OptLevel::Less => "-O1",
1099 OptLevel::Default => "-O2",
1100 OptLevel::Aggressive => "-O3",
1101 OptLevel::Size => "-Os",
1102 OptLevel::SizeMin => "-Oz",
1104 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
1105 self.cmd.args(&["--memory-init-file", "0"]);
1108 fn pgo_gen(&mut self) {
1109 // noop, but maybe we need something like the gnu linker?
1112 fn control_flow_guard(&mut self) {}
1114 fn debuginfo(&mut self, _strip: Strip) {
1115 // Preserve names or generate source maps depending on debug info
1116 self.cmd.arg(match self.sess.opts.debuginfo {
1117 DebugInfo::None => "-g0",
1118 DebugInfo::Limited => "-g3",
1119 DebugInfo::Full => "-g4",
1123 fn no_crt_objects(&mut self) {}
1125 fn no_default_libraries(&mut self) {
1126 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
1129 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1130 debug!("EXPORTED SYMBOLS:");
1134 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1135 let mut encoded = String::new();
1138 let mut encoder = json::Encoder::new(&mut encoded);
1139 let res = encoder.emit_seq(symbols.len(), |encoder| {
1140 for (i, sym) in symbols.iter().enumerate() {
1141 encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
1145 if let Err(e) = res {
1146 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
1149 debug!("{}", encoded);
1155 fn subsystem(&mut self, _subsystem: &str) {
1159 // Appears not necessary on Emscripten
1160 fn group_start(&mut self) {}
1161 fn group_end(&mut self) {}
1163 fn linker_plugin_lto(&mut self) {
1168 pub struct WasmLd<'a> {
1173 impl<'a> WasmLd<'a> {
1174 fn new(mut cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1175 // If the atomics feature is enabled for wasm then we need a whole bunch
1178 // * `--shared-memory` - the link won't even succeed without this, flags
1179 // the one linear memory as `shared`
1181 // * `--max-memory=1G` - when specifying a shared memory this must also
1182 // be specified. We conservatively choose 1GB but users should be able
1183 // to override this with `-C link-arg`.
1185 // * `--import-memory` - it doesn't make much sense for memory to be
1186 // exported in a threaded module because typically you're
1187 // sharing memory and instantiating the module multiple times. As a
1188 // result if it were exported then we'd just have no sharing.
1190 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
1191 // linker will synthesize this function, and so we need to make sure
1192 // that our usage of `--export` below won't accidentally cause this
1193 // function to get deleted.
1195 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
1196 // symbols are how the TLS segments are initialized and configured.
1197 if sess.target_features.contains(&sym::atomics) {
1198 cmd.arg("--shared-memory");
1199 cmd.arg("--max-memory=1073741824");
1200 cmd.arg("--import-memory");
1201 cmd.arg("--export=__wasm_init_memory");
1202 cmd.arg("--export=__wasm_init_tls");
1203 cmd.arg("--export=__tls_size");
1204 cmd.arg("--export=__tls_align");
1205 cmd.arg("--export=__tls_base");
1207 WasmLd { cmd, sess }
1211 impl<'a> Linker for WasmLd<'a> {
1212 fn cmd(&mut self) -> &mut Command {
1216 fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1218 LinkOutputKind::DynamicNoPicExe
1219 | LinkOutputKind::DynamicPicExe
1220 | LinkOutputKind::StaticNoPicExe
1221 | LinkOutputKind::StaticPicExe => {}
1222 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1223 self.cmd.arg("--no-entry");
1225 LinkOutputKind::WasiReactorExe => {
1226 self.cmd.arg("--entry");
1227 self.cmd.arg("_initialize");
1232 fn link_dylib(&mut self, lib: Symbol, _verbatim: bool, _as_needed: bool) {
1233 self.cmd.arg("-l").sym_arg(lib);
1236 fn link_staticlib(&mut self, lib: Symbol, _verbatim: bool) {
1237 self.cmd.arg("-l").sym_arg(lib);
1240 fn link_rlib(&mut self, lib: &Path) {
1244 fn include_path(&mut self, path: &Path) {
1245 self.cmd.arg("-L").arg(path);
1248 fn framework_path(&mut self, _path: &Path) {
1249 panic!("frameworks not supported")
1252 fn output_filename(&mut self, path: &Path) {
1253 self.cmd.arg("-o").arg(path);
1256 fn add_object(&mut self, path: &Path) {
1260 fn full_relro(&mut self) {}
1262 fn partial_relro(&mut self) {}
1264 fn no_relro(&mut self) {}
1266 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1267 self.cmd.arg("-l").sym_arg(lib);
1270 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1271 panic!("frameworks not supported")
1274 fn link_whole_staticlib(&mut self, lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1275 self.cmd.arg("-l").sym_arg(lib);
1278 fn link_whole_rlib(&mut self, lib: &Path) {
1282 fn gc_sections(&mut self, _keep_metadata: bool) {
1283 self.cmd.arg("--gc-sections");
1286 fn no_gc_sections(&mut self) {
1287 self.cmd.arg("--no-gc-sections");
1290 fn optimize(&mut self) {
1291 self.cmd.arg(match self.sess.opts.optimize {
1292 OptLevel::No => "-O0",
1293 OptLevel::Less => "-O1",
1294 OptLevel::Default => "-O2",
1295 OptLevel::Aggressive => "-O3",
1296 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1298 OptLevel::Size => "-O2",
1299 OptLevel::SizeMin => "-O2",
1303 fn pgo_gen(&mut self) {}
1305 fn debuginfo(&mut self, strip: Strip) {
1308 Strip::Debuginfo => {
1309 self.cmd.arg("--strip-debug");
1312 self.cmd.arg("--strip-all");
1317 fn control_flow_guard(&mut self) {}
1319 fn no_crt_objects(&mut self) {}
1321 fn no_default_libraries(&mut self) {}
1323 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1324 for sym in symbols {
1325 self.cmd.arg("--export").arg(&sym);
1328 // LLD will hide these otherwise-internal symbols since it only exports
1329 // symbols explicity passed via the `--export` flags above and hides all
1330 // others. Various bits and pieces of tooling use this, so be sure these
1331 // symbols make their way out of the linker as well.
1332 self.cmd.arg("--export=__heap_base");
1333 self.cmd.arg("--export=__data_end");
1336 fn subsystem(&mut self, _subsystem: &str) {}
1338 // Not needed for now with LLD
1339 fn group_start(&mut self) {}
1340 fn group_end(&mut self) {}
1342 fn linker_plugin_lto(&mut self) {
1343 // Do nothing for now
1347 pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1348 if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1349 return exports.clone();
1352 let mut symbols = Vec::new();
1354 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1355 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1356 if level.is_below_threshold(export_threshold) {
1357 symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1365 let formats = tcx.dependency_formats(());
1366 let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1368 for (index, dep_format) in deps.iter().enumerate() {
1369 let cnum = CrateNum::new(index + 1);
1370 // For each dependency that we are linking to statically ...
1371 if *dep_format == Linkage::Static {
1372 // ... we add its symbol list to our export list.
1373 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1374 if !level.is_below_threshold(export_threshold) {
1378 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1386 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1387 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1388 pub struct PtxLinker<'a> {
1393 impl<'a> Linker for PtxLinker<'a> {
1394 fn cmd(&mut self) -> &mut Command {
1398 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1400 fn link_rlib(&mut self, path: &Path) {
1401 self.cmd.arg("--rlib").arg(path);
1404 fn link_whole_rlib(&mut self, path: &Path) {
1405 self.cmd.arg("--rlib").arg(path);
1408 fn include_path(&mut self, path: &Path) {
1409 self.cmd.arg("-L").arg(path);
1412 fn debuginfo(&mut self, _strip: Strip) {
1413 self.cmd.arg("--debug");
1416 fn add_object(&mut self, path: &Path) {
1417 self.cmd.arg("--bitcode").arg(path);
1420 fn optimize(&mut self) {
1421 match self.sess.lto() {
1422 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1423 self.cmd.arg("-Olto");
1430 fn output_filename(&mut self, path: &Path) {
1431 self.cmd.arg("-o").arg(path);
1434 fn link_dylib(&mut self, _lib: Symbol, _verbatim: bool, _as_needed: bool) {
1435 panic!("external dylibs not supported")
1438 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1439 panic!("external dylibs not supported")
1442 fn link_staticlib(&mut self, _lib: Symbol, _verbatim: bool) {
1443 panic!("staticlibs not supported")
1446 fn link_whole_staticlib(&mut self, _lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1447 panic!("staticlibs not supported")
1450 fn framework_path(&mut self, _path: &Path) {
1451 panic!("frameworks not supported")
1454 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1455 panic!("frameworks not supported")
1458 fn full_relro(&mut self) {}
1460 fn partial_relro(&mut self) {}
1462 fn no_relro(&mut self) {}
1464 fn gc_sections(&mut self, _keep_metadata: bool) {}
1466 fn no_gc_sections(&mut self) {}
1468 fn pgo_gen(&mut self) {}
1470 fn no_crt_objects(&mut self) {}
1472 fn no_default_libraries(&mut self) {}
1474 fn control_flow_guard(&mut self) {}
1476 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, _symbols: &[String]) {}
1478 fn subsystem(&mut self, _subsystem: &str) {}
1480 fn group_start(&mut self) {}
1482 fn group_end(&mut self) {}
1484 fn linker_plugin_lto(&mut self) {}
1487 pub struct BpfLinker<'a> {
1492 impl<'a> Linker for BpfLinker<'a> {
1493 fn cmd(&mut self) -> &mut Command {
1497 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1499 fn link_rlib(&mut self, path: &Path) {
1503 fn link_whole_rlib(&mut self, path: &Path) {
1507 fn include_path(&mut self, path: &Path) {
1508 self.cmd.arg("-L").arg(path);
1511 fn debuginfo(&mut self, _strip: Strip) {
1512 self.cmd.arg("--debug");
1515 fn add_object(&mut self, path: &Path) {
1519 fn optimize(&mut self) {
1520 self.cmd.arg(match self.sess.opts.optimize {
1521 OptLevel::No => "-O0",
1522 OptLevel::Less => "-O1",
1523 OptLevel::Default => "-O2",
1524 OptLevel::Aggressive => "-O3",
1525 OptLevel::Size => "-Os",
1526 OptLevel::SizeMin => "-Oz",
1530 fn output_filename(&mut self, path: &Path) {
1531 self.cmd.arg("-o").arg(path);
1534 fn link_dylib(&mut self, _lib: Symbol, _verbatim: bool, _as_needed: bool) {
1535 panic!("external dylibs not supported")
1538 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1539 panic!("external dylibs not supported")
1542 fn link_staticlib(&mut self, _lib: Symbol, _verbatim: bool) {
1543 panic!("staticlibs not supported")
1546 fn link_whole_staticlib(&mut self, _lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1547 panic!("staticlibs not supported")
1550 fn framework_path(&mut self, _path: &Path) {
1551 panic!("frameworks not supported")
1554 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1555 panic!("frameworks not supported")
1558 fn full_relro(&mut self) {}
1560 fn partial_relro(&mut self) {}
1562 fn no_relro(&mut self) {}
1564 fn gc_sections(&mut self, _keep_metadata: bool) {}
1566 fn no_gc_sections(&mut self) {}
1568 fn pgo_gen(&mut self) {}
1570 fn no_crt_objects(&mut self) {}
1572 fn no_default_libraries(&mut self) {}
1574 fn control_flow_guard(&mut self) {}
1576 fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1577 let path = tmpdir.join("symbols");
1578 let res: io::Result<()> = try {
1579 let mut f = BufWriter::new(File::create(&path)?);
1580 for sym in symbols {
1581 writeln!(f, "{}", sym)?;
1584 if let Err(e) = res {
1585 self.sess.fatal(&format!("failed to write symbols file: {}", e));
1587 self.cmd.arg("--export-symbols").arg(&path);
1591 fn subsystem(&mut self, _subsystem: &str) {}
1593 fn group_start(&mut self) {}
1595 fn group_end(&mut self) {}
1597 fn linker_plugin_lto(&mut self) {}