1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_data_structures::fx::FxHashMap;
12 use std::ffi::{OsStr, OsString};
13 use std::fs::{self, File};
14 use std::io::prelude::*;
15 use std::io::{self, BufWriter};
16 use std::path::{Path, PathBuf};
19 use back::command::Command;
20 use back::symbol_export;
21 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::session::Session;
24 use rustc::session::config::{self, CrateType, OptLevel, DebugInfo,
26 use rustc::ty::TyCtxt;
27 use rustc_target::spec::{LinkerFlavor, LldFlavor};
28 use serialize::{json, Encoder};
31 /// For all the linkers we support, and information they might
32 /// need out of the shared crate context before we get rid of it.
33 pub struct LinkerInfo {
34 exports: FxHashMap<CrateType, Vec<String>>,
38 pub fn new(tcx: TyCtxt) -> LinkerInfo {
40 exports: tcx.sess.crate_types.borrow().iter().map(|&c| {
41 (c, exported_symbols(tcx, c))
46 pub fn to_linker<'a>(&'a self,
49 flavor: LinkerFlavor) -> Box<dyn Linker+'a> {
51 LinkerFlavor::Lld(LldFlavor::Link) |
52 LinkerFlavor::Msvc => {
66 LinkerFlavor::Gcc => {
76 LinkerFlavor::Lld(LldFlavor::Ld) |
77 LinkerFlavor::Lld(LldFlavor::Ld64) |
88 LinkerFlavor::Lld(LldFlavor::Wasm) => {
99 /// Linker abstraction used by back::link to build up the command to invoke a
102 /// This trait is the total list of requirements needed by `back::link` and
103 /// represents the meaning of each option being passed down. This trait is then
104 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
105 /// MSVC linker (e.g. `link.exe`) is being used.
107 fn link_dylib(&mut self, lib: &str);
108 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
109 fn link_framework(&mut self, framework: &str);
110 fn link_staticlib(&mut self, lib: &str);
111 fn link_rlib(&mut self, lib: &Path);
112 fn link_whole_rlib(&mut self, lib: &Path);
113 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
114 fn include_path(&mut self, path: &Path);
115 fn framework_path(&mut self, path: &Path);
116 fn output_filename(&mut self, path: &Path);
117 fn add_object(&mut self, path: &Path);
118 fn gc_sections(&mut self, keep_metadata: bool);
119 fn position_independent_executable(&mut self);
120 fn no_position_independent_executable(&mut self);
121 fn full_relro(&mut self);
122 fn partial_relro(&mut self);
123 fn no_relro(&mut self);
124 fn optimize(&mut self);
125 fn pgo_gen(&mut self);
126 fn debuginfo(&mut self);
127 fn no_default_libraries(&mut self);
128 fn build_dylib(&mut self, out_filename: &Path);
129 fn build_static_executable(&mut self);
130 fn args(&mut self, args: &[String]);
131 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
132 fn subsystem(&mut self, subsystem: &str);
133 fn group_start(&mut self);
134 fn group_end(&mut self);
135 fn cross_lang_lto(&mut self);
136 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
137 fn finalize(&mut self) -> Command;
140 pub struct GccLinker<'a> {
143 info: &'a LinkerInfo,
144 hinted_static: bool, // Keeps track of the current hinting mode.
149 impl<'a> GccLinker<'a> {
150 /// Argument that must be passed *directly* to the linker
152 /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
153 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
154 where S: AsRef<OsStr>
157 let mut os = OsString::from("-Wl,");
158 os.push(arg.as_ref());
166 fn takes_hints(&self) -> bool {
167 !self.sess.target.target.options.is_like_osx
170 // Some platforms take hints about whether a library is static or dynamic.
171 // For those that support this, we ensure we pass the option if the library
172 // was flagged "static" (most defaults are dynamic) to ensure that if
173 // libfoo.a and libfoo.so both exist that the right one is chosen.
174 fn hint_static(&mut self) {
175 if !self.takes_hints() { return }
176 if !self.hinted_static {
177 self.linker_arg("-Bstatic");
178 self.hinted_static = true;
182 fn hint_dynamic(&mut self) {
183 if !self.takes_hints() { return }
184 if self.hinted_static {
185 self.linker_arg("-Bdynamic");
186 self.hinted_static = false;
190 fn push_cross_lang_lto_args(&mut self, plugin_path: Option<&OsStr>) {
191 if let Some(plugin_path) = plugin_path {
192 let mut arg = OsString::from("-plugin=");
193 arg.push(plugin_path);
194 self.linker_arg(&arg);
197 let opt_level = match self.sess.opts.optimize {
198 config::OptLevel::No => "O0",
199 config::OptLevel::Less => "O1",
200 config::OptLevel::Default => "O2",
201 config::OptLevel::Aggressive => "O3",
202 config::OptLevel::Size => "Os",
203 config::OptLevel::SizeMin => "Oz",
206 self.linker_arg(&format!("-plugin-opt={}", opt_level));
207 self.linker_arg(&format!("-plugin-opt=mcpu={}", llvm_util::target_cpu(self.sess)));
209 match self.sess.lto() {
211 config::Lto::ThinLocal => {
212 self.linker_arg("-plugin-opt=thin");
216 // default to regular LTO
222 impl<'a> Linker for GccLinker<'a> {
223 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}",lib)); }
224 fn link_staticlib(&mut self, lib: &str) {
225 self.hint_static(); 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: &str, _path: &Path) {
242 self.cmd.arg(format!("-l{}",lib));
245 fn link_framework(&mut self, framework: &str) {
247 self.cmd.arg("-framework").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: &str, 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 match self.sess.opts.debuginfo {
344 // If we are building without debuginfo enabled and we were called with
345 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
346 // found when linking to get rid of symbols from libstd.
347 match self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
348 Some(true) => { self.linker_arg("-S"); },
356 fn no_default_libraries(&mut self) {
358 self.cmd.arg("-nodefaultlibs");
362 fn build_dylib(&mut self, out_filename: &Path) {
363 // On mac we need to tell the linker to let this library be rpathed
364 if self.sess.target.target.options.is_like_osx {
365 self.cmd.arg("-dynamiclib");
366 self.linker_arg("-dylib");
368 // Note that the `osx_rpath_install_name` option here is a hack
369 // purely to support rustbuild right now, we should get a more
370 // principled solution at some point to force the compiler to pass
371 // the right `-Wl,-install_name` with an `@rpath` in it.
372 if self.sess.opts.cg.rpath ||
373 self.sess.opts.debugging_opts.osx_rpath_install_name {
374 self.linker_arg("-install_name");
375 let mut v = OsString::from("@rpath/");
376 v.push(out_filename.file_name().unwrap());
380 self.cmd.arg("-shared");
384 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
385 // If we're compiling a dylib, then we let symbol visibility in object
386 // files to take care of whether they're exported or not.
388 // If we're compiling a cdylib, however, we manually create a list of
389 // exported symbols to ensure we don't expose any more. The object files
390 // have far more public symbols than we actually want to export, so we
391 // hide them all here.
392 if crate_type == CrateType::Dylib ||
393 crate_type == CrateType::ProcMacro {
397 let mut arg = OsString::new();
398 let path = tmpdir.join("list");
400 debug!("EXPORTED SYMBOLS:");
402 if self.sess.target.target.options.is_like_osx {
403 // Write a plain, newline-separated list of symbols
404 let res = (|| -> io::Result<()> {
405 let mut f = BufWriter::new(File::create(&path)?);
406 for sym in self.info.exports[&crate_type].iter() {
408 writeln!(f, "_{}", sym)?;
412 if let Err(e) = res {
413 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
416 // Write an LD version script
417 let res = (|| -> io::Result<()> {
418 let mut f = BufWriter::new(File::create(&path)?);
419 writeln!(f, "{{\n global:")?;
420 for sym in self.info.exports[&crate_type].iter() {
422 writeln!(f, " {};", sym)?;
424 writeln!(f, "\n local:\n *;\n}};")?;
427 if let Err(e) = res {
428 self.sess.fatal(&format!("failed to write version script: {}", e));
432 if self.sess.target.target.options.is_like_osx {
436 arg.push("-exported_symbols_list,");
437 } else if self.sess.target.target.options.is_like_solaris {
446 arg.push("--version-script=");
453 fn subsystem(&mut self, subsystem: &str) {
454 self.linker_arg("--subsystem");
455 self.linker_arg(&subsystem);
458 fn finalize(&mut self) -> Command {
459 self.hint_dynamic(); // Reset to default before returning the composed command line.
460 let mut cmd = Command::new("");
461 ::std::mem::swap(&mut cmd, &mut self.cmd);
465 fn group_start(&mut self) {
466 if !self.sess.target.target.options.is_like_osx {
467 self.linker_arg("--start-group");
471 fn group_end(&mut self) {
472 if !self.sess.target.target.options.is_like_osx {
473 self.linker_arg("--end-group");
477 fn cross_lang_lto(&mut self) {
478 match self.sess.opts.debugging_opts.cross_lang_lto {
479 CrossLangLto::Disabled => {
482 CrossLangLto::LinkerPluginAuto => {
483 self.push_cross_lang_lto_args(None);
485 CrossLangLto::LinkerPlugin(ref path) => {
486 self.push_cross_lang_lto_args(Some(path.as_os_str()));
492 pub struct MsvcLinker<'a> {
498 impl<'a> Linker for MsvcLinker<'a> {
499 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
500 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
501 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
503 fn build_dylib(&mut self, out_filename: &Path) {
504 self.cmd.arg("/DLL");
505 let mut arg: OsString = "/IMPLIB:".into();
506 arg.push(out_filename.with_extension("dll.lib"));
510 fn build_static_executable(&mut self) {
514 fn gc_sections(&mut self, _keep_metadata: bool) {
515 // MSVC's ICF (Identical COMDAT Folding) link optimization is
516 // slow for Rust and thus we disable it by default when not in
517 // optimization build.
518 if self.sess.opts.optimize != config::OptLevel::No {
519 self.cmd.arg("/OPT:REF,ICF");
521 // It is necessary to specify NOICF here, because /OPT:REF
522 // implies ICF by default.
523 self.cmd.arg("/OPT:REF,NOICF");
527 fn link_dylib(&mut self, lib: &str) {
528 self.cmd.arg(&format!("{}.lib", lib));
531 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
532 // When producing a dll, the MSVC linker may not actually emit a
533 // `foo.lib` file if the dll doesn't actually export any symbols, so we
534 // check to see if the file is there and just omit linking to it if it's
536 let name = format!("{}.dll.lib", lib);
537 if fs::metadata(&path.join(&name)).is_ok() {
542 fn link_staticlib(&mut self, lib: &str) {
543 self.cmd.arg(&format!("{}.lib", lib));
546 fn position_independent_executable(&mut self) {
550 fn no_position_independent_executable(&mut self) {
554 fn full_relro(&mut self) {
558 fn partial_relro(&mut self) {
562 fn no_relro(&mut self) {
566 fn no_default_libraries(&mut self) {
567 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
568 // as there's been trouble in the past of linking the C++ standard
569 // library required by LLVM. This likely needs to happen one day, but
570 // in general Windows is also a more controlled environment than
571 // Unix, so it's not necessarily as critical that this be implemented.
573 // Note that there are also some licensing worries about statically
574 // linking some libraries which require a specific agreement, so it may
575 // not ever be possible for us to pass this flag.
578 fn include_path(&mut self, path: &Path) {
579 let mut arg = OsString::from("/LIBPATH:");
584 fn output_filename(&mut self, path: &Path) {
585 let mut arg = OsString::from("/OUT:");
590 fn framework_path(&mut self, _path: &Path) {
591 bug!("frameworks are not supported on windows")
593 fn link_framework(&mut self, _framework: &str) {
594 bug!("frameworks are not supported on windows")
597 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
599 self.link_staticlib(lib);
601 fn link_whole_rlib(&mut self, path: &Path) {
603 self.link_rlib(path);
605 fn optimize(&mut self) {
606 // Needs more investigation of `/OPT` arguments
609 fn pgo_gen(&mut self) {
610 // Nothing needed here.
613 fn debuginfo(&mut self) {
614 // This will cause the Microsoft linker to generate a PDB file
615 // from the CodeView line tables in the object files.
616 self.cmd.arg("/DEBUG");
618 // This will cause the Microsoft linker to embed .natvis info into the the PDB file
619 let sysroot = self.sess.sysroot();
620 let natvis_dir_path = sysroot.join("lib\\rustlib\\etc");
621 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
622 // LLVM 5.0.0's lld-link frontend doesn't yet recognize, and chokes
623 // on, the /NATVIS:... flags. LLVM 6 (or earlier) should at worst ignore
624 // them, eventually mooting this workaround, per this landed patch:
625 // https://github.com/llvm-mirror/lld/commit/27b9c4285364d8d76bb43839daa100
626 if let Some(ref linker_path) = self.sess.opts.cg.linker {
627 if let Some(linker_name) = Path::new(&linker_path).file_stem() {
628 if linker_name.to_str().unwrap().to_lowercase() == "lld-link" {
629 self.sess.warn("not embedding natvis: lld-link may not support the flag");
634 for entry in natvis_dir {
637 let path = entry.path();
638 if path.extension() == Some("natvis".as_ref()) {
639 let mut arg = OsString::from("/NATVIS:");
645 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
652 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
653 // export symbols from a dynamic library. When building a dynamic library,
654 // however, we're going to want some symbols exported, so this function
655 // generates a DEF file which lists all the symbols.
657 // The linker will read this `*.def` file and export all the symbols from
658 // the dynamic library. Note that this is not as simple as just exporting
659 // all the symbols in the current crate (as specified by `codegen.reachable`)
660 // but rather we also need to possibly export the symbols of upstream
661 // crates. Upstream rlibs may be linked statically to this dynamic library,
662 // in which case they may continue to transitively be used and hence need
663 // their symbols exported.
664 fn export_symbols(&mut self,
666 crate_type: CrateType) {
667 let path = tmpdir.join("lib.def");
668 let res = (|| -> io::Result<()> {
669 let mut f = BufWriter::new(File::create(&path)?);
671 // Start off with the standard module name header and then go
672 // straight to exports.
673 writeln!(f, "LIBRARY")?;
674 writeln!(f, "EXPORTS")?;
675 for symbol in self.info.exports[&crate_type].iter() {
676 debug!(" _{}", symbol);
677 writeln!(f, " {}", symbol)?;
681 if let Err(e) = res {
682 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
684 let mut arg = OsString::from("/DEF:");
689 fn subsystem(&mut self, subsystem: &str) {
690 // Note that previous passes of the compiler validated this subsystem,
691 // so we just blindly pass it to the linker.
692 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
694 // Windows has two subsystems we're interested in right now, the console
695 // and windows subsystems. These both implicitly have different entry
696 // points (starting symbols). The console entry point starts with
697 // `mainCRTStartup` and the windows entry point starts with
698 // `WinMainCRTStartup`. These entry points, defined in system libraries,
699 // will then later probe for either `main` or `WinMain`, respectively to
700 // start the application.
702 // In Rust we just always generate a `main` function so we want control
703 // to always start there, so we force the entry point on the windows
704 // subsystem to be `mainCRTStartup` to get everything booted up
707 // For more information see RFC #1665
708 if subsystem == "windows" {
709 self.cmd.arg("/ENTRY:mainCRTStartup");
713 fn finalize(&mut self) -> Command {
714 let mut cmd = Command::new("");
715 ::std::mem::swap(&mut cmd, &mut self.cmd);
719 // MSVC doesn't need group indicators
720 fn group_start(&mut self) {}
721 fn group_end(&mut self) {}
723 fn cross_lang_lto(&mut self) {
728 pub struct EmLinker<'a> {
734 impl<'a> Linker for EmLinker<'a> {
735 fn include_path(&mut self, path: &Path) {
736 self.cmd.arg("-L").arg(path);
739 fn link_staticlib(&mut self, lib: &str) {
740 self.cmd.arg("-l").arg(lib);
743 fn output_filename(&mut self, path: &Path) {
744 self.cmd.arg("-o").arg(path);
747 fn add_object(&mut self, path: &Path) {
751 fn link_dylib(&mut self, lib: &str) {
752 // Emscripten always links statically
753 self.link_staticlib(lib);
756 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
758 self.link_staticlib(lib);
761 fn link_whole_rlib(&mut self, lib: &Path) {
766 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
767 self.link_dylib(lib);
770 fn link_rlib(&mut self, lib: &Path) {
771 self.add_object(lib);
774 fn position_independent_executable(&mut self) {
778 fn no_position_independent_executable(&mut self) {
782 fn full_relro(&mut self) {
786 fn partial_relro(&mut self) {
790 fn no_relro(&mut self) {
794 fn args(&mut self, args: &[String]) {
798 fn framework_path(&mut self, _path: &Path) {
799 bug!("frameworks are not supported on Emscripten")
802 fn link_framework(&mut self, _framework: &str) {
803 bug!("frameworks are not supported on Emscripten")
806 fn gc_sections(&mut self, _keep_metadata: bool) {
810 fn optimize(&mut self) {
811 // Emscripten performs own optimizations
812 self.cmd.arg(match self.sess.opts.optimize {
813 OptLevel::No => "-O0",
814 OptLevel::Less => "-O1",
815 OptLevel::Default => "-O2",
816 OptLevel::Aggressive => "-O3",
817 OptLevel::Size => "-Os",
818 OptLevel::SizeMin => "-Oz"
820 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
821 self.cmd.args(&["--memory-init-file", "0"]);
824 fn pgo_gen(&mut self) {
825 // noop, but maybe we need something like the gnu linker?
828 fn debuginfo(&mut self) {
829 // Preserve names or generate source maps depending on debug info
830 self.cmd.arg(match self.sess.opts.debuginfo {
831 DebugInfo::None => "-g0",
832 DebugInfo::Limited => "-g3",
833 DebugInfo::Full => "-g4"
837 fn no_default_libraries(&mut self) {
838 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
841 fn build_dylib(&mut self, _out_filename: &Path) {
842 bug!("building dynamic library is unsupported on Emscripten")
845 fn build_static_executable(&mut self) {
849 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
850 let symbols = &self.info.exports[&crate_type];
852 debug!("EXPORTED SYMBOLS:");
856 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
857 let mut encoded = String::new();
860 let mut encoder = json::Encoder::new(&mut encoded);
861 let res = encoder.emit_seq(symbols.len(), |encoder| {
862 for (i, sym) in symbols.iter().enumerate() {
863 encoder.emit_seq_elt(i, |encoder| {
864 encoder.emit_str(&("_".to_string() + sym))
869 if let Err(e) = res {
870 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
873 debug!("{}", encoded);
879 fn subsystem(&mut self, _subsystem: &str) {
883 fn finalize(&mut self) -> Command {
884 let mut cmd = Command::new("");
885 ::std::mem::swap(&mut cmd, &mut self.cmd);
889 // Appears not necessary on Emscripten
890 fn group_start(&mut self) {}
891 fn group_end(&mut self) {}
893 fn cross_lang_lto(&mut self) {
898 fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
899 let mut symbols = Vec::new();
901 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
902 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
903 if level.is_below_threshold(export_threshold) {
904 symbols.push(symbol.symbol_name(tcx).to_string());
908 let formats = tcx.sess.dependency_formats.borrow();
909 let deps = formats[&crate_type].iter();
911 for (index, dep_format) in deps.enumerate() {
912 let cnum = CrateNum::new(index + 1);
913 // For each dependency that we are linking to statically ...
914 if *dep_format == Linkage::Static {
915 // ... we add its symbol list to our export list.
916 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
917 if level.is_below_threshold(export_threshold) {
918 symbols.push(symbol.symbol_name(tcx).to_string());
927 pub struct WasmLd<'a> {
930 info: &'a LinkerInfo,
933 impl<'a> Linker for WasmLd<'a> {
934 fn link_dylib(&mut self, lib: &str) {
935 self.cmd.arg("-l").arg(lib);
938 fn link_staticlib(&mut self, lib: &str) {
939 self.cmd.arg("-l").arg(lib);
942 fn link_rlib(&mut self, lib: &Path) {
946 fn include_path(&mut self, path: &Path) {
947 self.cmd.arg("-L").arg(path);
950 fn framework_path(&mut self, _path: &Path) {
951 panic!("frameworks not supported")
954 fn output_filename(&mut self, path: &Path) {
955 self.cmd.arg("-o").arg(path);
958 fn add_object(&mut self, path: &Path) {
962 fn position_independent_executable(&mut self) {
965 fn full_relro(&mut self) {
968 fn partial_relro(&mut self) {
971 fn no_relro(&mut self) {
974 fn build_static_executable(&mut self) {
977 fn args(&mut self, args: &[String]) {
981 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
982 self.cmd.arg("-l").arg(lib);
985 fn link_framework(&mut self, _framework: &str) {
986 panic!("frameworks not supported")
989 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
990 self.cmd.arg("-l").arg(lib);
993 fn link_whole_rlib(&mut self, lib: &Path) {
997 fn gc_sections(&mut self, _keep_metadata: bool) {
998 self.cmd.arg("--gc-sections");
1001 fn optimize(&mut self) {
1002 self.cmd.arg(match self.sess.opts.optimize {
1003 OptLevel::No => "-O0",
1004 OptLevel::Less => "-O1",
1005 OptLevel::Default => "-O2",
1006 OptLevel::Aggressive => "-O3",
1007 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1009 OptLevel::Size => "-O2",
1010 OptLevel::SizeMin => "-O2"
1014 fn pgo_gen(&mut self) {
1017 fn debuginfo(&mut self) {
1020 fn no_default_libraries(&mut self) {
1023 fn build_dylib(&mut self, _out_filename: &Path) {
1026 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1027 for sym in self.info.exports[&crate_type].iter() {
1028 self.cmd.arg("--export").arg(&sym);
1032 fn subsystem(&mut self, _subsystem: &str) {
1035 fn no_position_independent_executable(&mut self) {
1038 fn finalize(&mut self) -> Command {
1039 // There have been reports in the wild (rustwasm/wasm-bindgen#119) of
1040 // using threads causing weird hangs and bugs. Disable it entirely as
1041 // this isn't yet the bottleneck of compilation at all anyway.
1042 self.cmd.arg("--no-threads");
1044 // By default LLD only gives us one page of stack (64k) which is a
1045 // little small. Default to a larger stack closer to other PC platforms
1046 // (1MB) and users can always inject their own link-args to override this.
1047 self.cmd.arg("-z").arg("stack-size=1048576");
1049 // By default LLD's memory layout is:
1051 // 1. First, a blank page
1052 // 2. Next, all static data
1053 // 3. Finally, the main stack (which grows down)
1055 // This has the unfortunate consequence that on stack overflows you
1056 // corrupt static data and can cause some exceedingly weird bugs. To
1057 // help detect this a little sooner we instead request that the stack is
1058 // placed before static data.
1060 // This means that we'll generate slightly larger binaries as references
1061 // to static data will take more bytes in the ULEB128 encoding, but
1062 // stack overflow will be guaranteed to trap as it underflows instead of
1063 // corrupting static data.
1064 self.cmd.arg("--stack-first");
1066 // FIXME we probably shouldn't pass this but instead pass an explicit
1067 // whitelist of symbols we'll allow to be undefined. Unfortunately
1068 // though we can't handle symbols like `log10` that LLVM injects at a
1069 // super late date without actually parsing object files. For now let's
1070 // stick to this and hopefully fix it before stabilization happens.
1071 self.cmd.arg("--allow-undefined");
1073 // For now we just never have an entry symbol
1074 self.cmd.arg("--no-entry");
1076 // Make the default table accessible
1077 self.cmd.arg("--export-table");
1079 // Rust code should never have warnings, and warnings are often
1080 // indicative of bugs, let's prevent them.
1081 self.cmd.arg("--fatal-warnings");
1083 let mut cmd = Command::new("");
1084 ::std::mem::swap(&mut cmd, &mut self.cmd);
1088 // Not needed for now with LLD
1089 fn group_start(&mut self) {}
1090 fn group_end(&mut self) {}
1092 fn cross_lang_lto(&mut self) {
1093 // Do nothing for now