1 use super::symbol_export;
2 use super::command::Command;
5 use rustc_data_structures::fx::FxHashMap;
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};
12 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
13 use rustc::middle::dependency_format::Linkage;
14 use rustc::session::Session;
15 use rustc::session::config::{self, CrateType, OptLevel, DebugInfo,
16 LinkerPluginLto, Lto};
17 use rustc::ty::TyCtxt;
18 use rustc_target::spec::{LinkerFlavor, LldFlavor};
19 use rustc_serialize::{json, Encoder};
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 pub struct LinkerInfo {
24 exports: FxHashMap<CrateType, Vec<String>>,
28 pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
30 exports: tcx.sess.crate_types.borrow().iter().map(|&c| {
31 (c, exported_symbols(tcx, c))
42 ) -> Box<dyn Linker+'a> {
44 LinkerFlavor::Lld(LldFlavor::Link) |
45 LinkerFlavor::Msvc => {
59 LinkerFlavor::Gcc => {
70 LinkerFlavor::Lld(LldFlavor::Ld) |
71 LinkerFlavor::Lld(LldFlavor::Ld64) |
83 LinkerFlavor::Lld(LldFlavor::Wasm) => {
84 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
87 LinkerFlavor::PtxLinker => {
88 Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>
94 /// Linker abstraction used by `back::link` to build up the command to invoke a
97 /// This trait is the total list of requirements needed by `back::link` and
98 /// represents the meaning of each option being passed down. This trait is then
99 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
100 /// MSVC linker (e.g., `link.exe`) is being used.
102 fn link_dylib(&mut self, lib: &str);
103 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
104 fn link_framework(&mut self, framework: &str);
105 fn link_staticlib(&mut self, lib: &str);
106 fn link_rlib(&mut self, lib: &Path);
107 fn link_whole_rlib(&mut self, lib: &Path);
108 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
109 fn include_path(&mut self, path: &Path);
110 fn framework_path(&mut self, path: &Path);
111 fn output_filename(&mut self, path: &Path);
112 fn add_object(&mut self, path: &Path);
113 fn gc_sections(&mut self, keep_metadata: bool);
114 fn position_independent_executable(&mut self);
115 fn no_position_independent_executable(&mut self);
116 fn full_relro(&mut self);
117 fn partial_relro(&mut self);
118 fn no_relro(&mut self);
119 fn optimize(&mut self);
120 fn pgo_gen(&mut self);
121 fn debuginfo(&mut self);
122 fn no_default_libraries(&mut self);
123 fn build_dylib(&mut self, out_filename: &Path);
124 fn build_static_executable(&mut self);
125 fn args(&mut self, args: &[String]);
126 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
127 fn subsystem(&mut self, subsystem: &str);
128 fn group_start(&mut self);
129 fn group_end(&mut self);
130 fn linker_plugin_lto(&mut self);
131 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
132 fn finalize(&mut self) -> Command;
135 pub struct GccLinker<'a> {
138 info: &'a LinkerInfo,
139 hinted_static: bool, // Keeps track of the current hinting mode.
145 impl<'a> GccLinker<'a> {
146 /// Argument that must be passed *directly* to the linker
148 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
149 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
150 where S: AsRef<OsStr>
153 let mut os = OsString::from("-Wl,");
154 os.push(arg.as_ref());
162 fn takes_hints(&self) -> bool {
163 // Really this function only returns true if the underlying linker
164 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
165 // don't really have a foolproof way to detect that, so rule out some
166 // platforms where currently this is guaranteed to *not* be the case:
168 // * On OSX they have their own linker, not binutils'
169 // * For WebAssembly the only functional linker is LLD, which doesn't
170 // support hint flags
171 !self.sess.target.target.options.is_like_osx &&
172 self.sess.target.target.arch != "wasm32"
175 // Some platforms take hints about whether a library is static or dynamic.
176 // For those that support this, we ensure we pass the option if the library
177 // was flagged "static" (most defaults are dynamic) to ensure that if
178 // libfoo.a and libfoo.so both exist that the right one is chosen.
179 fn hint_static(&mut self) {
180 if !self.takes_hints() { return }
181 if !self.hinted_static {
182 self.linker_arg("-Bstatic");
183 self.hinted_static = true;
187 fn hint_dynamic(&mut self) {
188 if !self.takes_hints() { return }
189 if self.hinted_static {
190 self.linker_arg("-Bdynamic");
191 self.hinted_static = false;
195 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
196 if let Some(plugin_path) = plugin_path {
197 let mut arg = OsString::from("-plugin=");
198 arg.push(plugin_path);
199 self.linker_arg(&arg);
202 let opt_level = match self.sess.opts.optimize {
203 config::OptLevel::No => "O0",
204 config::OptLevel::Less => "O1",
205 config::OptLevel::Default => "O2",
206 config::OptLevel::Aggressive => "O3",
207 config::OptLevel::Size => "Os",
208 config::OptLevel::SizeMin => "Oz",
211 self.linker_arg(&format!("-plugin-opt={}", opt_level));
212 let target_cpu = self.target_cpu;
213 self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
217 impl<'a> Linker for GccLinker<'a> {
218 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}", lib)); }
219 fn link_staticlib(&mut self, lib: &str) {
220 self.hint_static(); self.cmd.arg(format!("-l{}", lib));
222 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
223 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
224 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
225 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
226 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
227 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
228 fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
229 fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
230 fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
231 fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
232 fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
233 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
235 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
237 self.cmd.arg(format!("-l{}", lib));
240 fn link_framework(&mut self, framework: &str) {
242 self.cmd.arg("-framework").arg(framework);
245 // Here we explicitly ask that the entire archive is included into the
246 // result artifact. For more details see #15460, but the gist is that
247 // the linker will strip away any unused objects in the archive if we
248 // don't otherwise explicitly reference them. This can occur for
249 // libraries which are just providing bindings, libraries with generic
251 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
253 let target = &self.sess.target.target;
254 if !target.options.is_like_osx {
255 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
256 self.linker_arg("--no-whole-archive");
258 // -force_load is the macOS equivalent of --whole-archive, but it
259 // involves passing the full path to the library to link.
260 self.linker_arg("-force_load");
261 let lib = archive::find_library(lib, search_path, &self.sess);
262 self.linker_arg(&lib);
266 fn link_whole_rlib(&mut self, lib: &Path) {
268 if self.sess.target.target.options.is_like_osx {
269 self.linker_arg("-force_load");
270 self.linker_arg(&lib);
272 self.linker_arg("--whole-archive").cmd.arg(lib);
273 self.linker_arg("--no-whole-archive");
277 fn gc_sections(&mut self, keep_metadata: bool) {
278 // The dead_strip option to the linker specifies that functions and data
279 // unreachable by the entry point will be removed. This is quite useful
280 // with Rust's compilation model of compiling libraries at a time into
281 // one object file. For example, this brings hello world from 1.7MB to
284 // Note that this is done for both executables and dynamic libraries. We
285 // won't get much benefit from dylibs because LLVM will have already
286 // stripped away as much as it could. This has not been seen to impact
287 // link times negatively.
289 // -dead_strip can't be part of the pre_link_args because it's also used
290 // for partial linking when using multiple codegen units (-r). So we
292 if self.sess.target.target.options.is_like_osx {
293 self.linker_arg("-dead_strip");
294 } else if self.sess.target.target.options.is_like_solaris {
295 self.linker_arg("-zignore");
297 // If we're building a dylib, we don't use --gc-sections because LLVM
298 // has already done the best it can do, and we also don't want to
299 // eliminate the metadata. If we're building an executable, however,
300 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
302 } else if !keep_metadata {
303 self.linker_arg("--gc-sections");
307 fn optimize(&mut self) {
308 if !self.sess.target.target.options.linker_is_gnu { return }
310 // GNU-style linkers support optimization with -O. GNU ld doesn't
311 // need a numeric argument, but other linkers do.
312 if self.sess.opts.optimize == config::OptLevel::Default ||
313 self.sess.opts.optimize == config::OptLevel::Aggressive {
314 self.linker_arg("-O1");
318 fn pgo_gen(&mut self) {
319 if !self.sess.target.target.options.linker_is_gnu { return }
321 // If we're doing PGO generation stuff and on a GNU-like linker, use the
322 // "-u" flag to properly pull in the profiler runtime bits.
324 // This is because LLVM otherwise won't add the needed initialization
325 // for us on Linux (though the extra flag should be harmless if it
328 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
330 // Though it may be worth to try to revert those changes upstream, since
331 // the overhead of the initialization should be minor.
333 self.cmd.arg("__llvm_profile_runtime");
336 fn debuginfo(&mut self) {
337 if let DebugInfo::None = self.sess.opts.debuginfo {
338 // If we are building without debuginfo enabled and we were called with
339 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
340 // found when linking to get rid of symbols from libstd.
341 if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
342 self.linker_arg("-S");
347 fn no_default_libraries(&mut self) {
349 self.cmd.arg("-nodefaultlibs");
353 fn build_dylib(&mut self, out_filename: &Path) {
354 // On mac we need to tell the linker to let this library be rpathed
355 if self.sess.target.target.options.is_like_osx {
356 self.cmd.arg("-dynamiclib");
357 self.linker_arg("-dylib");
359 // Note that the `osx_rpath_install_name` option here is a hack
360 // purely to support rustbuild right now, we should get a more
361 // principled solution at some point to force the compiler to pass
362 // the right `-Wl,-install_name` with an `@rpath` in it.
363 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
364 self.linker_arg("-install_name");
365 let mut v = OsString::from("@rpath/");
366 v.push(out_filename.file_name().unwrap());
370 self.cmd.arg("-shared");
371 if self.sess.target.target.options.is_like_windows {
372 // The output filename already contains `dll_suffix` so
373 // the resulting import library will have a name in the
374 // form of libfoo.dll.a
375 let implib_name = out_filename
377 .and_then(|file| file.to_str())
378 .map(|file| format!("{}{}{}",
379 self.sess.target.target.options.staticlib_prefix,
381 self.sess.target.target.options.staticlib_suffix));
382 if let Some(implib_name) = implib_name {
383 let implib = out_filename
385 .map(|dir| dir.join(&implib_name));
386 if let Some(implib) = implib {
387 self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
394 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
395 // Symbol visibility in object files typically takes care of this.
396 if crate_type == CrateType::Executable {
400 // We manually create a list of exported symbols to ensure we don't expose any more.
401 // The object files have far more public symbols than we actually want to export,
402 // so we hide them all here.
404 if !self.sess.target.target.options.limit_rdylib_exports {
408 if crate_type == CrateType::ProcMacro {
412 let mut arg = OsString::new();
413 let path = tmpdir.join("list");
415 debug!("EXPORTED SYMBOLS:");
417 if self.sess.target.target.options.is_like_osx {
418 // Write a plain, newline-separated list of symbols
419 let res: io::Result<()> = try {
420 let mut f = BufWriter::new(File::create(&path)?);
421 for sym in self.info.exports[&crate_type].iter() {
423 writeln!(f, "_{}", sym)?;
426 if let Err(e) = res {
427 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
430 // Write an LD version script
431 let res: io::Result<()> = try {
432 let mut f = BufWriter::new(File::create(&path)?);
434 if !self.info.exports[&crate_type].is_empty() {
435 writeln!(f, " global:")?;
436 for sym in self.info.exports[&crate_type].iter() {
438 writeln!(f, " {};", sym)?;
441 writeln!(f, "\n local:\n *;\n}};")?;
443 if let Err(e) = res {
444 self.sess.fatal(&format!("failed to write version script: {}", e));
448 if self.sess.target.target.options.is_like_osx {
452 arg.push("-exported_symbols_list,");
453 } else if self.sess.target.target.options.is_like_solaris {
462 arg.push("--version-script=");
469 fn subsystem(&mut self, subsystem: &str) {
470 self.linker_arg("--subsystem");
471 self.linker_arg(&subsystem);
474 fn finalize(&mut self) -> Command {
475 self.hint_dynamic(); // Reset to default before returning the composed command line.
477 ::std::mem::replace(&mut self.cmd, Command::new(""))
480 fn group_start(&mut self) {
481 if self.takes_hints() {
482 self.linker_arg("--start-group");
486 fn group_end(&mut self) {
487 if self.takes_hints() {
488 self.linker_arg("--end-group");
492 fn linker_plugin_lto(&mut self) {
493 match self.sess.opts.cg.linker_plugin_lto {
494 LinkerPluginLto::Disabled => {
497 LinkerPluginLto::LinkerPluginAuto => {
498 self.push_linker_plugin_lto_args(None);
500 LinkerPluginLto::LinkerPlugin(ref path) => {
501 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
507 pub struct MsvcLinker<'a> {
513 impl<'a> Linker for MsvcLinker<'a> {
514 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
515 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
516 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
518 fn build_dylib(&mut self, out_filename: &Path) {
519 self.cmd.arg("/DLL");
520 let mut arg: OsString = "/IMPLIB:".into();
521 arg.push(out_filename.with_extension("dll.lib"));
525 fn build_static_executable(&mut self) {
529 fn gc_sections(&mut self, _keep_metadata: bool) {
530 // MSVC's ICF (Identical COMDAT Folding) link optimization is
531 // slow for Rust and thus we disable it by default when not in
532 // optimization build.
533 if self.sess.opts.optimize != config::OptLevel::No {
534 self.cmd.arg("/OPT:REF,ICF");
536 // It is necessary to specify NOICF here, because /OPT:REF
537 // implies ICF by default.
538 self.cmd.arg("/OPT:REF,NOICF");
542 fn link_dylib(&mut self, lib: &str) {
543 self.cmd.arg(&format!("{}.lib", lib));
546 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
547 // When producing a dll, the MSVC linker may not actually emit a
548 // `foo.lib` file if the dll doesn't actually export any symbols, so we
549 // check to see if the file is there and just omit linking to it if it's
551 let name = format!("{}.dll.lib", lib);
552 if fs::metadata(&path.join(&name)).is_ok() {
557 fn link_staticlib(&mut self, lib: &str) {
558 self.cmd.arg(&format!("{}.lib", lib));
561 fn position_independent_executable(&mut self) {
565 fn no_position_independent_executable(&mut self) {
569 fn full_relro(&mut self) {
573 fn partial_relro(&mut self) {
577 fn no_relro(&mut self) {
581 fn no_default_libraries(&mut self) {
582 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
583 // as there's been trouble in the past of linking the C++ standard
584 // library required by LLVM. This likely needs to happen one day, but
585 // in general Windows is also a more controlled environment than
586 // Unix, so it's not necessarily as critical that this be implemented.
588 // Note that there are also some licensing worries about statically
589 // linking some libraries which require a specific agreement, so it may
590 // not ever be possible for us to pass this flag.
593 fn include_path(&mut self, path: &Path) {
594 let mut arg = OsString::from("/LIBPATH:");
599 fn output_filename(&mut self, path: &Path) {
600 let mut arg = OsString::from("/OUT:");
605 fn framework_path(&mut self, _path: &Path) {
606 bug!("frameworks are not supported on windows")
608 fn link_framework(&mut self, _framework: &str) {
609 bug!("frameworks are not supported on windows")
612 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
614 self.link_staticlib(lib);
616 fn link_whole_rlib(&mut self, path: &Path) {
618 self.link_rlib(path);
620 fn optimize(&mut self) {
621 // Needs more investigation of `/OPT` arguments
624 fn pgo_gen(&mut self) {
625 // Nothing needed here.
628 fn debuginfo(&mut self) {
629 // This will cause the Microsoft linker to generate a PDB file
630 // from the CodeView line tables in the object files.
631 self.cmd.arg("/DEBUG");
633 // This will cause the Microsoft linker to embed .natvis info into the PDB file
634 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
635 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
636 for entry in natvis_dir {
639 let path = entry.path();
640 if path.extension() == Some("natvis".as_ref()) {
641 let mut arg = OsString::from("/NATVIS:");
647 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
654 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
655 // export symbols from a dynamic library. When building a dynamic library,
656 // however, we're going to want some symbols exported, so this function
657 // generates a DEF file which lists all the symbols.
659 // The linker will read this `*.def` file and export all the symbols from
660 // the dynamic library. Note that this is not as simple as just exporting
661 // all the symbols in the current crate (as specified by `codegen.reachable`)
662 // but rather we also need to possibly export the symbols of upstream
663 // crates. Upstream rlibs may be linked statically to this dynamic library,
664 // in which case they may continue to transitively be used and hence need
665 // their symbols exported.
666 fn export_symbols(&mut self,
668 crate_type: CrateType) {
669 // Symbol visibility takes care of this typically
670 if crate_type == CrateType::Executable {
674 let path = tmpdir.join("lib.def");
675 let res: io::Result<()> = try {
676 let mut f = BufWriter::new(File::create(&path)?);
678 // Start off with the standard module name header and then go
679 // straight to exports.
680 writeln!(f, "LIBRARY")?;
681 writeln!(f, "EXPORTS")?;
682 for symbol in self.info.exports[&crate_type].iter() {
683 debug!(" _{}", symbol);
684 writeln!(f, " {}", symbol)?;
687 if let Err(e) = res {
688 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
690 let mut arg = OsString::from("/DEF:");
695 fn subsystem(&mut self, subsystem: &str) {
696 // Note that previous passes of the compiler validated this subsystem,
697 // so we just blindly pass it to the linker.
698 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
700 // Windows has two subsystems we're interested in right now, the console
701 // and windows subsystems. These both implicitly have different entry
702 // points (starting symbols). The console entry point starts with
703 // `mainCRTStartup` and the windows entry point starts with
704 // `WinMainCRTStartup`. These entry points, defined in system libraries,
705 // will then later probe for either `main` or `WinMain`, respectively to
706 // start the application.
708 // In Rust we just always generate a `main` function so we want control
709 // to always start there, so we force the entry point on the windows
710 // subsystem to be `mainCRTStartup` to get everything booted up
713 // For more information see RFC #1665
714 if subsystem == "windows" {
715 self.cmd.arg("/ENTRY:mainCRTStartup");
719 fn finalize(&mut self) -> Command {
720 ::std::mem::replace(&mut self.cmd, Command::new(""))
723 // MSVC doesn't need group indicators
724 fn group_start(&mut self) {}
725 fn group_end(&mut self) {}
727 fn linker_plugin_lto(&mut self) {
732 pub struct EmLinker<'a> {
738 impl<'a> Linker for EmLinker<'a> {
739 fn include_path(&mut self, path: &Path) {
740 self.cmd.arg("-L").arg(path);
743 fn link_staticlib(&mut self, lib: &str) {
744 self.cmd.arg("-l").arg(lib);
747 fn output_filename(&mut self, path: &Path) {
748 self.cmd.arg("-o").arg(path);
751 fn add_object(&mut self, path: &Path) {
755 fn link_dylib(&mut self, lib: &str) {
756 // Emscripten always links statically
757 self.link_staticlib(lib);
760 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
762 self.link_staticlib(lib);
765 fn link_whole_rlib(&mut self, lib: &Path) {
770 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
771 self.link_dylib(lib);
774 fn link_rlib(&mut self, lib: &Path) {
775 self.add_object(lib);
778 fn position_independent_executable(&mut self) {
782 fn no_position_independent_executable(&mut self) {
786 fn full_relro(&mut self) {
790 fn partial_relro(&mut self) {
794 fn no_relro(&mut self) {
798 fn args(&mut self, args: &[String]) {
802 fn framework_path(&mut self, _path: &Path) {
803 bug!("frameworks are not supported on Emscripten")
806 fn link_framework(&mut self, _framework: &str) {
807 bug!("frameworks are not supported on Emscripten")
810 fn gc_sections(&mut self, _keep_metadata: bool) {
814 fn optimize(&mut self) {
815 // Emscripten performs own optimizations
816 self.cmd.arg(match self.sess.opts.optimize {
817 OptLevel::No => "-O0",
818 OptLevel::Less => "-O1",
819 OptLevel::Default => "-O2",
820 OptLevel::Aggressive => "-O3",
821 OptLevel::Size => "-Os",
822 OptLevel::SizeMin => "-Oz"
824 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
825 self.cmd.args(&["--memory-init-file", "0"]);
828 fn pgo_gen(&mut self) {
829 // noop, but maybe we need something like the gnu linker?
832 fn debuginfo(&mut self) {
833 // Preserve names or generate source maps depending on debug info
834 self.cmd.arg(match self.sess.opts.debuginfo {
835 DebugInfo::None => "-g0",
836 DebugInfo::Limited => "-g3",
837 DebugInfo::Full => "-g4"
841 fn no_default_libraries(&mut self) {
842 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
845 fn build_dylib(&mut self, _out_filename: &Path) {
846 bug!("building dynamic library is unsupported on Emscripten")
849 fn build_static_executable(&mut self) {
853 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
854 let symbols = &self.info.exports[&crate_type];
856 debug!("EXPORTED SYMBOLS:");
860 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
861 let mut encoded = String::new();
864 let mut encoder = json::Encoder::new(&mut encoded);
865 let res = encoder.emit_seq(symbols.len(), |encoder| {
866 for (i, sym) in symbols.iter().enumerate() {
867 encoder.emit_seq_elt(i, |encoder| {
868 encoder.emit_str(&("_".to_owned() + sym))
873 if let Err(e) = res {
874 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
877 debug!("{}", encoded);
883 fn subsystem(&mut self, _subsystem: &str) {
887 fn finalize(&mut self) -> Command {
888 ::std::mem::replace(&mut self.cmd, Command::new(""))
891 // Appears not necessary on Emscripten
892 fn group_start(&mut self) {}
893 fn group_end(&mut self) {}
895 fn linker_plugin_lto(&mut self) {
900 pub struct WasmLd<'a> {
903 info: &'a LinkerInfo,
906 impl<'a> WasmLd<'a> {
907 fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
908 // If the atomics feature is enabled for wasm then we need a whole bunch
911 // * `--shared-memory` - the link won't even succeed without this, flags
912 // the one linear memory as `shared`
914 // * `--max-memory=1G` - when specifying a shared memory this must also
915 // be specified. We conservatively choose 1GB but users should be able
916 // to override this with `-C link-arg`.
918 // * `--import-memory` - it doesn't make much sense for memory to be
919 // exported in a threaded module because typically you're
920 // sharing memory and instantiating the module multiple times. As a
921 // result if it were exported then we'd just have no sharing.
923 // * `--passive-segments` - all memory segments should be passive to
924 // prevent each module instantiation from reinitializing memory.
926 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
927 // linker will synthesize this function, and so we need to make sure
928 // that our usage of `--export` below won't accidentally cause this
929 // function to get deleted.
931 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
932 // symbols are how the TLS segments are initialized and configured.
933 let atomics = sess.opts.cg.target_feature.contains("+atomics") ||
934 sess.target.target.options.features.contains("+atomics");
936 cmd.arg("--shared-memory");
937 cmd.arg("--max-memory=1073741824");
938 cmd.arg("--import-memory");
939 cmd.arg("--passive-segments");
940 cmd.arg("--export=__wasm_init_memory");
941 cmd.arg("--export=__wasm_init_tls");
942 cmd.arg("--export=__tls_size");
943 cmd.arg("--export=__tls_align");
944 cmd.arg("--export=__tls_base");
946 WasmLd { cmd, sess, info }
950 impl<'a> Linker for WasmLd<'a> {
951 fn link_dylib(&mut self, lib: &str) {
952 self.cmd.arg("-l").arg(lib);
955 fn link_staticlib(&mut self, lib: &str) {
956 self.cmd.arg("-l").arg(lib);
959 fn link_rlib(&mut self, lib: &Path) {
963 fn include_path(&mut self, path: &Path) {
964 self.cmd.arg("-L").arg(path);
967 fn framework_path(&mut self, _path: &Path) {
968 panic!("frameworks not supported")
971 fn output_filename(&mut self, path: &Path) {
972 self.cmd.arg("-o").arg(path);
975 fn add_object(&mut self, path: &Path) {
979 fn position_independent_executable(&mut self) {
982 fn full_relro(&mut self) {
985 fn partial_relro(&mut self) {
988 fn no_relro(&mut self) {
991 fn build_static_executable(&mut self) {
994 fn args(&mut self, args: &[String]) {
998 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
999 self.cmd.arg("-l").arg(lib);
1002 fn link_framework(&mut self, _framework: &str) {
1003 panic!("frameworks not supported")
1006 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
1007 self.cmd.arg("-l").arg(lib);
1010 fn link_whole_rlib(&mut self, lib: &Path) {
1014 fn gc_sections(&mut self, _keep_metadata: bool) {
1015 self.cmd.arg("--gc-sections");
1018 fn optimize(&mut self) {
1019 self.cmd.arg(match self.sess.opts.optimize {
1020 OptLevel::No => "-O0",
1021 OptLevel::Less => "-O1",
1022 OptLevel::Default => "-O2",
1023 OptLevel::Aggressive => "-O3",
1024 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1026 OptLevel::Size => "-O2",
1027 OptLevel::SizeMin => "-O2"
1031 fn pgo_gen(&mut self) {
1034 fn debuginfo(&mut self) {
1037 fn no_default_libraries(&mut self) {
1040 fn build_dylib(&mut self, _out_filename: &Path) {
1041 self.cmd.arg("--no-entry");
1044 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1045 for sym in self.info.exports[&crate_type].iter() {
1046 self.cmd.arg("--export").arg(&sym);
1049 // LLD will hide these otherwise-internal symbols since our `--export`
1050 // list above is a whitelist of what to export. Various bits and pieces
1051 // of tooling use this, so be sure these symbols make their way out of
1052 // the linker as well.
1053 self.cmd.arg("--export=__heap_base");
1054 self.cmd.arg("--export=__data_end");
1057 fn subsystem(&mut self, _subsystem: &str) {
1060 fn no_position_independent_executable(&mut self) {
1063 fn finalize(&mut self) -> Command {
1064 ::std::mem::replace(&mut self.cmd, Command::new(""))
1067 // Not needed for now with LLD
1068 fn group_start(&mut self) {}
1069 fn group_end(&mut self) {}
1071 fn linker_plugin_lto(&mut self) {
1072 // Do nothing for now
1076 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1077 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1078 return exports.clone()
1081 let mut symbols = Vec::new();
1083 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1084 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1085 if level.is_below_threshold(export_threshold) {
1086 symbols.push(symbol.symbol_name(tcx).to_string());
1090 let formats = tcx.sess.dependency_formats.borrow();
1091 let deps = formats[&crate_type].iter();
1093 for (index, dep_format) in deps.enumerate() {
1094 let cnum = CrateNum::new(index + 1);
1095 // For each dependency that we are linking to statically ...
1096 if *dep_format == Linkage::Static {
1097 // ... we add its symbol list to our export list.
1098 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1099 if level.is_below_threshold(export_threshold) {
1100 symbols.push(symbol.symbol_name(tcx).to_string());
1109 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1110 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1111 pub struct PtxLinker<'a> {
1116 impl<'a> Linker for PtxLinker<'a> {
1117 fn link_rlib(&mut self, path: &Path) {
1118 self.cmd.arg("--rlib").arg(path);
1121 fn link_whole_rlib(&mut self, path: &Path) {
1122 self.cmd.arg("--rlib").arg(path);
1125 fn include_path(&mut self, path: &Path) {
1126 self.cmd.arg("-L").arg(path);
1129 fn debuginfo(&mut self) {
1130 self.cmd.arg("--debug");
1133 fn add_object(&mut self, path: &Path) {
1134 self.cmd.arg("--bitcode").arg(path);
1137 fn args(&mut self, args: &[String]) {
1138 self.cmd.args(args);
1141 fn optimize(&mut self) {
1142 match self.sess.lto() {
1143 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1144 self.cmd.arg("-Olto");
1151 fn output_filename(&mut self, path: &Path) {
1152 self.cmd.arg("-o").arg(path);
1155 fn finalize(&mut self) -> Command {
1156 // Provide the linker with fallback to internal `target-cpu`.
1157 self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1159 None => &self.sess.target.target.options.cpu
1162 ::std::mem::replace(&mut self.cmd, Command::new(""))
1165 fn link_dylib(&mut self, _lib: &str) {
1166 panic!("external dylibs not supported")
1169 fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
1170 panic!("external dylibs not supported")
1173 fn link_staticlib(&mut self, _lib: &str) {
1174 panic!("staticlibs not supported")
1177 fn link_whole_staticlib(&mut self, _lib: &str, _search_path: &[PathBuf]) {
1178 panic!("staticlibs not supported")
1181 fn framework_path(&mut self, _path: &Path) {
1182 panic!("frameworks not supported")
1185 fn link_framework(&mut self, _framework: &str) {
1186 panic!("frameworks not supported")
1189 fn position_independent_executable(&mut self) {
1192 fn full_relro(&mut self) {
1195 fn partial_relro(&mut self) {
1198 fn no_relro(&mut self) {
1201 fn build_static_executable(&mut self) {
1204 fn gc_sections(&mut self, _keep_metadata: bool) {
1207 fn pgo_gen(&mut self) {
1210 fn no_default_libraries(&mut self) {
1213 fn build_dylib(&mut self, _out_filename: &Path) {
1216 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
1219 fn subsystem(&mut self, _subsystem: &str) {
1222 fn no_position_independent_executable(&mut self) {
1225 fn group_start(&mut self) {
1228 fn group_end(&mut self) {
1231 fn linker_plugin_lto(&mut self) {