2 use super::command::Command;
3 use super::symbol_export;
5 use std::ffi::{OsStr, OsString};
6 use std::fs::{self, File};
7 use std::io::prelude::*;
8 use std::io::{self, BufWriter};
9 use std::path::{Path, PathBuf};
11 use rustc::middle::dependency_format::Linkage;
12 use rustc::ty::TyCtxt;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
15 use rustc_serialize::{json, Encoder};
16 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
17 use rustc_session::Session;
18 use rustc_span::symbol::Symbol;
19 use rustc_target::spec::{LinkerFlavor, LldFlavor};
21 /// For all the linkers we support, and information they might
22 /// need out of the shared crate context before we get rid of it.
23 #[derive(RustcEncodable, RustcDecodable)]
24 pub struct LinkerInfo {
25 exports: FxHashMap<CrateType, Vec<String>>,
29 pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
36 .map(|&c| (c, exported_symbols(tcx, c)))
47 ) -> Box<dyn Linker + 'a> {
49 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
50 Box::new(MsvcLinker { cmd, sess, info: self }) as Box<dyn Linker>
52 LinkerFlavor::Em => Box::new(EmLinker { cmd, sess, info: self }) as Box<dyn Linker>,
53 LinkerFlavor::Gcc => Box::new(GccLinker {
60 }) as Box<dyn Linker>,
62 LinkerFlavor::Lld(LldFlavor::Ld)
63 | LinkerFlavor::Lld(LldFlavor::Ld64)
64 | LinkerFlavor::Ld => Box::new(GccLinker {
71 }) as Box<dyn Linker>,
73 LinkerFlavor::Lld(LldFlavor::Wasm) => {
74 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
77 LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
82 /// Linker abstraction used by `back::link` to build up the command to invoke a
85 /// This trait is the total list of requirements needed by `back::link` and
86 /// represents the meaning of each option being passed down. This trait is then
87 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
88 /// MSVC linker (e.g., `link.exe`) is being used.
90 fn link_dylib(&mut self, lib: Symbol);
91 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
92 fn link_framework(&mut self, framework: Symbol);
93 fn link_staticlib(&mut self, lib: Symbol);
94 fn link_rlib(&mut self, lib: &Path);
95 fn link_whole_rlib(&mut self, lib: &Path);
96 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]);
97 fn include_path(&mut self, path: &Path);
98 fn framework_path(&mut self, path: &Path);
99 fn output_filename(&mut self, path: &Path);
100 fn add_object(&mut self, path: &Path);
101 fn gc_sections(&mut self, keep_metadata: bool);
102 fn position_independent_executable(&mut self);
103 fn no_position_independent_executable(&mut self);
104 fn full_relro(&mut self);
105 fn partial_relro(&mut self);
106 fn no_relro(&mut self);
107 fn optimize(&mut self);
108 fn pgo_gen(&mut self);
109 fn control_flow_guard(&mut self);
110 fn debuginfo(&mut self);
111 fn no_default_libraries(&mut self);
112 fn build_dylib(&mut self, out_filename: &Path);
113 fn build_static_executable(&mut self);
114 fn args(&mut self, args: &[String]);
115 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
116 fn subsystem(&mut self, subsystem: &str);
117 fn group_start(&mut self);
118 fn group_end(&mut self);
119 fn linker_plugin_lto(&mut self);
120 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
121 fn finalize(&mut self) -> Command;
124 pub struct GccLinker<'a> {
127 info: &'a LinkerInfo,
128 hinted_static: bool, // Keeps track of the current hinting mode.
134 impl<'a> GccLinker<'a> {
135 /// Argument that must be passed *directly* to the linker
137 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
138 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
143 let mut os = OsString::from("-Wl,");
144 os.push(arg.as_ref());
152 fn takes_hints(&self) -> bool {
153 // Really this function only returns true if the underlying linker
154 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
155 // don't really have a foolproof way to detect that, so rule out some
156 // platforms where currently this is guaranteed to *not* be the case:
158 // * On OSX they have their own linker, not binutils'
159 // * For WebAssembly the only functional linker is LLD, which doesn't
160 // support hint flags
161 !self.sess.target.target.options.is_like_osx && self.sess.target.target.arch != "wasm32"
164 // Some platforms take hints about whether a library is static or dynamic.
165 // For those that support this, we ensure we pass the option if the library
166 // was flagged "static" (most defaults are dynamic) to ensure that if
167 // libfoo.a and libfoo.so both exist that the right one is chosen.
168 fn hint_static(&mut self) {
169 if !self.takes_hints() {
172 if !self.hinted_static {
173 self.linker_arg("-Bstatic");
174 self.hinted_static = true;
178 fn hint_dynamic(&mut self) {
179 if !self.takes_hints() {
182 if self.hinted_static {
183 self.linker_arg("-Bdynamic");
184 self.hinted_static = false;
188 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
189 if let Some(plugin_path) = plugin_path {
190 let mut arg = OsString::from("-plugin=");
191 arg.push(plugin_path);
192 self.linker_arg(&arg);
195 let opt_level = match self.sess.opts.optimize {
196 config::OptLevel::No => "O0",
197 config::OptLevel::Less => "O1",
198 config::OptLevel::Default => "O2",
199 config::OptLevel::Aggressive => "O3",
200 config::OptLevel::Size => "Os",
201 config::OptLevel::SizeMin => "Oz",
204 self.linker_arg(&format!("-plugin-opt={}", opt_level));
205 let target_cpu = self.target_cpu;
206 self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
210 impl<'a> Linker for GccLinker<'a> {
211 fn link_dylib(&mut self, lib: Symbol) {
213 self.cmd.arg(format!("-l{}", lib));
215 fn link_staticlib(&mut self, lib: Symbol) {
217 self.cmd.arg(format!("-l{}", lib));
219 fn link_rlib(&mut self, lib: &Path) {
223 fn include_path(&mut self, path: &Path) {
224 self.cmd.arg("-L").arg(path);
226 fn framework_path(&mut self, path: &Path) {
227 self.cmd.arg("-F").arg(path);
229 fn output_filename(&mut self, path: &Path) {
230 self.cmd.arg("-o").arg(path);
232 fn add_object(&mut self, path: &Path) {
235 fn position_independent_executable(&mut self) {
236 self.cmd.arg("-pie");
238 fn no_position_independent_executable(&mut self) {
239 self.cmd.arg("-no-pie");
241 fn full_relro(&mut self) {
242 self.linker_arg("-zrelro");
243 self.linker_arg("-znow");
245 fn partial_relro(&mut self) {
246 self.linker_arg("-zrelro");
248 fn no_relro(&mut self) {
249 self.linker_arg("-znorelro");
251 fn build_static_executable(&mut self) {
252 self.cmd.arg("-static");
254 fn args(&mut self, args: &[String]) {
258 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
260 self.cmd.arg(format!("-l{}", lib));
263 fn link_framework(&mut self, framework: Symbol) {
265 self.cmd.arg("-framework").sym_arg(framework);
268 // Here we explicitly ask that the entire archive is included into the
269 // result artifact. For more details see #15460, but the gist is that
270 // the linker will strip away any unused objects in the archive if we
271 // don't otherwise explicitly reference them. This can occur for
272 // libraries which are just providing bindings, libraries with generic
274 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
276 let target = &self.sess.target.target;
277 if !target.options.is_like_osx {
278 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
279 self.linker_arg("--no-whole-archive");
281 // -force_load is the macOS equivalent of --whole-archive, but it
282 // involves passing the full path to the library to link.
283 self.linker_arg("-force_load");
284 let lib = archive::find_library(lib, search_path, &self.sess);
285 self.linker_arg(&lib);
289 fn link_whole_rlib(&mut self, lib: &Path) {
291 if self.sess.target.target.options.is_like_osx {
292 self.linker_arg("-force_load");
293 self.linker_arg(&lib);
295 self.linker_arg("--whole-archive").cmd.arg(lib);
296 self.linker_arg("--no-whole-archive");
300 fn gc_sections(&mut self, keep_metadata: bool) {
301 // The dead_strip option to the linker specifies that functions and data
302 // unreachable by the entry point will be removed. This is quite useful
303 // with Rust's compilation model of compiling libraries at a time into
304 // one object file. For example, this brings hello world from 1.7MB to
307 // Note that this is done for both executables and dynamic libraries. We
308 // won't get much benefit from dylibs because LLVM will have already
309 // stripped away as much as it could. This has not been seen to impact
310 // link times negatively.
312 // -dead_strip can't be part of the pre_link_args because it's also used
313 // for partial linking when using multiple codegen units (-r). So we
315 if self.sess.target.target.options.is_like_osx {
316 self.linker_arg("-dead_strip");
317 } else if self.sess.target.target.options.is_like_solaris {
318 self.linker_arg("-zignore");
320 // If we're building a dylib, we don't use --gc-sections because LLVM
321 // has already done the best it can do, and we also don't want to
322 // eliminate the metadata. If we're building an executable, however,
323 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
325 } else if !keep_metadata {
326 self.linker_arg("--gc-sections");
330 fn optimize(&mut self) {
331 if !self.sess.target.target.options.linker_is_gnu {
335 // GNU-style linkers support optimization with -O. GNU ld doesn't
336 // need a numeric argument, but other linkers do.
337 if self.sess.opts.optimize == config::OptLevel::Default
338 || self.sess.opts.optimize == config::OptLevel::Aggressive
340 self.linker_arg("-O1");
344 fn pgo_gen(&mut self) {
345 if !self.sess.target.target.options.linker_is_gnu {
349 // If we're doing PGO generation stuff and on a GNU-like linker, use the
350 // "-u" flag to properly pull in the profiler runtime bits.
352 // This is because LLVM otherwise won't add the needed initialization
353 // for us on Linux (though the extra flag should be harmless if it
356 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
358 // Though it may be worth to try to revert those changes upstream, since
359 // the overhead of the initialization should be minor.
361 self.cmd.arg("__llvm_profile_runtime");
364 fn control_flow_guard(&mut self) {
365 self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
368 fn debuginfo(&mut self) {
369 if let DebugInfo::None = self.sess.opts.debuginfo {
370 // If we are building without debuginfo enabled and we were called with
371 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
372 // found when linking to get rid of symbols from libstd.
373 if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
374 self.linker_arg("-S");
379 fn no_default_libraries(&mut self) {
381 self.cmd.arg("-nodefaultlibs");
385 fn build_dylib(&mut self, out_filename: &Path) {
386 // On mac we need to tell the linker to let this library be rpathed
387 if self.sess.target.target.options.is_like_osx {
388 self.cmd.arg("-dynamiclib");
389 self.linker_arg("-dylib");
391 // Note that the `osx_rpath_install_name` option here is a hack
392 // purely to support rustbuild right now, we should get a more
393 // principled solution at some point to force the compiler to pass
394 // the right `-Wl,-install_name` with an `@rpath` in it.
395 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
396 self.linker_arg("-install_name");
397 let mut v = OsString::from("@rpath/");
398 v.push(out_filename.file_name().unwrap());
402 self.cmd.arg("-shared");
403 if self.sess.target.target.options.is_like_windows {
404 // The output filename already contains `dll_suffix` so
405 // the resulting import library will have a name in the
406 // form of libfoo.dll.a
408 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
411 self.sess.target.target.options.staticlib_prefix,
413 self.sess.target.target.options.staticlib_suffix
416 if let Some(implib_name) = implib_name {
417 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
418 if let Some(implib) = implib {
419 self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
426 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
427 // Symbol visibility in object files typically takes care of this.
428 if crate_type == CrateType::Executable
429 && self.sess.target.target.options.override_export_symbols.is_none()
434 // We manually create a list of exported symbols to ensure we don't expose any more.
435 // The object files have far more public symbols than we actually want to export,
436 // so we hide them all here.
438 if !self.sess.target.target.options.limit_rdylib_exports {
442 if crate_type == CrateType::ProcMacro {
446 let mut arg = OsString::new();
447 let path = tmpdir.join("list");
449 debug!("EXPORTED SYMBOLS:");
451 if self.sess.target.target.options.is_like_osx {
452 // Write a plain, newline-separated list of symbols
453 let res: io::Result<()> = try {
454 let mut f = BufWriter::new(File::create(&path)?);
455 for sym in self.info.exports[&crate_type].iter() {
457 writeln!(f, "_{}", sym)?;
460 if let Err(e) = res {
461 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
464 // Write an LD version script
465 let res: io::Result<()> = try {
466 let mut f = BufWriter::new(File::create(&path)?);
468 if !self.info.exports[&crate_type].is_empty() {
469 writeln!(f, " global:")?;
470 for sym in self.info.exports[&crate_type].iter() {
472 writeln!(f, " {};", sym)?;
475 writeln!(f, "\n local:\n *;\n}};")?;
477 if let Err(e) = res {
478 self.sess.fatal(&format!("failed to write version script: {}", e));
482 if self.sess.target.target.options.is_like_osx {
486 arg.push("-exported_symbols_list,");
487 } else if self.sess.target.target.options.is_like_solaris {
496 arg.push("--version-script=");
503 fn subsystem(&mut self, subsystem: &str) {
504 self.linker_arg("--subsystem");
505 self.linker_arg(&subsystem);
508 fn finalize(&mut self) -> Command {
509 self.hint_dynamic(); // Reset to default before returning the composed command line.
511 ::std::mem::replace(&mut self.cmd, Command::new(""))
514 fn group_start(&mut self) {
515 if self.takes_hints() {
516 self.linker_arg("--start-group");
520 fn group_end(&mut self) {
521 if self.takes_hints() {
522 self.linker_arg("--end-group");
526 fn linker_plugin_lto(&mut self) {
527 match self.sess.opts.cg.linker_plugin_lto {
528 LinkerPluginLto::Disabled => {
531 LinkerPluginLto::LinkerPluginAuto => {
532 self.push_linker_plugin_lto_args(None);
534 LinkerPluginLto::LinkerPlugin(ref path) => {
535 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
541 pub struct MsvcLinker<'a> {
544 info: &'a LinkerInfo,
547 impl<'a> Linker for MsvcLinker<'a> {
548 fn link_rlib(&mut self, lib: &Path) {
551 fn add_object(&mut self, path: &Path) {
554 fn args(&mut self, args: &[String]) {
558 fn build_dylib(&mut self, out_filename: &Path) {
559 self.cmd.arg("/DLL");
560 let mut arg: OsString = "/IMPLIB:".into();
561 arg.push(out_filename.with_extension("dll.lib"));
565 fn build_static_executable(&mut self) {
569 fn gc_sections(&mut self, _keep_metadata: bool) {
570 // MSVC's ICF (Identical COMDAT Folding) link optimization is
571 // slow for Rust and thus we disable it by default when not in
572 // optimization build.
573 if self.sess.opts.optimize != config::OptLevel::No {
574 self.cmd.arg("/OPT:REF,ICF");
576 // It is necessary to specify NOICF here, because /OPT:REF
577 // implies ICF by default.
578 self.cmd.arg("/OPT:REF,NOICF");
582 fn link_dylib(&mut self, lib: Symbol) {
583 self.cmd.arg(&format!("{}.lib", lib));
586 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
587 // When producing a dll, the MSVC linker may not actually emit a
588 // `foo.lib` file if the dll doesn't actually export any symbols, so we
589 // check to see if the file is there and just omit linking to it if it's
591 let name = format!("{}.dll.lib", lib);
592 if fs::metadata(&path.join(&name)).is_ok() {
597 fn link_staticlib(&mut self, lib: Symbol) {
598 self.cmd.arg(&format!("{}.lib", lib));
601 fn position_independent_executable(&mut self) {
605 fn no_position_independent_executable(&mut self) {
609 fn full_relro(&mut self) {
613 fn partial_relro(&mut self) {
617 fn no_relro(&mut self) {
621 fn no_default_libraries(&mut self) {
622 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
623 // as there's been trouble in the past of linking the C++ standard
624 // library required by LLVM. This likely needs to happen one day, but
625 // in general Windows is also a more controlled environment than
626 // Unix, so it's not necessarily as critical that this be implemented.
628 // Note that there are also some licensing worries about statically
629 // linking some libraries which require a specific agreement, so it may
630 // not ever be possible for us to pass this flag.
633 fn include_path(&mut self, path: &Path) {
634 let mut arg = OsString::from("/LIBPATH:");
639 fn output_filename(&mut self, path: &Path) {
640 let mut arg = OsString::from("/OUT:");
645 fn framework_path(&mut self, _path: &Path) {
646 bug!("frameworks are not supported on windows")
648 fn link_framework(&mut self, _framework: Symbol) {
649 bug!("frameworks are not supported on windows")
652 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
654 self.link_staticlib(lib);
656 fn link_whole_rlib(&mut self, path: &Path) {
658 self.link_rlib(path);
660 fn optimize(&mut self) {
661 // Needs more investigation of `/OPT` arguments
664 fn pgo_gen(&mut self) {
665 // Nothing needed here.
668 fn control_flow_guard(&mut self) {
669 self.cmd.arg("/guard:cf");
672 fn debuginfo(&mut self) {
673 // This will cause the Microsoft linker to generate a PDB file
674 // from the CodeView line tables in the object files.
675 self.cmd.arg("/DEBUG");
677 // This will cause the Microsoft linker to embed .natvis info into the PDB file
678 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
679 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
680 for entry in natvis_dir {
683 let path = entry.path();
684 if path.extension() == Some("natvis".as_ref()) {
685 let mut arg = OsString::from("/NATVIS:");
691 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
698 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
699 // export symbols from a dynamic library. When building a dynamic library,
700 // however, we're going to want some symbols exported, so this function
701 // generates a DEF file which lists all the symbols.
703 // The linker will read this `*.def` file and export all the symbols from
704 // the dynamic library. Note that this is not as simple as just exporting
705 // all the symbols in the current crate (as specified by `codegen.reachable`)
706 // but rather we also need to possibly export the symbols of upstream
707 // crates. Upstream rlibs may be linked statically to this dynamic library,
708 // in which case they may continue to transitively be used and hence need
709 // their symbols exported.
710 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
711 // Symbol visibility takes care of this typically
712 if crate_type == CrateType::Executable {
716 let path = tmpdir.join("lib.def");
717 let res: io::Result<()> = try {
718 let mut f = BufWriter::new(File::create(&path)?);
720 // Start off with the standard module name header and then go
721 // straight to exports.
722 writeln!(f, "LIBRARY")?;
723 writeln!(f, "EXPORTS")?;
724 for symbol in self.info.exports[&crate_type].iter() {
725 debug!(" _{}", symbol);
726 writeln!(f, " {}", symbol)?;
729 if let Err(e) = res {
730 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
732 let mut arg = OsString::from("/DEF:");
737 fn subsystem(&mut self, subsystem: &str) {
738 // Note that previous passes of the compiler validated this subsystem,
739 // so we just blindly pass it to the linker.
740 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
742 // Windows has two subsystems we're interested in right now, the console
743 // and windows subsystems. These both implicitly have different entry
744 // points (starting symbols). The console entry point starts with
745 // `mainCRTStartup` and the windows entry point starts with
746 // `WinMainCRTStartup`. These entry points, defined in system libraries,
747 // will then later probe for either `main` or `WinMain`, respectively to
748 // start the application.
750 // In Rust we just always generate a `main` function so we want control
751 // to always start there, so we force the entry point on the windows
752 // subsystem to be `mainCRTStartup` to get everything booted up
755 // For more information see RFC #1665
756 if subsystem == "windows" {
757 self.cmd.arg("/ENTRY:mainCRTStartup");
761 fn finalize(&mut self) -> Command {
762 ::std::mem::replace(&mut self.cmd, Command::new(""))
765 // MSVC doesn't need group indicators
766 fn group_start(&mut self) {}
767 fn group_end(&mut self) {}
769 fn linker_plugin_lto(&mut self) {
774 pub struct EmLinker<'a> {
777 info: &'a LinkerInfo,
780 impl<'a> Linker for EmLinker<'a> {
781 fn include_path(&mut self, path: &Path) {
782 self.cmd.arg("-L").arg(path);
785 fn link_staticlib(&mut self, lib: Symbol) {
786 self.cmd.arg("-l").sym_arg(lib);
789 fn output_filename(&mut self, path: &Path) {
790 self.cmd.arg("-o").arg(path);
793 fn add_object(&mut self, path: &Path) {
797 fn link_dylib(&mut self, lib: Symbol) {
798 // Emscripten always links statically
799 self.link_staticlib(lib);
802 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
804 self.link_staticlib(lib);
807 fn link_whole_rlib(&mut self, lib: &Path) {
812 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
813 self.link_dylib(lib);
816 fn link_rlib(&mut self, lib: &Path) {
817 self.add_object(lib);
820 fn position_independent_executable(&mut self) {
824 fn no_position_independent_executable(&mut self) {
828 fn full_relro(&mut self) {
832 fn partial_relro(&mut self) {
836 fn no_relro(&mut self) {
840 fn args(&mut self, args: &[String]) {
844 fn framework_path(&mut self, _path: &Path) {
845 bug!("frameworks are not supported on Emscripten")
848 fn link_framework(&mut self, _framework: Symbol) {
849 bug!("frameworks are not supported on Emscripten")
852 fn gc_sections(&mut self, _keep_metadata: bool) {
856 fn optimize(&mut self) {
857 // Emscripten performs own optimizations
858 self.cmd.arg(match self.sess.opts.optimize {
859 OptLevel::No => "-O0",
860 OptLevel::Less => "-O1",
861 OptLevel::Default => "-O2",
862 OptLevel::Aggressive => "-O3",
863 OptLevel::Size => "-Os",
864 OptLevel::SizeMin => "-Oz",
866 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
867 self.cmd.args(&["--memory-init-file", "0"]);
870 fn pgo_gen(&mut self) {
871 // noop, but maybe we need something like the gnu linker?
874 fn control_flow_guard(&mut self) {
875 self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
878 fn debuginfo(&mut self) {
879 // Preserve names or generate source maps depending on debug info
880 self.cmd.arg(match self.sess.opts.debuginfo {
881 DebugInfo::None => "-g0",
882 DebugInfo::Limited => "-g3",
883 DebugInfo::Full => "-g4",
887 fn no_default_libraries(&mut self) {
888 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
891 fn build_dylib(&mut self, _out_filename: &Path) {
892 bug!("building dynamic library is unsupported on Emscripten")
895 fn build_static_executable(&mut self) {
899 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
900 let symbols = &self.info.exports[&crate_type];
902 debug!("EXPORTED SYMBOLS:");
906 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
907 let mut encoded = String::new();
910 let mut encoder = json::Encoder::new(&mut encoded);
911 let res = encoder.emit_seq(symbols.len(), |encoder| {
912 for (i, sym) in symbols.iter().enumerate() {
913 encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
917 if let Err(e) = res {
918 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
921 debug!("{}", encoded);
927 fn subsystem(&mut self, _subsystem: &str) {
931 fn finalize(&mut self) -> Command {
932 ::std::mem::replace(&mut self.cmd, Command::new(""))
935 // Appears not necessary on Emscripten
936 fn group_start(&mut self) {}
937 fn group_end(&mut self) {}
939 fn linker_plugin_lto(&mut self) {
944 pub struct WasmLd<'a> {
947 info: &'a LinkerInfo,
950 impl<'a> WasmLd<'a> {
951 fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
952 // If the atomics feature is enabled for wasm then we need a whole bunch
955 // * `--shared-memory` - the link won't even succeed without this, flags
956 // the one linear memory as `shared`
958 // * `--max-memory=1G` - when specifying a shared memory this must also
959 // be specified. We conservatively choose 1GB but users should be able
960 // to override this with `-C link-arg`.
962 // * `--import-memory` - it doesn't make much sense for memory to be
963 // exported in a threaded module because typically you're
964 // sharing memory and instantiating the module multiple times. As a
965 // result if it were exported then we'd just have no sharing.
967 // * `--passive-segments` - all memory segments should be passive to
968 // prevent each module instantiation from reinitializing memory.
970 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
971 // linker will synthesize this function, and so we need to make sure
972 // that our usage of `--export` below won't accidentally cause this
973 // function to get deleted.
975 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
976 // symbols are how the TLS segments are initialized and configured.
977 let atomics = sess.opts.cg.target_feature.contains("+atomics")
978 || sess.target.target.options.features.contains("+atomics");
980 cmd.arg("--shared-memory");
981 cmd.arg("--max-memory=1073741824");
982 cmd.arg("--import-memory");
983 cmd.arg("--passive-segments");
984 cmd.arg("--export=__wasm_init_memory");
985 cmd.arg("--export=__wasm_init_tls");
986 cmd.arg("--export=__tls_size");
987 cmd.arg("--export=__tls_align");
988 cmd.arg("--export=__tls_base");
990 WasmLd { cmd, sess, info }
994 impl<'a> Linker for WasmLd<'a> {
995 fn link_dylib(&mut self, lib: Symbol) {
996 self.cmd.arg("-l").sym_arg(lib);
999 fn link_staticlib(&mut self, lib: Symbol) {
1000 self.cmd.arg("-l").sym_arg(lib);
1003 fn link_rlib(&mut self, lib: &Path) {
1007 fn include_path(&mut self, path: &Path) {
1008 self.cmd.arg("-L").arg(path);
1011 fn framework_path(&mut self, _path: &Path) {
1012 panic!("frameworks not supported")
1015 fn output_filename(&mut self, path: &Path) {
1016 self.cmd.arg("-o").arg(path);
1019 fn add_object(&mut self, path: &Path) {
1023 fn position_independent_executable(&mut self) {}
1025 fn full_relro(&mut self) {}
1027 fn partial_relro(&mut self) {}
1029 fn no_relro(&mut self) {}
1031 fn build_static_executable(&mut self) {}
1033 fn args(&mut self, args: &[String]) {
1034 self.cmd.args(args);
1037 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1038 self.cmd.arg("-l").sym_arg(lib);
1041 fn link_framework(&mut self, _framework: Symbol) {
1042 panic!("frameworks not supported")
1045 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1046 self.cmd.arg("-l").sym_arg(lib);
1049 fn link_whole_rlib(&mut self, lib: &Path) {
1053 fn gc_sections(&mut self, _keep_metadata: bool) {
1054 self.cmd.arg("--gc-sections");
1057 fn optimize(&mut self) {
1058 self.cmd.arg(match self.sess.opts.optimize {
1059 OptLevel::No => "-O0",
1060 OptLevel::Less => "-O1",
1061 OptLevel::Default => "-O2",
1062 OptLevel::Aggressive => "-O3",
1063 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1065 OptLevel::Size => "-O2",
1066 OptLevel::SizeMin => "-O2",
1070 fn pgo_gen(&mut self) {}
1072 fn debuginfo(&mut self) {}
1074 fn control_flow_guard(&mut self) {
1075 self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
1078 fn no_default_libraries(&mut self) {}
1080 fn build_dylib(&mut self, _out_filename: &Path) {
1081 self.cmd.arg("--no-entry");
1084 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1085 for sym in self.info.exports[&crate_type].iter() {
1086 self.cmd.arg("--export").arg(&sym);
1089 // LLD will hide these otherwise-internal symbols since our `--export`
1090 // list above is a whitelist of what to export. Various bits and pieces
1091 // of tooling use this, so be sure these symbols make their way out of
1092 // the linker as well.
1093 self.cmd.arg("--export=__heap_base");
1094 self.cmd.arg("--export=__data_end");
1097 fn subsystem(&mut self, _subsystem: &str) {}
1099 fn no_position_independent_executable(&mut self) {}
1101 fn finalize(&mut self) -> Command {
1102 ::std::mem::replace(&mut self.cmd, Command::new(""))
1105 // Not needed for now with LLD
1106 fn group_start(&mut self) {}
1107 fn group_end(&mut self) {}
1109 fn linker_plugin_lto(&mut self) {
1110 // Do nothing for now
1114 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1115 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1116 return exports.clone();
1119 let mut symbols = Vec::new();
1121 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1122 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1123 if level.is_below_threshold(export_threshold) {
1124 symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1132 let formats = tcx.dependency_formats(LOCAL_CRATE);
1135 .filter_map(|(t, list)| if *t == crate_type { Some(list) } else { None })
1139 for (index, dep_format) in deps.iter().enumerate() {
1140 let cnum = CrateNum::new(index + 1);
1141 // For each dependency that we are linking to statically ...
1142 if *dep_format == Linkage::Static {
1143 // ... we add its symbol list to our export list.
1144 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1145 if !level.is_below_threshold(export_threshold) {
1149 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1157 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1158 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1159 pub struct PtxLinker<'a> {
1164 impl<'a> Linker for PtxLinker<'a> {
1165 fn link_rlib(&mut self, path: &Path) {
1166 self.cmd.arg("--rlib").arg(path);
1169 fn link_whole_rlib(&mut self, path: &Path) {
1170 self.cmd.arg("--rlib").arg(path);
1173 fn include_path(&mut self, path: &Path) {
1174 self.cmd.arg("-L").arg(path);
1177 fn debuginfo(&mut self) {
1178 self.cmd.arg("--debug");
1181 fn add_object(&mut self, path: &Path) {
1182 self.cmd.arg("--bitcode").arg(path);
1185 fn args(&mut self, args: &[String]) {
1186 self.cmd.args(args);
1189 fn optimize(&mut self) {
1190 match self.sess.lto() {
1191 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1192 self.cmd.arg("-Olto");
1199 fn output_filename(&mut self, path: &Path) {
1200 self.cmd.arg("-o").arg(path);
1203 fn finalize(&mut self) -> Command {
1204 // Provide the linker with fallback to internal `target-cpu`.
1205 self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1207 None => &self.sess.target.target.options.cpu,
1210 ::std::mem::replace(&mut self.cmd, Command::new(""))
1213 fn link_dylib(&mut self, _lib: Symbol) {
1214 panic!("external dylibs not supported")
1217 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1218 panic!("external dylibs not supported")
1221 fn link_staticlib(&mut self, _lib: Symbol) {
1222 panic!("staticlibs not supported")
1225 fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1226 panic!("staticlibs not supported")
1229 fn framework_path(&mut self, _path: &Path) {
1230 panic!("frameworks not supported")
1233 fn link_framework(&mut self, _framework: Symbol) {
1234 panic!("frameworks not supported")
1237 fn position_independent_executable(&mut self) {}
1239 fn full_relro(&mut self) {}
1241 fn partial_relro(&mut self) {}
1243 fn no_relro(&mut self) {}
1245 fn build_static_executable(&mut self) {}
1247 fn gc_sections(&mut self, _keep_metadata: bool) {}
1249 fn pgo_gen(&mut self) {}
1251 fn no_default_libraries(&mut self) {}
1253 fn control_flow_guard(&mut self) {
1254 self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
1257 fn build_dylib(&mut self, _out_filename: &Path) {}
1259 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {}
1261 fn subsystem(&mut self, _subsystem: &str) {}
1263 fn no_position_independent_executable(&mut self) {}
1265 fn group_start(&mut self) {}
1267 fn group_end(&mut self) {}
1269 fn linker_plugin_lto(&mut self) {}