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};
20 use syntax::symbol::Symbol;
22 /// For all the linkers we support, and information they might
23 /// need out of the shared crate context before we get rid of it.
24 pub struct LinkerInfo {
25 exports: FxHashMap<CrateType, Vec<String>>,
29 pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
31 exports: tcx.sess.crate_types.borrow().iter().map(|&c| {
32 (c, exported_symbols(tcx, c))
43 ) -> Box<dyn Linker+'a> {
45 LinkerFlavor::Lld(LldFlavor::Link) |
46 LinkerFlavor::Msvc => {
60 LinkerFlavor::Gcc => {
71 LinkerFlavor::Lld(LldFlavor::Ld) |
72 LinkerFlavor::Lld(LldFlavor::Ld64) |
84 LinkerFlavor::Lld(LldFlavor::Wasm) => {
85 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
88 LinkerFlavor::PtxLinker => {
89 Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>
95 /// Linker abstraction used by `back::link` to build up the command to invoke a
98 /// This trait is the total list of requirements needed by `back::link` and
99 /// represents the meaning of each option being passed down. This trait is then
100 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
101 /// MSVC linker (e.g., `link.exe`) is being used.
103 fn link_dylib(&mut self, lib: Symbol);
104 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
105 fn link_framework(&mut self, framework: Symbol);
106 fn link_staticlib(&mut self, lib: Symbol);
107 fn link_rlib(&mut self, lib: &Path);
108 fn link_whole_rlib(&mut self, lib: &Path);
109 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]);
110 fn include_path(&mut self, path: &Path);
111 fn framework_path(&mut self, path: &Path);
112 fn output_filename(&mut self, path: &Path);
113 fn add_object(&mut self, path: &Path);
114 fn gc_sections(&mut self, keep_metadata: bool);
115 fn position_independent_executable(&mut self);
116 fn no_position_independent_executable(&mut self);
117 fn full_relro(&mut self);
118 fn partial_relro(&mut self);
119 fn no_relro(&mut self);
120 fn optimize(&mut self);
121 fn pgo_gen(&mut self);
122 fn debuginfo(&mut self);
123 fn no_default_libraries(&mut self);
124 fn build_dylib(&mut self, out_filename: &Path);
125 fn build_static_executable(&mut self);
126 fn args(&mut self, args: &[String]);
127 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
128 fn subsystem(&mut self, subsystem: &str);
129 fn group_start(&mut self);
130 fn group_end(&mut self);
131 fn linker_plugin_lto(&mut self);
132 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
133 fn finalize(&mut self) -> Command;
136 pub struct GccLinker<'a> {
139 info: &'a LinkerInfo,
140 hinted_static: bool, // Keeps track of the current hinting mode.
146 impl<'a> GccLinker<'a> {
147 /// Argument that must be passed *directly* to the linker
149 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
150 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
151 where S: AsRef<OsStr>
154 let mut os = OsString::from("-Wl,");
155 os.push(arg.as_ref());
163 fn takes_hints(&self) -> bool {
164 // Really this function only returns true if the underlying linker
165 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
166 // don't really have a foolproof way to detect that, so rule out some
167 // platforms where currently this is guaranteed to *not* be the case:
169 // * On OSX they have their own linker, not binutils'
170 // * For WebAssembly the only functional linker is LLD, which doesn't
171 // support hint flags
172 !self.sess.target.target.options.is_like_osx &&
173 self.sess.target.target.arch != "wasm32"
176 // Some platforms take hints about whether a library is static or dynamic.
177 // For those that support this, we ensure we pass the option if the library
178 // was flagged "static" (most defaults are dynamic) to ensure that if
179 // libfoo.a and libfoo.so both exist that the right one is chosen.
180 fn hint_static(&mut self) {
181 if !self.takes_hints() { return }
182 if !self.hinted_static {
183 self.linker_arg("-Bstatic");
184 self.hinted_static = true;
188 fn hint_dynamic(&mut self) {
189 if !self.takes_hints() { return }
190 if self.hinted_static {
191 self.linker_arg("-Bdynamic");
192 self.hinted_static = false;
196 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
197 if let Some(plugin_path) = plugin_path {
198 let mut arg = OsString::from("-plugin=");
199 arg.push(plugin_path);
200 self.linker_arg(&arg);
203 let opt_level = match self.sess.opts.optimize {
204 config::OptLevel::No => "O0",
205 config::OptLevel::Less => "O1",
206 config::OptLevel::Default => "O2",
207 config::OptLevel::Aggressive => "O3",
208 config::OptLevel::Size => "Os",
209 config::OptLevel::SizeMin => "Oz",
212 self.linker_arg(&format!("-plugin-opt={}", opt_level));
213 let target_cpu = self.target_cpu;
214 self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
218 impl<'a> Linker for GccLinker<'a> {
219 fn link_dylib(&mut self, lib: Symbol) {
221 self.cmd.arg(format!("-l{}", lib));
223 fn link_staticlib(&mut self, lib: Symbol) {
225 self.cmd.arg(format!("-l{}", lib));
227 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
228 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
229 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
230 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
231 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
232 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
233 fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
234 fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
235 fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
236 fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
237 fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
238 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
240 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
242 self.cmd.arg(format!("-l{}", lib));
245 fn link_framework(&mut self, framework: Symbol) {
247 self.cmd.arg("-framework").sym_arg(framework);
250 // Here we explicitly ask that the entire archive is included into the
251 // result artifact. For more details see #15460, but the gist is that
252 // the linker will strip away any unused objects in the archive if we
253 // don't otherwise explicitly reference them. This can occur for
254 // libraries which are just providing bindings, libraries with generic
256 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
258 let target = &self.sess.target.target;
259 if !target.options.is_like_osx {
260 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
261 self.linker_arg("--no-whole-archive");
263 // -force_load is the macOS equivalent of --whole-archive, but it
264 // involves passing the full path to the library to link.
265 self.linker_arg("-force_load");
266 let lib = archive::find_library(lib, search_path, &self.sess);
267 self.linker_arg(&lib);
271 fn link_whole_rlib(&mut self, lib: &Path) {
273 if self.sess.target.target.options.is_like_osx {
274 self.linker_arg("-force_load");
275 self.linker_arg(&lib);
277 self.linker_arg("--whole-archive").cmd.arg(lib);
278 self.linker_arg("--no-whole-archive");
282 fn gc_sections(&mut self, keep_metadata: bool) {
283 // The dead_strip option to the linker specifies that functions and data
284 // unreachable by the entry point will be removed. This is quite useful
285 // with Rust's compilation model of compiling libraries at a time into
286 // one object file. For example, this brings hello world from 1.7MB to
289 // Note that this is done for both executables and dynamic libraries. We
290 // won't get much benefit from dylibs because LLVM will have already
291 // stripped away as much as it could. This has not been seen to impact
292 // link times negatively.
294 // -dead_strip can't be part of the pre_link_args because it's also used
295 // for partial linking when using multiple codegen units (-r). So we
297 if self.sess.target.target.options.is_like_osx {
298 self.linker_arg("-dead_strip");
299 } else if self.sess.target.target.options.is_like_solaris {
300 self.linker_arg("-zignore");
302 // If we're building a dylib, we don't use --gc-sections because LLVM
303 // has already done the best it can do, and we also don't want to
304 // eliminate the metadata. If we're building an executable, however,
305 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
307 } else if !keep_metadata {
308 self.linker_arg("--gc-sections");
312 fn optimize(&mut self) {
313 if !self.sess.target.target.options.linker_is_gnu { return }
315 // GNU-style linkers support optimization with -O. GNU ld doesn't
316 // need a numeric argument, but other linkers do.
317 if self.sess.opts.optimize == config::OptLevel::Default ||
318 self.sess.opts.optimize == config::OptLevel::Aggressive {
319 self.linker_arg("-O1");
323 fn pgo_gen(&mut self) {
324 if !self.sess.target.target.options.linker_is_gnu { return }
326 // If we're doing PGO generation stuff and on a GNU-like linker, use the
327 // "-u" flag to properly pull in the profiler runtime bits.
329 // This is because LLVM otherwise won't add the needed initialization
330 // for us on Linux (though the extra flag should be harmless if it
333 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
335 // Though it may be worth to try to revert those changes upstream, since
336 // the overhead of the initialization should be minor.
338 self.cmd.arg("__llvm_profile_runtime");
341 fn debuginfo(&mut self) {
342 if let DebugInfo::None = self.sess.opts.debuginfo {
343 // If we are building without debuginfo enabled and we were called with
344 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
345 // found when linking to get rid of symbols from libstd.
346 if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
347 self.linker_arg("-S");
352 fn no_default_libraries(&mut self) {
354 self.cmd.arg("-nodefaultlibs");
358 fn build_dylib(&mut self, out_filename: &Path) {
359 // On mac we need to tell the linker to let this library be rpathed
360 if self.sess.target.target.options.is_like_osx {
361 self.cmd.arg("-dynamiclib");
362 self.linker_arg("-dylib");
364 // Note that the `osx_rpath_install_name` option here is a hack
365 // purely to support rustbuild right now, we should get a more
366 // principled solution at some point to force the compiler to pass
367 // the right `-Wl,-install_name` with an `@rpath` in it.
368 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
369 self.linker_arg("-install_name");
370 let mut v = OsString::from("@rpath/");
371 v.push(out_filename.file_name().unwrap());
375 self.cmd.arg("-shared");
376 if self.sess.target.target.options.is_like_windows {
377 // The output filename already contains `dll_suffix` so
378 // the resulting import library will have a name in the
379 // form of libfoo.dll.a
380 let implib_name = out_filename
382 .and_then(|file| file.to_str())
383 .map(|file| format!("{}{}{}",
384 self.sess.target.target.options.staticlib_prefix,
386 self.sess.target.target.options.staticlib_suffix));
387 if let Some(implib_name) = implib_name {
388 let implib = out_filename
390 .map(|dir| dir.join(&implib_name));
391 if let Some(implib) = implib {
392 self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
399 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
400 // Symbol visibility in object files typically takes care of this.
401 if crate_type == CrateType::Executable {
405 // We manually create a list of exported symbols to ensure we don't expose any more.
406 // The object files have far more public symbols than we actually want to export,
407 // so we hide them all here.
409 if !self.sess.target.target.options.limit_rdylib_exports {
413 if crate_type == CrateType::ProcMacro {
417 let mut arg = OsString::new();
418 let path = tmpdir.join("list");
420 debug!("EXPORTED SYMBOLS:");
422 if self.sess.target.target.options.is_like_osx {
423 // Write a plain, newline-separated list of symbols
424 let res: io::Result<()> = try {
425 let mut f = BufWriter::new(File::create(&path)?);
426 for sym in self.info.exports[&crate_type].iter() {
428 writeln!(f, "_{}", sym)?;
431 if let Err(e) = res {
432 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
435 // Write an LD version script
436 let res: io::Result<()> = try {
437 let mut f = BufWriter::new(File::create(&path)?);
439 if !self.info.exports[&crate_type].is_empty() {
440 writeln!(f, " global:")?;
441 for sym in self.info.exports[&crate_type].iter() {
443 writeln!(f, " {};", sym)?;
446 writeln!(f, "\n local:\n *;\n}};")?;
448 if let Err(e) = res {
449 self.sess.fatal(&format!("failed to write version script: {}", e));
453 if self.sess.target.target.options.is_like_osx {
457 arg.push("-exported_symbols_list,");
458 } else if self.sess.target.target.options.is_like_solaris {
467 arg.push("--version-script=");
474 fn subsystem(&mut self, subsystem: &str) {
475 self.linker_arg("--subsystem");
476 self.linker_arg(&subsystem);
479 fn finalize(&mut self) -> Command {
480 self.hint_dynamic(); // Reset to default before returning the composed command line.
482 ::std::mem::replace(&mut self.cmd, Command::new(""))
485 fn group_start(&mut self) {
486 if self.takes_hints() {
487 self.linker_arg("--start-group");
491 fn group_end(&mut self) {
492 if self.takes_hints() {
493 self.linker_arg("--end-group");
497 fn linker_plugin_lto(&mut self) {
498 match self.sess.opts.cg.linker_plugin_lto {
499 LinkerPluginLto::Disabled => {
502 LinkerPluginLto::LinkerPluginAuto => {
503 self.push_linker_plugin_lto_args(None);
505 LinkerPluginLto::LinkerPlugin(ref path) => {
506 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
512 pub struct MsvcLinker<'a> {
518 impl<'a> Linker for MsvcLinker<'a> {
519 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
520 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
521 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
523 fn build_dylib(&mut self, out_filename: &Path) {
524 self.cmd.arg("/DLL");
525 let mut arg: OsString = "/IMPLIB:".into();
526 arg.push(out_filename.with_extension("dll.lib"));
530 fn build_static_executable(&mut self) {
534 fn gc_sections(&mut self, _keep_metadata: bool) {
535 // MSVC's ICF (Identical COMDAT Folding) link optimization is
536 // slow for Rust and thus we disable it by default when not in
537 // optimization build.
538 if self.sess.opts.optimize != config::OptLevel::No {
539 self.cmd.arg("/OPT:REF,ICF");
541 // It is necessary to specify NOICF here, because /OPT:REF
542 // implies ICF by default.
543 self.cmd.arg("/OPT:REF,NOICF");
547 fn link_dylib(&mut self, lib: Symbol) {
548 self.cmd.arg(&format!("{}.lib", lib));
551 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
552 // When producing a dll, the MSVC linker may not actually emit a
553 // `foo.lib` file if the dll doesn't actually export any symbols, so we
554 // check to see if the file is there and just omit linking to it if it's
556 let name = format!("{}.dll.lib", lib);
557 if fs::metadata(&path.join(&name)).is_ok() {
562 fn link_staticlib(&mut self, lib: Symbol) {
563 self.cmd.arg(&format!("{}.lib", lib));
566 fn position_independent_executable(&mut self) {
570 fn no_position_independent_executable(&mut self) {
574 fn full_relro(&mut self) {
578 fn partial_relro(&mut self) {
582 fn no_relro(&mut self) {
586 fn no_default_libraries(&mut self) {
587 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
588 // as there's been trouble in the past of linking the C++ standard
589 // library required by LLVM. This likely needs to happen one day, but
590 // in general Windows is also a more controlled environment than
591 // Unix, so it's not necessarily as critical that this be implemented.
593 // Note that there are also some licensing worries about statically
594 // linking some libraries which require a specific agreement, so it may
595 // not ever be possible for us to pass this flag.
598 fn include_path(&mut self, path: &Path) {
599 let mut arg = OsString::from("/LIBPATH:");
604 fn output_filename(&mut self, path: &Path) {
605 let mut arg = OsString::from("/OUT:");
610 fn framework_path(&mut self, _path: &Path) {
611 bug!("frameworks are not supported on windows")
613 fn link_framework(&mut self, _framework: Symbol) {
614 bug!("frameworks are not supported on windows")
617 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
619 self.link_staticlib(lib);
621 fn link_whole_rlib(&mut self, path: &Path) {
623 self.link_rlib(path);
625 fn optimize(&mut self) {
626 // Needs more investigation of `/OPT` arguments
629 fn pgo_gen(&mut self) {
630 // Nothing needed here.
633 fn debuginfo(&mut self) {
634 // This will cause the Microsoft linker to generate a PDB file
635 // from the CodeView line tables in the object files.
636 self.cmd.arg("/DEBUG");
638 // This will cause the Microsoft linker to embed .natvis info into the PDB file
639 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
640 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
641 for entry in natvis_dir {
644 let path = entry.path();
645 if path.extension() == Some("natvis".as_ref()) {
646 let mut arg = OsString::from("/NATVIS:");
652 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
659 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
660 // export symbols from a dynamic library. When building a dynamic library,
661 // however, we're going to want some symbols exported, so this function
662 // generates a DEF file which lists all the symbols.
664 // The linker will read this `*.def` file and export all the symbols from
665 // the dynamic library. Note that this is not as simple as just exporting
666 // all the symbols in the current crate (as specified by `codegen.reachable`)
667 // but rather we also need to possibly export the symbols of upstream
668 // crates. Upstream rlibs may be linked statically to this dynamic library,
669 // in which case they may continue to transitively be used and hence need
670 // their symbols exported.
671 fn export_symbols(&mut self,
673 crate_type: CrateType) {
674 // Symbol visibility takes care of this typically
675 if crate_type == CrateType::Executable {
679 let path = tmpdir.join("lib.def");
680 let res: io::Result<()> = try {
681 let mut f = BufWriter::new(File::create(&path)?);
683 // Start off with the standard module name header and then go
684 // straight to exports.
685 writeln!(f, "LIBRARY")?;
686 writeln!(f, "EXPORTS")?;
687 for symbol in self.info.exports[&crate_type].iter() {
688 debug!(" _{}", symbol);
689 writeln!(f, " {}", symbol)?;
692 if let Err(e) = res {
693 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
695 let mut arg = OsString::from("/DEF:");
700 fn subsystem(&mut self, subsystem: &str) {
701 // Note that previous passes of the compiler validated this subsystem,
702 // so we just blindly pass it to the linker.
703 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
705 // Windows has two subsystems we're interested in right now, the console
706 // and windows subsystems. These both implicitly have different entry
707 // points (starting symbols). The console entry point starts with
708 // `mainCRTStartup` and the windows entry point starts with
709 // `WinMainCRTStartup`. These entry points, defined in system libraries,
710 // will then later probe for either `main` or `WinMain`, respectively to
711 // start the application.
713 // In Rust we just always generate a `main` function so we want control
714 // to always start there, so we force the entry point on the windows
715 // subsystem to be `mainCRTStartup` to get everything booted up
718 // For more information see RFC #1665
719 if subsystem == "windows" {
720 self.cmd.arg("/ENTRY:mainCRTStartup");
724 fn finalize(&mut self) -> Command {
725 ::std::mem::replace(&mut self.cmd, Command::new(""))
728 // MSVC doesn't need group indicators
729 fn group_start(&mut self) {}
730 fn group_end(&mut self) {}
732 fn linker_plugin_lto(&mut self) {
737 pub struct EmLinker<'a> {
743 impl<'a> Linker for EmLinker<'a> {
744 fn include_path(&mut self, path: &Path) {
745 self.cmd.arg("-L").arg(path);
748 fn link_staticlib(&mut self, lib: Symbol) {
749 self.cmd.arg("-l").sym_arg(lib);
752 fn output_filename(&mut self, path: &Path) {
753 self.cmd.arg("-o").arg(path);
756 fn add_object(&mut self, path: &Path) {
760 fn link_dylib(&mut self, lib: Symbol) {
761 // Emscripten always links statically
762 self.link_staticlib(lib);
765 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
767 self.link_staticlib(lib);
770 fn link_whole_rlib(&mut self, lib: &Path) {
775 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
776 self.link_dylib(lib);
779 fn link_rlib(&mut self, lib: &Path) {
780 self.add_object(lib);
783 fn position_independent_executable(&mut self) {
787 fn no_position_independent_executable(&mut self) {
791 fn full_relro(&mut self) {
795 fn partial_relro(&mut self) {
799 fn no_relro(&mut self) {
803 fn args(&mut self, args: &[String]) {
807 fn framework_path(&mut self, _path: &Path) {
808 bug!("frameworks are not supported on Emscripten")
811 fn link_framework(&mut self, _framework: Symbol) {
812 bug!("frameworks are not supported on Emscripten")
815 fn gc_sections(&mut self, _keep_metadata: bool) {
819 fn optimize(&mut self) {
820 // Emscripten performs own optimizations
821 self.cmd.arg(match self.sess.opts.optimize {
822 OptLevel::No => "-O0",
823 OptLevel::Less => "-O1",
824 OptLevel::Default => "-O2",
825 OptLevel::Aggressive => "-O3",
826 OptLevel::Size => "-Os",
827 OptLevel::SizeMin => "-Oz"
829 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
830 self.cmd.args(&["--memory-init-file", "0"]);
833 fn pgo_gen(&mut self) {
834 // noop, but maybe we need something like the gnu linker?
837 fn debuginfo(&mut self) {
838 // Preserve names or generate source maps depending on debug info
839 self.cmd.arg(match self.sess.opts.debuginfo {
840 DebugInfo::None => "-g0",
841 DebugInfo::Limited => "-g3",
842 DebugInfo::Full => "-g4"
846 fn no_default_libraries(&mut self) {
847 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
850 fn build_dylib(&mut self, _out_filename: &Path) {
851 bug!("building dynamic library is unsupported on Emscripten")
854 fn build_static_executable(&mut self) {
858 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
859 let symbols = &self.info.exports[&crate_type];
861 debug!("EXPORTED SYMBOLS:");
865 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
866 let mut encoded = String::new();
869 let mut encoder = json::Encoder::new(&mut encoded);
870 let res = encoder.emit_seq(symbols.len(), |encoder| {
871 for (i, sym) in symbols.iter().enumerate() {
872 encoder.emit_seq_elt(i, |encoder| {
873 encoder.emit_str(&("_".to_owned() + sym))
878 if let Err(e) = res {
879 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
882 debug!("{}", encoded);
888 fn subsystem(&mut self, _subsystem: &str) {
892 fn finalize(&mut self) -> Command {
893 ::std::mem::replace(&mut self.cmd, Command::new(""))
896 // Appears not necessary on Emscripten
897 fn group_start(&mut self) {}
898 fn group_end(&mut self) {}
900 fn linker_plugin_lto(&mut self) {
905 pub struct WasmLd<'a> {
908 info: &'a LinkerInfo,
911 impl<'a> WasmLd<'a> {
912 fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
913 // If the atomics feature is enabled for wasm then we need a whole bunch
916 // * `--shared-memory` - the link won't even succeed without this, flags
917 // the one linear memory as `shared`
919 // * `--max-memory=1G` - when specifying a shared memory this must also
920 // be specified. We conservatively choose 1GB but users should be able
921 // to override this with `-C link-arg`.
923 // * `--import-memory` - it doesn't make much sense for memory to be
924 // exported in a threaded module because typically you're
925 // sharing memory and instantiating the module multiple times. As a
926 // result if it were exported then we'd just have no sharing.
928 // * `--passive-segments` - all memory segments should be passive to
929 // prevent each module instantiation from reinitializing memory.
931 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
932 // linker will synthesize this function, and so we need to make sure
933 // that our usage of `--export` below won't accidentally cause this
934 // function to get deleted.
936 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
937 // symbols are how the TLS segments are initialized and configured.
938 let atomics = sess.opts.cg.target_feature.contains("+atomics") ||
939 sess.target.target.options.features.contains("+atomics");
941 cmd.arg("--shared-memory");
942 cmd.arg("--max-memory=1073741824");
943 cmd.arg("--import-memory");
944 cmd.arg("--passive-segments");
945 cmd.arg("--export=__wasm_init_memory");
946 cmd.arg("--export=__wasm_init_tls");
947 cmd.arg("--export=__tls_size");
948 cmd.arg("--export=__tls_align");
949 cmd.arg("--export=__tls_base");
951 WasmLd { cmd, sess, info }
955 impl<'a> Linker for WasmLd<'a> {
956 fn link_dylib(&mut self, lib: Symbol) {
957 self.cmd.arg("-l").sym_arg(lib);
960 fn link_staticlib(&mut self, lib: Symbol) {
961 self.cmd.arg("-l").sym_arg(lib);
964 fn link_rlib(&mut self, lib: &Path) {
968 fn include_path(&mut self, path: &Path) {
969 self.cmd.arg("-L").arg(path);
972 fn framework_path(&mut self, _path: &Path) {
973 panic!("frameworks not supported")
976 fn output_filename(&mut self, path: &Path) {
977 self.cmd.arg("-o").arg(path);
980 fn add_object(&mut self, path: &Path) {
984 fn position_independent_executable(&mut self) {
987 fn full_relro(&mut self) {
990 fn partial_relro(&mut self) {
993 fn no_relro(&mut self) {
996 fn build_static_executable(&mut self) {
999 fn args(&mut self, args: &[String]) {
1000 self.cmd.args(args);
1003 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1004 self.cmd.arg("-l").sym_arg(lib);
1007 fn link_framework(&mut self, _framework: Symbol) {
1008 panic!("frameworks not supported")
1011 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1012 self.cmd.arg("-l").sym_arg(lib);
1015 fn link_whole_rlib(&mut self, lib: &Path) {
1019 fn gc_sections(&mut self, _keep_metadata: bool) {
1020 self.cmd.arg("--gc-sections");
1023 fn optimize(&mut self) {
1024 self.cmd.arg(match self.sess.opts.optimize {
1025 OptLevel::No => "-O0",
1026 OptLevel::Less => "-O1",
1027 OptLevel::Default => "-O2",
1028 OptLevel::Aggressive => "-O3",
1029 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1031 OptLevel::Size => "-O2",
1032 OptLevel::SizeMin => "-O2"
1036 fn pgo_gen(&mut self) {
1039 fn debuginfo(&mut self) {
1042 fn no_default_libraries(&mut self) {
1045 fn build_dylib(&mut self, _out_filename: &Path) {
1046 self.cmd.arg("--no-entry");
1049 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1050 for sym in self.info.exports[&crate_type].iter() {
1051 self.cmd.arg("--export").arg(&sym);
1054 // LLD will hide these otherwise-internal symbols since our `--export`
1055 // list above is a whitelist of what to export. Various bits and pieces
1056 // of tooling use this, so be sure these symbols make their way out of
1057 // the linker as well.
1058 self.cmd.arg("--export=__heap_base");
1059 self.cmd.arg("--export=__data_end");
1062 fn subsystem(&mut self, _subsystem: &str) {
1065 fn no_position_independent_executable(&mut self) {
1068 fn finalize(&mut self) -> Command {
1069 ::std::mem::replace(&mut self.cmd, Command::new(""))
1072 // Not needed for now with LLD
1073 fn group_start(&mut self) {}
1074 fn group_end(&mut self) {}
1076 fn linker_plugin_lto(&mut self) {
1077 // Do nothing for now
1081 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1082 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1083 return exports.clone()
1086 let mut symbols = Vec::new();
1088 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1089 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1090 if level.is_below_threshold(export_threshold) {
1091 symbols.push(symbol.symbol_name(tcx).to_string());
1095 let formats = tcx.sess.dependency_formats.borrow();
1096 let deps = formats[&crate_type].iter();
1098 for (index, dep_format) in deps.enumerate() {
1099 let cnum = CrateNum::new(index + 1);
1100 // For each dependency that we are linking to statically ...
1101 if *dep_format == Linkage::Static {
1102 // ... we add its symbol list to our export list.
1103 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1104 if level.is_below_threshold(export_threshold) {
1105 symbols.push(symbol.symbol_name(tcx).to_string());
1114 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1115 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1116 pub struct PtxLinker<'a> {
1121 impl<'a> Linker for PtxLinker<'a> {
1122 fn link_rlib(&mut self, path: &Path) {
1123 self.cmd.arg("--rlib").arg(path);
1126 fn link_whole_rlib(&mut self, path: &Path) {
1127 self.cmd.arg("--rlib").arg(path);
1130 fn include_path(&mut self, path: &Path) {
1131 self.cmd.arg("-L").arg(path);
1134 fn debuginfo(&mut self) {
1135 self.cmd.arg("--debug");
1138 fn add_object(&mut self, path: &Path) {
1139 self.cmd.arg("--bitcode").arg(path);
1142 fn args(&mut self, args: &[String]) {
1143 self.cmd.args(args);
1146 fn optimize(&mut self) {
1147 match self.sess.lto() {
1148 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1149 self.cmd.arg("-Olto");
1156 fn output_filename(&mut self, path: &Path) {
1157 self.cmd.arg("-o").arg(path);
1160 fn finalize(&mut self) -> Command {
1161 // Provide the linker with fallback to internal `target-cpu`.
1162 self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1164 None => &self.sess.target.target.options.cpu
1167 ::std::mem::replace(&mut self.cmd, Command::new(""))
1170 fn link_dylib(&mut self, _lib: Symbol) {
1171 panic!("external dylibs not supported")
1174 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1175 panic!("external dylibs not supported")
1178 fn link_staticlib(&mut self, _lib: Symbol) {
1179 panic!("staticlibs not supported")
1182 fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1183 panic!("staticlibs not supported")
1186 fn framework_path(&mut self, _path: &Path) {
1187 panic!("frameworks not supported")
1190 fn link_framework(&mut self, _framework: Symbol) {
1191 panic!("frameworks not supported")
1194 fn position_independent_executable(&mut self) {
1197 fn full_relro(&mut self) {
1200 fn partial_relro(&mut self) {
1203 fn no_relro(&mut self) {
1206 fn build_static_executable(&mut self) {
1209 fn gc_sections(&mut self, _keep_metadata: bool) {
1212 fn pgo_gen(&mut self) {
1215 fn no_default_libraries(&mut self) {
1218 fn build_dylib(&mut self, _out_filename: &Path) {
1221 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
1224 fn subsystem(&mut self, _subsystem: &str) {
1227 fn no_position_independent_executable(&mut self) {
1230 fn group_start(&mut self) {
1233 fn group_end(&mut self) {
1236 fn linker_plugin_lto(&mut self) {