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 std::collections::HashMap;
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};
30 /// For all the linkers we support, and information they might
31 /// need out of the shared crate context before we get rid of it.
32 pub struct LinkerInfo {
33 exports: HashMap<CrateType, Vec<String>>,
37 pub fn new(tcx: TyCtxt) -> LinkerInfo {
39 exports: tcx.sess.crate_types.borrow().iter().map(|&c| {
40 (c, exported_symbols(tcx, c))
45 pub fn to_linker<'a>(&'a self,
47 sess: &'a Session) -> Box<dyn Linker+'a> {
48 match sess.linker_flavor() {
49 LinkerFlavor::Lld(LldFlavor::Link) |
50 LinkerFlavor::Msvc => {
64 LinkerFlavor::Gcc => {
74 LinkerFlavor::Lld(LldFlavor::Ld) |
75 LinkerFlavor::Lld(LldFlavor::Ld64) |
86 LinkerFlavor::Lld(LldFlavor::Wasm) => {
96 /// Linker abstraction used by back::link to build up the command to invoke a
99 /// This trait is the total list of requirements needed by `back::link` and
100 /// represents the meaning of each option being passed down. This trait is then
101 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
102 /// MSVC linker (e.g. `link.exe`) is being used.
104 fn link_dylib(&mut self, lib: &str);
105 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
106 fn link_framework(&mut self, framework: &str);
107 fn link_staticlib(&mut self, lib: &str);
108 fn link_rlib(&mut self, lib: &Path);
109 fn link_whole_rlib(&mut self, lib: &Path);
110 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
111 fn include_path(&mut self, path: &Path);
112 fn framework_path(&mut self, path: &Path);
113 fn output_filename(&mut self, path: &Path);
114 fn add_object(&mut self, path: &Path);
115 fn gc_sections(&mut self, keep_metadata: bool);
116 fn position_independent_executable(&mut self);
117 fn no_position_independent_executable(&mut self);
118 fn full_relro(&mut self);
119 fn partial_relro(&mut self);
120 fn no_relro(&mut self);
121 fn optimize(&mut self);
122 fn pgo_gen(&mut self);
123 fn debuginfo(&mut self);
124 fn no_default_libraries(&mut self);
125 fn build_dylib(&mut self, out_filename: &Path);
126 fn build_static_executable(&mut self);
127 fn args(&mut self, args: &[String]);
128 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
129 fn subsystem(&mut self, subsystem: &str);
130 fn group_start(&mut self);
131 fn group_end(&mut self);
132 fn cross_lang_lto(&mut self);
133 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
134 fn finalize(&mut self) -> Command;
137 pub struct GccLinker<'a> {
140 info: &'a LinkerInfo,
141 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 !self.sess.target.target.options.is_like_osx
167 // Some platforms take hints about whether a library is static or dynamic.
168 // For those that support this, we ensure we pass the option if the library
169 // was flagged "static" (most defaults are dynamic) to ensure that if
170 // libfoo.a and libfoo.so both exist that the right one is chosen.
171 fn hint_static(&mut self) {
172 if !self.takes_hints() { return }
173 if !self.hinted_static {
174 self.linker_arg("-Bstatic");
175 self.hinted_static = true;
179 fn hint_dynamic(&mut self) {
180 if !self.takes_hints() { return }
181 if self.hinted_static {
182 self.linker_arg("-Bdynamic");
183 self.hinted_static = false;
187 fn push_cross_lang_lto_args(&mut self, plugin_path: Option<&OsStr>) {
188 if let Some(plugin_path) = plugin_path {
189 let mut arg = OsString::from("-plugin=");
190 arg.push(plugin_path);
191 self.linker_arg(&arg);
194 let opt_level = match self.sess.opts.optimize {
195 config::OptLevel::No => "O0",
196 config::OptLevel::Less => "O1",
197 config::OptLevel::Default => "O2",
198 config::OptLevel::Aggressive => "O3",
199 config::OptLevel::Size => "Os",
200 config::OptLevel::SizeMin => "Oz",
203 self.linker_arg(&format!("-plugin-opt={}", opt_level));
204 self.linker_arg(&format!("-plugin-opt=mcpu={}", self.sess.target_cpu()));
206 match self.sess.opts.cg.lto {
208 config::Lto::ThinLocal => {
209 self.linker_arg("-plugin-opt=thin");
214 // default to regular LTO
220 impl<'a> Linker for GccLinker<'a> {
221 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}",lib)); }
222 fn link_staticlib(&mut self, lib: &str) {
223 self.hint_static(); self.cmd.arg(format!("-l{}",lib));
225 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
226 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
227 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
228 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
229 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
230 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
231 fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
232 fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
233 fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
234 fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
235 fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
236 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
238 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
240 self.cmd.arg(format!("-l{}",lib));
243 fn link_framework(&mut self, framework: &str) {
245 self.cmd.arg("-framework").arg(framework);
248 // Here we explicitly ask that the entire archive is included into the
249 // result artifact. For more details see #15460, but the gist is that
250 // the linker will strip away any unused objects in the archive if we
251 // don't otherwise explicitly reference them. This can occur for
252 // libraries which are just providing bindings, libraries with generic
254 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
256 let target = &self.sess.target.target;
257 if !target.options.is_like_osx {
258 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}",lib));
259 self.linker_arg("--no-whole-archive");
261 // -force_load is the macOS equivalent of --whole-archive, but it
262 // involves passing the full path to the library to link.
263 self.linker_arg("-force_load");
264 let lib = archive::find_library(lib, search_path, &self.sess);
265 self.linker_arg(&lib);
269 fn link_whole_rlib(&mut self, lib: &Path) {
271 if self.sess.target.target.options.is_like_osx {
272 self.linker_arg("-force_load");
273 self.linker_arg(&lib);
275 self.linker_arg("--whole-archive").cmd.arg(lib);
276 self.linker_arg("--no-whole-archive");
280 fn gc_sections(&mut self, keep_metadata: bool) {
281 // The dead_strip option to the linker specifies that functions and data
282 // unreachable by the entry point will be removed. This is quite useful
283 // with Rust's compilation model of compiling libraries at a time into
284 // one object file. For example, this brings hello world from 1.7MB to
287 // Note that this is done for both executables and dynamic libraries. We
288 // won't get much benefit from dylibs because LLVM will have already
289 // stripped away as much as it could. This has not been seen to impact
290 // link times negatively.
292 // -dead_strip can't be part of the pre_link_args because it's also used
293 // for partial linking when using multiple codegen units (-r). So we
295 if self.sess.target.target.options.is_like_osx {
296 self.linker_arg("-dead_strip");
297 } else if self.sess.target.target.options.is_like_solaris {
298 self.linker_arg("-zignore");
300 // If we're building a dylib, we don't use --gc-sections because LLVM
301 // has already done the best it can do, and we also don't want to
302 // eliminate the metadata. If we're building an executable, however,
303 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
305 } else if !keep_metadata {
306 self.linker_arg("--gc-sections");
310 fn optimize(&mut self) {
311 if !self.sess.target.target.options.linker_is_gnu { return }
313 // GNU-style linkers support optimization with -O. GNU ld doesn't
314 // need a numeric argument, but other linkers do.
315 if self.sess.opts.optimize == config::OptLevel::Default ||
316 self.sess.opts.optimize == config::OptLevel::Aggressive {
317 self.linker_arg("-O1");
321 fn pgo_gen(&mut self) {
322 if !self.sess.target.target.options.linker_is_gnu { return }
324 // If we're doing PGO generation stuff and on a GNU-like linker, use the
325 // "-u" flag to properly pull in the profiler runtime bits.
327 // This is because LLVM otherwise won't add the needed initialization
328 // for us on Linux (though the extra flag should be harmless if it
331 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
333 // Though it may be worth to try to revert those changes upstream, since
334 // the overhead of the initialization should be minor.
336 self.cmd.arg("__llvm_profile_runtime");
339 fn debuginfo(&mut self) {
340 match self.sess.opts.debuginfo {
342 // If we are building without debuginfo enabled and we were called with
343 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
344 // found when linking to get rid of symbols from libstd.
345 match self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
346 Some(true) => { self.linker_arg("-S"); },
354 fn no_default_libraries(&mut self) {
356 self.cmd.arg("-nodefaultlibs");
360 fn build_dylib(&mut self, out_filename: &Path) {
361 // On mac we need to tell the linker to let this library be rpathed
362 if self.sess.target.target.options.is_like_osx {
363 self.cmd.arg("-dynamiclib");
364 self.linker_arg("-dylib");
366 // Note that the `osx_rpath_install_name` option here is a hack
367 // purely to support rustbuild right now, we should get a more
368 // principled solution at some point to force the compiler to pass
369 // the right `-Wl,-install_name` with an `@rpath` in it.
370 if self.sess.opts.cg.rpath ||
371 self.sess.opts.debugging_opts.osx_rpath_install_name {
372 self.linker_arg("-install_name");
373 let mut v = OsString::from("@rpath/");
374 v.push(out_filename.file_name().unwrap());
378 self.cmd.arg("-shared");
382 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
383 // If we're compiling a dylib, then we let symbol visibility in object
384 // files to take care of whether they're exported or not.
386 // If we're compiling a cdylib, however, we manually create a list of
387 // exported symbols to ensure we don't expose any more. The object files
388 // have far more public symbols than we actually want to export, so we
389 // hide them all here.
390 if crate_type == CrateType::Dylib ||
391 crate_type == CrateType::ProcMacro {
395 let mut arg = OsString::new();
396 let path = tmpdir.join("list");
398 debug!("EXPORTED SYMBOLS:");
400 if self.sess.target.target.options.is_like_osx {
401 // Write a plain, newline-separated list of symbols
402 let res = (|| -> io::Result<()> {
403 let mut f = BufWriter::new(File::create(&path)?);
404 for sym in self.info.exports[&crate_type].iter() {
406 writeln!(f, "_{}", sym)?;
410 if let Err(e) = res {
411 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
414 // Write an LD version script
415 let res = (|| -> io::Result<()> {
416 let mut f = BufWriter::new(File::create(&path)?);
417 writeln!(f, "{{\n global:")?;
418 for sym in self.info.exports[&crate_type].iter() {
420 writeln!(f, " {};", sym)?;
422 writeln!(f, "\n local:\n *;\n}};")?;
425 if let Err(e) = res {
426 self.sess.fatal(&format!("failed to write version script: {}", e));
430 if self.sess.target.target.options.is_like_osx {
434 arg.push("-exported_symbols_list,");
435 } else if self.sess.target.target.options.is_like_solaris {
444 arg.push("--version-script=");
451 fn subsystem(&mut self, subsystem: &str) {
452 self.linker_arg("--subsystem");
453 self.linker_arg(&subsystem);
456 fn finalize(&mut self) -> Command {
457 self.hint_dynamic(); // Reset to default before returning the composed command line.
458 let mut cmd = Command::new("");
459 ::std::mem::swap(&mut cmd, &mut self.cmd);
463 fn group_start(&mut self) {
464 if !self.sess.target.target.options.is_like_osx {
465 self.linker_arg("--start-group");
469 fn group_end(&mut self) {
470 if !self.sess.target.target.options.is_like_osx {
471 self.linker_arg("--end-group");
475 fn cross_lang_lto(&mut self) {
476 match self.sess.opts.debugging_opts.cross_lang_lto {
477 CrossLangLto::Disabled => {
480 CrossLangLto::LinkerPluginAuto => {
481 self.push_cross_lang_lto_args(None);
483 CrossLangLto::LinkerPlugin(ref path) => {
484 self.push_cross_lang_lto_args(Some(path.as_os_str()));
490 pub struct MsvcLinker<'a> {
496 impl<'a> Linker for MsvcLinker<'a> {
497 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
498 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
499 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
501 fn build_dylib(&mut self, out_filename: &Path) {
502 self.cmd.arg("/DLL");
503 let mut arg: OsString = "/IMPLIB:".into();
504 arg.push(out_filename.with_extension("dll.lib"));
508 fn build_static_executable(&mut self) {
512 fn gc_sections(&mut self, _keep_metadata: bool) {
513 // MSVC's ICF (Identical COMDAT Folding) link optimization is
514 // slow for Rust and thus we disable it by default when not in
515 // optimization build.
516 if self.sess.opts.optimize != config::OptLevel::No {
517 self.cmd.arg("/OPT:REF,ICF");
519 // It is necessary to specify NOICF here, because /OPT:REF
520 // implies ICF by default.
521 self.cmd.arg("/OPT:REF,NOICF");
525 fn link_dylib(&mut self, lib: &str) {
526 self.cmd.arg(&format!("{}.lib", lib));
529 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
530 // When producing a dll, the MSVC linker may not actually emit a
531 // `foo.lib` file if the dll doesn't actually export any symbols, so we
532 // check to see if the file is there and just omit linking to it if it's
534 let name = format!("{}.dll.lib", lib);
535 if fs::metadata(&path.join(&name)).is_ok() {
540 fn link_staticlib(&mut self, lib: &str) {
541 self.cmd.arg(&format!("{}.lib", lib));
544 fn position_independent_executable(&mut self) {
548 fn no_position_independent_executable(&mut self) {
552 fn full_relro(&mut self) {
556 fn partial_relro(&mut self) {
560 fn no_relro(&mut self) {
564 fn no_default_libraries(&mut self) {
565 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
566 // as there's been trouble in the past of linking the C++ standard
567 // library required by LLVM. This likely needs to happen one day, but
568 // in general Windows is also a more controlled environment than
569 // Unix, so it's not necessarily as critical that this be implemented.
571 // Note that there are also some licensing worries about statically
572 // linking some libraries which require a specific agreement, so it may
573 // not ever be possible for us to pass this flag.
576 fn include_path(&mut self, path: &Path) {
577 let mut arg = OsString::from("/LIBPATH:");
582 fn output_filename(&mut self, path: &Path) {
583 let mut arg = OsString::from("/OUT:");
588 fn framework_path(&mut self, _path: &Path) {
589 bug!("frameworks are not supported on windows")
591 fn link_framework(&mut self, _framework: &str) {
592 bug!("frameworks are not supported on windows")
595 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
597 self.link_staticlib(lib);
599 fn link_whole_rlib(&mut self, path: &Path) {
601 self.link_rlib(path);
603 fn optimize(&mut self) {
604 // Needs more investigation of `/OPT` arguments
607 fn pgo_gen(&mut self) {
608 // Nothing needed here.
611 fn debuginfo(&mut self) {
612 // This will cause the Microsoft linker to generate a PDB file
613 // from the CodeView line tables in the object files.
614 self.cmd.arg("/DEBUG");
616 // This will cause the Microsoft linker to embed .natvis info into the the PDB file
617 let sysroot = self.sess.sysroot();
618 let natvis_dir_path = sysroot.join("lib\\rustlib\\etc");
619 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
620 // LLVM 5.0.0's lld-link frontend doesn't yet recognize, and chokes
621 // on, the /NATVIS:... flags. LLVM 6 (or earlier) should at worst ignore
622 // them, eventually mooting this workaround, per this landed patch:
623 // https://github.com/llvm-mirror/lld/commit/27b9c4285364d8d76bb43839daa100
624 if let Some(ref linker_path) = self.sess.opts.cg.linker {
625 if let Some(linker_name) = Path::new(&linker_path).file_stem() {
626 if linker_name.to_str().unwrap().to_lowercase() == "lld-link" {
627 self.sess.warn("not embedding natvis: lld-link may not support the flag");
632 for entry in natvis_dir {
635 let path = entry.path();
636 if path.extension() == Some("natvis".as_ref()) {
637 let mut arg = OsString::from("/NATVIS:");
643 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
650 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
651 // export symbols from a dynamic library. When building a dynamic library,
652 // however, we're going to want some symbols exported, so this function
653 // generates a DEF file which lists all the symbols.
655 // The linker will read this `*.def` file and export all the symbols from
656 // the dynamic library. Note that this is not as simple as just exporting
657 // all the symbols in the current crate (as specified by `codegen.reachable`)
658 // but rather we also need to possibly export the symbols of upstream
659 // crates. Upstream rlibs may be linked statically to this dynamic library,
660 // in which case they may continue to transitively be used and hence need
661 // their symbols exported.
662 fn export_symbols(&mut self,
664 crate_type: CrateType) {
665 let path = tmpdir.join("lib.def");
666 let res = (|| -> io::Result<()> {
667 let mut f = BufWriter::new(File::create(&path)?);
669 // Start off with the standard module name header and then go
670 // straight to exports.
671 writeln!(f, "LIBRARY")?;
672 writeln!(f, "EXPORTS")?;
673 for symbol in self.info.exports[&crate_type].iter() {
674 debug!(" _{}", symbol);
675 writeln!(f, " {}", symbol)?;
679 if let Err(e) = res {
680 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
682 let mut arg = OsString::from("/DEF:");
687 fn subsystem(&mut self, subsystem: &str) {
688 // Note that previous passes of the compiler validated this subsystem,
689 // so we just blindly pass it to the linker.
690 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
692 // Windows has two subsystems we're interested in right now, the console
693 // and windows subsystems. These both implicitly have different entry
694 // points (starting symbols). The console entry point starts with
695 // `mainCRTStartup` and the windows entry point starts with
696 // `WinMainCRTStartup`. These entry points, defined in system libraries,
697 // will then later probe for either `main` or `WinMain`, respectively to
698 // start the application.
700 // In Rust we just always generate a `main` function so we want control
701 // to always start there, so we force the entry point on the windows
702 // subsystem to be `mainCRTStartup` to get everything booted up
705 // For more information see RFC #1665
706 if subsystem == "windows" {
707 self.cmd.arg("/ENTRY:mainCRTStartup");
711 fn finalize(&mut self) -> Command {
712 let mut cmd = Command::new("");
713 ::std::mem::swap(&mut cmd, &mut self.cmd);
717 // MSVC doesn't need group indicators
718 fn group_start(&mut self) {}
719 fn group_end(&mut self) {}
721 fn cross_lang_lto(&mut self) {
726 pub struct EmLinker<'a> {
732 impl<'a> Linker for EmLinker<'a> {
733 fn include_path(&mut self, path: &Path) {
734 self.cmd.arg("-L").arg(path);
737 fn link_staticlib(&mut self, lib: &str) {
738 self.cmd.arg("-l").arg(lib);
741 fn output_filename(&mut self, path: &Path) {
742 self.cmd.arg("-o").arg(path);
745 fn add_object(&mut self, path: &Path) {
749 fn link_dylib(&mut self, lib: &str) {
750 // Emscripten always links statically
751 self.link_staticlib(lib);
754 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
756 self.link_staticlib(lib);
759 fn link_whole_rlib(&mut self, lib: &Path) {
764 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
765 self.link_dylib(lib);
768 fn link_rlib(&mut self, lib: &Path) {
769 self.add_object(lib);
772 fn position_independent_executable(&mut self) {
776 fn no_position_independent_executable(&mut self) {
780 fn full_relro(&mut self) {
784 fn partial_relro(&mut self) {
788 fn no_relro(&mut self) {
792 fn args(&mut self, args: &[String]) {
796 fn framework_path(&mut self, _path: &Path) {
797 bug!("frameworks are not supported on Emscripten")
800 fn link_framework(&mut self, _framework: &str) {
801 bug!("frameworks are not supported on Emscripten")
804 fn gc_sections(&mut self, _keep_metadata: bool) {
808 fn optimize(&mut self) {
809 // Emscripten performs own optimizations
810 self.cmd.arg(match self.sess.opts.optimize {
811 OptLevel::No => "-O0",
812 OptLevel::Less => "-O1",
813 OptLevel::Default => "-O2",
814 OptLevel::Aggressive => "-O3",
815 OptLevel::Size => "-Os",
816 OptLevel::SizeMin => "-Oz"
818 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
819 self.cmd.args(&["--memory-init-file", "0"]);
822 fn pgo_gen(&mut self) {
823 // noop, but maybe we need something like the gnu linker?
826 fn debuginfo(&mut self) {
827 // Preserve names or generate source maps depending on debug info
828 self.cmd.arg(match self.sess.opts.debuginfo {
829 DebugInfo::None => "-g0",
830 DebugInfo::Limited => "-g3",
831 DebugInfo::Full => "-g4"
835 fn no_default_libraries(&mut self) {
836 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
839 fn build_dylib(&mut self, _out_filename: &Path) {
840 bug!("building dynamic library is unsupported on Emscripten")
843 fn build_static_executable(&mut self) {
847 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
848 let symbols = &self.info.exports[&crate_type];
850 debug!("EXPORTED SYMBOLS:");
854 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
855 let mut encoded = String::new();
858 let mut encoder = json::Encoder::new(&mut encoded);
859 let res = encoder.emit_seq(symbols.len(), |encoder| {
860 for (i, sym) in symbols.iter().enumerate() {
861 encoder.emit_seq_elt(i, |encoder| {
862 encoder.emit_str(&("_".to_string() + sym))
867 if let Err(e) = res {
868 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
871 debug!("{}", encoded);
877 fn subsystem(&mut self, _subsystem: &str) {
881 fn finalize(&mut self) -> Command {
882 let mut cmd = Command::new("");
883 ::std::mem::swap(&mut cmd, &mut self.cmd);
887 // Appears not necessary on Emscripten
888 fn group_start(&mut self) {}
889 fn group_end(&mut self) {}
891 fn cross_lang_lto(&mut self) {
896 fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
897 let mut symbols = Vec::new();
899 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
900 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
901 if level.is_below_threshold(export_threshold) {
902 symbols.push(symbol.symbol_name(tcx).to_string());
906 let formats = tcx.sess.dependency_formats.borrow();
907 let deps = formats[&crate_type].iter();
909 for (index, dep_format) in deps.enumerate() {
910 let cnum = CrateNum::new(index + 1);
911 // For each dependency that we are linking to statically ...
912 if *dep_format == Linkage::Static {
913 // ... we add its symbol list to our export list.
914 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
915 if level.is_below_threshold(export_threshold) {
916 symbols.push(symbol.symbol_name(tcx).to_string());
925 pub struct WasmLd<'a> {
930 impl<'a> Linker for WasmLd<'a> {
931 fn link_dylib(&mut self, lib: &str) {
932 self.cmd.arg("-l").arg(lib);
935 fn link_staticlib(&mut self, lib: &str) {
936 self.cmd.arg("-l").arg(lib);
939 fn link_rlib(&mut self, lib: &Path) {
943 fn include_path(&mut self, path: &Path) {
944 self.cmd.arg("-L").arg(path);
947 fn framework_path(&mut self, _path: &Path) {
948 panic!("frameworks not supported")
951 fn output_filename(&mut self, path: &Path) {
952 self.cmd.arg("-o").arg(path);
955 fn add_object(&mut self, path: &Path) {
959 fn position_independent_executable(&mut self) {
962 fn full_relro(&mut self) {
965 fn partial_relro(&mut self) {
968 fn no_relro(&mut self) {
971 fn build_static_executable(&mut self) {
974 fn args(&mut self, args: &[String]) {
978 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
979 self.cmd.arg("-l").arg(lib);
982 fn link_framework(&mut self, _framework: &str) {
983 panic!("frameworks not supported")
986 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
987 self.cmd.arg("-l").arg(lib);
990 fn link_whole_rlib(&mut self, lib: &Path) {
994 fn gc_sections(&mut self, _keep_metadata: bool) {
995 self.cmd.arg("--gc-sections");
998 fn optimize(&mut self) {
999 self.cmd.arg(match self.sess.opts.optimize {
1000 OptLevel::No => "-O0",
1001 OptLevel::Less => "-O1",
1002 OptLevel::Default => "-O2",
1003 OptLevel::Aggressive => "-O3",
1004 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1006 OptLevel::Size => "-O2",
1007 OptLevel::SizeMin => "-O2"
1011 fn pgo_gen(&mut self) {
1014 fn debuginfo(&mut self) {
1017 fn no_default_libraries(&mut self) {
1020 fn build_dylib(&mut self, _out_filename: &Path) {
1023 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
1026 fn subsystem(&mut self, _subsystem: &str) {
1029 fn no_position_independent_executable(&mut self) {
1032 fn finalize(&mut self) -> Command {
1033 // There have been reports in the wild (rustwasm/wasm-bindgen#119) of
1034 // using threads causing weird hangs and bugs. Disable it entirely as
1035 // this isn't yet the bottleneck of compilation at all anyway.
1036 self.cmd.arg("--no-threads");
1038 // By default LLD only gives us one page of stack (64k) which is a
1039 // little small. Default to a larger stack closer to other PC platforms
1040 // (1MB) and users can always inject their own link-args to override this.
1041 self.cmd.arg("-z").arg("stack-size=1048576");
1043 // By default LLD's memory layout is:
1045 // 1. First, a blank page
1046 // 2. Next, all static data
1047 // 3. Finally, the main stack (which grows down)
1049 // This has the unfortunate consequence that on stack overflows you
1050 // corrupt static data and can cause some exceedingly weird bugs. To
1051 // help detect this a little sooner we instead request that the stack is
1052 // placed before static data.
1054 // This means that we'll generate slightly larger binaries as references
1055 // to static data will take more bytes in the ULEB128 encoding, but
1056 // stack overflow will be guaranteed to trap as it underflows instead of
1057 // corrupting static data.
1058 self.cmd.arg("--stack-first");
1060 // FIXME we probably shouldn't pass this but instead pass an explicit
1061 // whitelist of symbols we'll allow to be undefined. Unfortunately
1062 // though we can't handle symbols like `log10` that LLVM injects at a
1063 // super late date without actually parsing object files. For now let's
1064 // stick to this and hopefully fix it before stabilization happens.
1065 self.cmd.arg("--allow-undefined");
1067 // For now we just never have an entry symbol
1068 self.cmd.arg("--no-entry");
1070 // Make the default table accessible
1071 self.cmd.arg("--export-table");
1073 let mut cmd = Command::new("");
1074 ::std::mem::swap(&mut cmd, &mut self.cmd);
1078 // Not needed for now with LLD
1079 fn group_start(&mut self) {}
1080 fn group_end(&mut self) {}
1082 fn cross_lang_lto(&mut self) {
1083 // Do nothing for now