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) => {
98 /// Linker abstraction used by back::link to build up the command to invoke a
101 /// This trait is the total list of requirements needed by `back::link` and
102 /// represents the meaning of each option being passed down. This trait is then
103 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
104 /// MSVC linker (e.g. `link.exe`) is being used.
106 fn link_dylib(&mut self, lib: &str);
107 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
108 fn link_framework(&mut self, framework: &str);
109 fn link_staticlib(&mut self, lib: &str);
110 fn link_rlib(&mut self, lib: &Path);
111 fn link_whole_rlib(&mut self, lib: &Path);
112 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
113 fn include_path(&mut self, path: &Path);
114 fn framework_path(&mut self, path: &Path);
115 fn output_filename(&mut self, path: &Path);
116 fn add_object(&mut self, path: &Path);
117 fn gc_sections(&mut self, keep_metadata: bool);
118 fn position_independent_executable(&mut self);
119 fn no_position_independent_executable(&mut self);
120 fn full_relro(&mut self);
121 fn partial_relro(&mut self);
122 fn no_relro(&mut self);
123 fn optimize(&mut self);
124 fn pgo_gen(&mut self);
125 fn debuginfo(&mut self);
126 fn no_default_libraries(&mut self);
127 fn build_dylib(&mut self, out_filename: &Path);
128 fn build_static_executable(&mut self);
129 fn args(&mut self, args: &[String]);
130 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
131 fn subsystem(&mut self, subsystem: &str);
132 fn group_start(&mut self);
133 fn group_end(&mut self);
134 fn cross_lang_lto(&mut self);
135 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
136 fn finalize(&mut self) -> Command;
139 pub struct GccLinker<'a> {
142 info: &'a LinkerInfo,
143 hinted_static: bool, // Keeps track of the current hinting mode.
148 impl<'a> GccLinker<'a> {
149 /// Argument that must be passed *directly* to the linker
151 /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
152 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
153 where S: AsRef<OsStr>
156 let mut os = OsString::from("-Wl,");
157 os.push(arg.as_ref());
165 fn takes_hints(&self) -> bool {
166 !self.sess.target.target.options.is_like_osx
169 // Some platforms take hints about whether a library is static or dynamic.
170 // For those that support this, we ensure we pass the option if the library
171 // was flagged "static" (most defaults are dynamic) to ensure that if
172 // libfoo.a and libfoo.so both exist that the right one is chosen.
173 fn hint_static(&mut self) {
174 if !self.takes_hints() { return }
175 if !self.hinted_static {
176 self.linker_arg("-Bstatic");
177 self.hinted_static = true;
181 fn hint_dynamic(&mut self) {
182 if !self.takes_hints() { return }
183 if self.hinted_static {
184 self.linker_arg("-Bdynamic");
185 self.hinted_static = false;
189 fn push_cross_lang_lto_args(&mut self, plugin_path: Option<&OsStr>) {
190 if let Some(plugin_path) = plugin_path {
191 let mut arg = OsString::from("-plugin=");
192 arg.push(plugin_path);
193 self.linker_arg(&arg);
196 let opt_level = match self.sess.opts.optimize {
197 config::OptLevel::No => "O0",
198 config::OptLevel::Less => "O1",
199 config::OptLevel::Default => "O2",
200 config::OptLevel::Aggressive => "O3",
201 config::OptLevel::Size => "Os",
202 config::OptLevel::SizeMin => "Oz",
205 self.linker_arg(&format!("-plugin-opt={}", opt_level));
206 self.linker_arg(&format!("-plugin-opt=mcpu={}", llvm_util::target_cpu(self.sess)));
208 match self.sess.lto() {
210 config::Lto::ThinLocal => {
211 self.linker_arg("-plugin-opt=thin");
215 // default to regular LTO
221 impl<'a> Linker for GccLinker<'a> {
222 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}",lib)); }
223 fn link_staticlib(&mut self, lib: &str) {
224 self.hint_static(); self.cmd.arg(format!("-l{}",lib));
226 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
227 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
228 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
229 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
230 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
231 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
232 fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
233 fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
234 fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
235 fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
236 fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
237 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
239 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
241 self.cmd.arg(format!("-l{}",lib));
244 fn link_framework(&mut self, framework: &str) {
246 self.cmd.arg("-framework").arg(framework);
249 // Here we explicitly ask that the entire archive is included into the
250 // result artifact. For more details see #15460, but the gist is that
251 // the linker will strip away any unused objects in the archive if we
252 // don't otherwise explicitly reference them. This can occur for
253 // libraries which are just providing bindings, libraries with generic
255 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
257 let target = &self.sess.target.target;
258 if !target.options.is_like_osx {
259 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}",lib));
260 self.linker_arg("--no-whole-archive");
262 // -force_load is the macOS equivalent of --whole-archive, but it
263 // involves passing the full path to the library to link.
264 self.linker_arg("-force_load");
265 let lib = archive::find_library(lib, search_path, &self.sess);
266 self.linker_arg(&lib);
270 fn link_whole_rlib(&mut self, lib: &Path) {
272 if self.sess.target.target.options.is_like_osx {
273 self.linker_arg("-force_load");
274 self.linker_arg(&lib);
276 self.linker_arg("--whole-archive").cmd.arg(lib);
277 self.linker_arg("--no-whole-archive");
281 fn gc_sections(&mut self, keep_metadata: bool) {
282 // The dead_strip option to the linker specifies that functions and data
283 // unreachable by the entry point will be removed. This is quite useful
284 // with Rust's compilation model of compiling libraries at a time into
285 // one object file. For example, this brings hello world from 1.7MB to
288 // Note that this is done for both executables and dynamic libraries. We
289 // won't get much benefit from dylibs because LLVM will have already
290 // stripped away as much as it could. This has not been seen to impact
291 // link times negatively.
293 // -dead_strip can't be part of the pre_link_args because it's also used
294 // for partial linking when using multiple codegen units (-r). So we
296 if self.sess.target.target.options.is_like_osx {
297 self.linker_arg("-dead_strip");
298 } else if self.sess.target.target.options.is_like_solaris {
299 self.linker_arg("-zignore");
301 // If we're building a dylib, we don't use --gc-sections because LLVM
302 // has already done the best it can do, and we also don't want to
303 // eliminate the metadata. If we're building an executable, however,
304 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
306 } else if !keep_metadata {
307 self.linker_arg("--gc-sections");
311 fn optimize(&mut self) {
312 if !self.sess.target.target.options.linker_is_gnu { return }
314 // GNU-style linkers support optimization with -O. GNU ld doesn't
315 // need a numeric argument, but other linkers do.
316 if self.sess.opts.optimize == config::OptLevel::Default ||
317 self.sess.opts.optimize == config::OptLevel::Aggressive {
318 self.linker_arg("-O1");
322 fn pgo_gen(&mut self) {
323 if !self.sess.target.target.options.linker_is_gnu { return }
325 // If we're doing PGO generation stuff and on a GNU-like linker, use the
326 // "-u" flag to properly pull in the profiler runtime bits.
328 // This is because LLVM otherwise won't add the needed initialization
329 // for us on Linux (though the extra flag should be harmless if it
332 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
334 // Though it may be worth to try to revert those changes upstream, since
335 // the overhead of the initialization should be minor.
337 self.cmd.arg("__llvm_profile_runtime");
340 fn debuginfo(&mut self) {
341 match 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 match self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
347 Some(true) => { self.linker_arg("-S"); },
355 fn no_default_libraries(&mut self) {
357 self.cmd.arg("-nodefaultlibs");
361 fn build_dylib(&mut self, out_filename: &Path) {
362 // On mac we need to tell the linker to let this library be rpathed
363 if self.sess.target.target.options.is_like_osx {
364 self.cmd.arg("-dynamiclib");
365 self.linker_arg("-dylib");
367 // Note that the `osx_rpath_install_name` option here is a hack
368 // purely to support rustbuild right now, we should get a more
369 // principled solution at some point to force the compiler to pass
370 // the right `-Wl,-install_name` with an `@rpath` in it.
371 if self.sess.opts.cg.rpath ||
372 self.sess.opts.debugging_opts.osx_rpath_install_name {
373 self.linker_arg("-install_name");
374 let mut v = OsString::from("@rpath/");
375 v.push(out_filename.file_name().unwrap());
379 self.cmd.arg("-shared");
383 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
384 // If we're compiling a dylib, then we let symbol visibility in object
385 // files to take care of whether they're exported or not.
387 // If we're compiling a cdylib, however, we manually create a list of
388 // exported symbols to ensure we don't expose any more. The object files
389 // have far more public symbols than we actually want to export, so we
390 // hide them all here.
391 if crate_type == CrateType::Dylib ||
392 crate_type == CrateType::ProcMacro {
396 let mut arg = OsString::new();
397 let path = tmpdir.join("list");
399 debug!("EXPORTED SYMBOLS:");
401 if self.sess.target.target.options.is_like_osx {
402 // Write a plain, newline-separated list of symbols
403 let res = (|| -> io::Result<()> {
404 let mut f = BufWriter::new(File::create(&path)?);
405 for sym in self.info.exports[&crate_type].iter() {
407 writeln!(f, "_{}", sym)?;
411 if let Err(e) = res {
412 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
415 // Write an LD version script
416 let res = (|| -> io::Result<()> {
417 let mut f = BufWriter::new(File::create(&path)?);
418 writeln!(f, "{{\n global:")?;
419 for sym in self.info.exports[&crate_type].iter() {
421 writeln!(f, " {};", sym)?;
423 writeln!(f, "\n local:\n *;\n}};")?;
426 if let Err(e) = res {
427 self.sess.fatal(&format!("failed to write version script: {}", e));
431 if self.sess.target.target.options.is_like_osx {
435 arg.push("-exported_symbols_list,");
436 } else if self.sess.target.target.options.is_like_solaris {
445 arg.push("--version-script=");
452 fn subsystem(&mut self, subsystem: &str) {
453 self.linker_arg("--subsystem");
454 self.linker_arg(&subsystem);
457 fn finalize(&mut self) -> Command {
458 self.hint_dynamic(); // Reset to default before returning the composed command line.
459 let mut cmd = Command::new("");
460 ::std::mem::swap(&mut cmd, &mut self.cmd);
464 fn group_start(&mut self) {
465 if !self.sess.target.target.options.is_like_osx {
466 self.linker_arg("--start-group");
470 fn group_end(&mut self) {
471 if !self.sess.target.target.options.is_like_osx {
472 self.linker_arg("--end-group");
476 fn cross_lang_lto(&mut self) {
477 match self.sess.opts.debugging_opts.cross_lang_lto {
478 CrossLangLto::Disabled => {
481 CrossLangLto::LinkerPluginAuto => {
482 self.push_cross_lang_lto_args(None);
484 CrossLangLto::LinkerPlugin(ref path) => {
485 self.push_cross_lang_lto_args(Some(path.as_os_str()));
491 pub struct MsvcLinker<'a> {
497 impl<'a> Linker for MsvcLinker<'a> {
498 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
499 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
500 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
502 fn build_dylib(&mut self, out_filename: &Path) {
503 self.cmd.arg("/DLL");
504 let mut arg: OsString = "/IMPLIB:".into();
505 arg.push(out_filename.with_extension("dll.lib"));
509 fn build_static_executable(&mut self) {
513 fn gc_sections(&mut self, _keep_metadata: bool) {
514 // MSVC's ICF (Identical COMDAT Folding) link optimization is
515 // slow for Rust and thus we disable it by default when not in
516 // optimization build.
517 if self.sess.opts.optimize != config::OptLevel::No {
518 self.cmd.arg("/OPT:REF,ICF");
520 // It is necessary to specify NOICF here, because /OPT:REF
521 // implies ICF by default.
522 self.cmd.arg("/OPT:REF,NOICF");
526 fn link_dylib(&mut self, lib: &str) {
527 self.cmd.arg(&format!("{}.lib", lib));
530 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
531 // When producing a dll, the MSVC linker may not actually emit a
532 // `foo.lib` file if the dll doesn't actually export any symbols, so we
533 // check to see if the file is there and just omit linking to it if it's
535 let name = format!("{}.dll.lib", lib);
536 if fs::metadata(&path.join(&name)).is_ok() {
541 fn link_staticlib(&mut self, lib: &str) {
542 self.cmd.arg(&format!("{}.lib", lib));
545 fn position_independent_executable(&mut self) {
549 fn no_position_independent_executable(&mut self) {
553 fn full_relro(&mut self) {
557 fn partial_relro(&mut self) {
561 fn no_relro(&mut self) {
565 fn no_default_libraries(&mut self) {
566 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
567 // as there's been trouble in the past of linking the C++ standard
568 // library required by LLVM. This likely needs to happen one day, but
569 // in general Windows is also a more controlled environment than
570 // Unix, so it's not necessarily as critical that this be implemented.
572 // Note that there are also some licensing worries about statically
573 // linking some libraries which require a specific agreement, so it may
574 // not ever be possible for us to pass this flag.
577 fn include_path(&mut self, path: &Path) {
578 let mut arg = OsString::from("/LIBPATH:");
583 fn output_filename(&mut self, path: &Path) {
584 let mut arg = OsString::from("/OUT:");
589 fn framework_path(&mut self, _path: &Path) {
590 bug!("frameworks are not supported on windows")
592 fn link_framework(&mut self, _framework: &str) {
593 bug!("frameworks are not supported on windows")
596 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
598 self.link_staticlib(lib);
600 fn link_whole_rlib(&mut self, path: &Path) {
602 self.link_rlib(path);
604 fn optimize(&mut self) {
605 // Needs more investigation of `/OPT` arguments
608 fn pgo_gen(&mut self) {
609 // Nothing needed here.
612 fn debuginfo(&mut self) {
613 // This will cause the Microsoft linker to generate a PDB file
614 // from the CodeView line tables in the object files.
615 self.cmd.arg("/DEBUG");
617 // This will cause the Microsoft linker to embed .natvis info into the the PDB file
618 let sysroot = self.sess.sysroot();
619 let natvis_dir_path = sysroot.join("lib\\rustlib\\etc");
620 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
621 // LLVM 5.0.0's lld-link frontend doesn't yet recognize, and chokes
622 // on, the /NATVIS:... flags. LLVM 6 (or earlier) should at worst ignore
623 // them, eventually mooting this workaround, per this landed patch:
624 // https://github.com/llvm-mirror/lld/commit/27b9c4285364d8d76bb43839daa100
625 if let Some(ref linker_path) = self.sess.opts.cg.linker {
626 if let Some(linker_name) = Path::new(&linker_path).file_stem() {
627 if linker_name.to_str().unwrap().to_lowercase() == "lld-link" {
628 self.sess.warn("not embedding natvis: lld-link may not support the flag");
633 for entry in natvis_dir {
636 let path = entry.path();
637 if path.extension() == Some("natvis".as_ref()) {
638 let mut arg = OsString::from("/NATVIS:");
644 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
651 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
652 // export symbols from a dynamic library. When building a dynamic library,
653 // however, we're going to want some symbols exported, so this function
654 // generates a DEF file which lists all the symbols.
656 // The linker will read this `*.def` file and export all the symbols from
657 // the dynamic library. Note that this is not as simple as just exporting
658 // all the symbols in the current crate (as specified by `codegen.reachable`)
659 // but rather we also need to possibly export the symbols of upstream
660 // crates. Upstream rlibs may be linked statically to this dynamic library,
661 // in which case they may continue to transitively be used and hence need
662 // their symbols exported.
663 fn export_symbols(&mut self,
665 crate_type: CrateType) {
666 let path = tmpdir.join("lib.def");
667 let res = (|| -> io::Result<()> {
668 let mut f = BufWriter::new(File::create(&path)?);
670 // Start off with the standard module name header and then go
671 // straight to exports.
672 writeln!(f, "LIBRARY")?;
673 writeln!(f, "EXPORTS")?;
674 for symbol in self.info.exports[&crate_type].iter() {
675 debug!(" _{}", symbol);
676 writeln!(f, " {}", symbol)?;
680 if let Err(e) = res {
681 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
683 let mut arg = OsString::from("/DEF:");
688 fn subsystem(&mut self, subsystem: &str) {
689 // Note that previous passes of the compiler validated this subsystem,
690 // so we just blindly pass it to the linker.
691 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
693 // Windows has two subsystems we're interested in right now, the console
694 // and windows subsystems. These both implicitly have different entry
695 // points (starting symbols). The console entry point starts with
696 // `mainCRTStartup` and the windows entry point starts with
697 // `WinMainCRTStartup`. These entry points, defined in system libraries,
698 // will then later probe for either `main` or `WinMain`, respectively to
699 // start the application.
701 // In Rust we just always generate a `main` function so we want control
702 // to always start there, so we force the entry point on the windows
703 // subsystem to be `mainCRTStartup` to get everything booted up
706 // For more information see RFC #1665
707 if subsystem == "windows" {
708 self.cmd.arg("/ENTRY:mainCRTStartup");
712 fn finalize(&mut self) -> Command {
713 let mut cmd = Command::new("");
714 ::std::mem::swap(&mut cmd, &mut self.cmd);
718 // MSVC doesn't need group indicators
719 fn group_start(&mut self) {}
720 fn group_end(&mut self) {}
722 fn cross_lang_lto(&mut self) {
727 pub struct EmLinker<'a> {
733 impl<'a> Linker for EmLinker<'a> {
734 fn include_path(&mut self, path: &Path) {
735 self.cmd.arg("-L").arg(path);
738 fn link_staticlib(&mut self, lib: &str) {
739 self.cmd.arg("-l").arg(lib);
742 fn output_filename(&mut self, path: &Path) {
743 self.cmd.arg("-o").arg(path);
746 fn add_object(&mut self, path: &Path) {
750 fn link_dylib(&mut self, lib: &str) {
751 // Emscripten always links statically
752 self.link_staticlib(lib);
755 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
757 self.link_staticlib(lib);
760 fn link_whole_rlib(&mut self, lib: &Path) {
765 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
766 self.link_dylib(lib);
769 fn link_rlib(&mut self, lib: &Path) {
770 self.add_object(lib);
773 fn position_independent_executable(&mut self) {
777 fn no_position_independent_executable(&mut self) {
781 fn full_relro(&mut self) {
785 fn partial_relro(&mut self) {
789 fn no_relro(&mut self) {
793 fn args(&mut self, args: &[String]) {
797 fn framework_path(&mut self, _path: &Path) {
798 bug!("frameworks are not supported on Emscripten")
801 fn link_framework(&mut self, _framework: &str) {
802 bug!("frameworks are not supported on Emscripten")
805 fn gc_sections(&mut self, _keep_metadata: bool) {
809 fn optimize(&mut self) {
810 // Emscripten performs own optimizations
811 self.cmd.arg(match self.sess.opts.optimize {
812 OptLevel::No => "-O0",
813 OptLevel::Less => "-O1",
814 OptLevel::Default => "-O2",
815 OptLevel::Aggressive => "-O3",
816 OptLevel::Size => "-Os",
817 OptLevel::SizeMin => "-Oz"
819 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
820 self.cmd.args(&["--memory-init-file", "0"]);
823 fn pgo_gen(&mut self) {
824 // noop, but maybe we need something like the gnu linker?
827 fn debuginfo(&mut self) {
828 // Preserve names or generate source maps depending on debug info
829 self.cmd.arg(match self.sess.opts.debuginfo {
830 DebugInfo::None => "-g0",
831 DebugInfo::Limited => "-g3",
832 DebugInfo::Full => "-g4"
836 fn no_default_libraries(&mut self) {
837 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
840 fn build_dylib(&mut self, _out_filename: &Path) {
841 bug!("building dynamic library is unsupported on Emscripten")
844 fn build_static_executable(&mut self) {
848 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
849 let symbols = &self.info.exports[&crate_type];
851 debug!("EXPORTED SYMBOLS:");
855 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
856 let mut encoded = String::new();
859 let mut encoder = json::Encoder::new(&mut encoded);
860 let res = encoder.emit_seq(symbols.len(), |encoder| {
861 for (i, sym) in symbols.iter().enumerate() {
862 encoder.emit_seq_elt(i, |encoder| {
863 encoder.emit_str(&("_".to_string() + sym))
868 if let Err(e) = res {
869 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
872 debug!("{}", encoded);
878 fn subsystem(&mut self, _subsystem: &str) {
882 fn finalize(&mut self) -> Command {
883 let mut cmd = Command::new("");
884 ::std::mem::swap(&mut cmd, &mut self.cmd);
888 // Appears not necessary on Emscripten
889 fn group_start(&mut self) {}
890 fn group_end(&mut self) {}
892 fn cross_lang_lto(&mut self) {
897 fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
898 let mut symbols = Vec::new();
900 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
901 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
902 if level.is_below_threshold(export_threshold) {
903 symbols.push(symbol.symbol_name(tcx).to_string());
907 let formats = tcx.sess.dependency_formats.borrow();
908 let deps = formats[&crate_type].iter();
910 for (index, dep_format) in deps.enumerate() {
911 let cnum = CrateNum::new(index + 1);
912 // For each dependency that we are linking to statically ...
913 if *dep_format == Linkage::Static {
914 // ... we add its symbol list to our export list.
915 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
916 if level.is_below_threshold(export_threshold) {
917 symbols.push(symbol.symbol_name(tcx).to_string());
926 pub struct WasmLd<'a> {
931 impl<'a> Linker for WasmLd<'a> {
932 fn link_dylib(&mut self, lib: &str) {
933 self.cmd.arg("-l").arg(lib);
936 fn link_staticlib(&mut self, lib: &str) {
937 self.cmd.arg("-l").arg(lib);
940 fn link_rlib(&mut self, lib: &Path) {
944 fn include_path(&mut self, path: &Path) {
945 self.cmd.arg("-L").arg(path);
948 fn framework_path(&mut self, _path: &Path) {
949 panic!("frameworks not supported")
952 fn output_filename(&mut self, path: &Path) {
953 self.cmd.arg("-o").arg(path);
956 fn add_object(&mut self, path: &Path) {
960 fn position_independent_executable(&mut self) {
963 fn full_relro(&mut self) {
966 fn partial_relro(&mut self) {
969 fn no_relro(&mut self) {
972 fn build_static_executable(&mut self) {
975 fn args(&mut self, args: &[String]) {
979 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
980 self.cmd.arg("-l").arg(lib);
983 fn link_framework(&mut self, _framework: &str) {
984 panic!("frameworks not supported")
987 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
988 self.cmd.arg("-l").arg(lib);
991 fn link_whole_rlib(&mut self, lib: &Path) {
995 fn gc_sections(&mut self, _keep_metadata: bool) {
996 self.cmd.arg("--gc-sections");
999 fn optimize(&mut self) {
1000 self.cmd.arg(match self.sess.opts.optimize {
1001 OptLevel::No => "-O0",
1002 OptLevel::Less => "-O1",
1003 OptLevel::Default => "-O2",
1004 OptLevel::Aggressive => "-O3",
1005 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1007 OptLevel::Size => "-O2",
1008 OptLevel::SizeMin => "-O2"
1012 fn pgo_gen(&mut self) {
1015 fn debuginfo(&mut self) {
1018 fn no_default_libraries(&mut self) {
1021 fn build_dylib(&mut self, _out_filename: &Path) {
1024 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
1027 fn subsystem(&mut self, _subsystem: &str) {
1030 fn no_position_independent_executable(&mut self) {
1033 fn finalize(&mut self) -> Command {
1034 // There have been reports in the wild (rustwasm/wasm-bindgen#119) of
1035 // using threads causing weird hangs and bugs. Disable it entirely as
1036 // this isn't yet the bottleneck of compilation at all anyway.
1037 self.cmd.arg("--no-threads");
1039 // By default LLD only gives us one page of stack (64k) which is a
1040 // little small. Default to a larger stack closer to other PC platforms
1041 // (1MB) and users can always inject their own link-args to override this.
1042 self.cmd.arg("-z").arg("stack-size=1048576");
1044 // By default LLD's memory layout is:
1046 // 1. First, a blank page
1047 // 2. Next, all static data
1048 // 3. Finally, the main stack (which grows down)
1050 // This has the unfortunate consequence that on stack overflows you
1051 // corrupt static data and can cause some exceedingly weird bugs. To
1052 // help detect this a little sooner we instead request that the stack is
1053 // placed before static data.
1055 // This means that we'll generate slightly larger binaries as references
1056 // to static data will take more bytes in the ULEB128 encoding, but
1057 // stack overflow will be guaranteed to trap as it underflows instead of
1058 // corrupting static data.
1059 self.cmd.arg("--stack-first");
1061 // FIXME we probably shouldn't pass this but instead pass an explicit
1062 // whitelist of symbols we'll allow to be undefined. Unfortunately
1063 // though we can't handle symbols like `log10` that LLVM injects at a
1064 // super late date without actually parsing object files. For now let's
1065 // stick to this and hopefully fix it before stabilization happens.
1066 self.cmd.arg("--allow-undefined");
1068 // For now we just never have an entry symbol
1069 self.cmd.arg("--no-entry");
1071 // Make the default table accessible
1072 self.cmd.arg("--export-table");
1074 // Rust code should never have warnings, and warnings are often
1075 // indicative of bugs, let's prevent them.
1076 self.cmd.arg("--fatal-warnings");
1078 let mut cmd = Command::new("");
1079 ::std::mem::swap(&mut cmd, &mut self.cmd);
1083 // Not needed for now with LLD
1084 fn group_start(&mut self) {}
1085 fn group_end(&mut self) {}
1087 fn cross_lang_lto(&mut self) {
1088 // Do nothing for now