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 super::symbol_export;
12 use super::command::Command;
15 use rustc_data_structures::fx::FxHashMap;
16 use std::ffi::{OsStr, OsString};
17 use std::fs::{self, File};
18 use std::io::prelude::*;
19 use std::io::{self, BufWriter};
20 use std::path::{Path, PathBuf};
22 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
23 use rustc::middle::dependency_format::Linkage;
24 use rustc::session::Session;
25 use rustc::session::config::{self, CrateType, OptLevel, DebugInfo,
27 use rustc::ty::TyCtxt;
28 use rustc_target::spec::{LinkerFlavor, LldFlavor};
29 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))
52 ) -> Box<dyn Linker+'a> {
54 LinkerFlavor::Lld(LldFlavor::Link) |
55 LinkerFlavor::Msvc => {
69 LinkerFlavor::Gcc => {
80 LinkerFlavor::Lld(LldFlavor::Ld) |
81 LinkerFlavor::Lld(LldFlavor::Ld64) |
93 LinkerFlavor::Lld(LldFlavor::Wasm) => {
104 /// Linker abstraction used by back::link to build up the command to invoke a
107 /// This trait is the total list of requirements needed by `back::link` and
108 /// represents the meaning of each option being passed down. This trait is then
109 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
110 /// MSVC linker (e.g., `link.exe`) is being used.
112 fn link_dylib(&mut self, lib: &str);
113 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
114 fn link_framework(&mut self, framework: &str);
115 fn link_staticlib(&mut self, lib: &str);
116 fn link_rlib(&mut self, lib: &Path);
117 fn link_whole_rlib(&mut self, lib: &Path);
118 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
119 fn include_path(&mut self, path: &Path);
120 fn framework_path(&mut self, path: &Path);
121 fn output_filename(&mut self, path: &Path);
122 fn add_object(&mut self, path: &Path);
123 fn gc_sections(&mut self, keep_metadata: bool);
124 fn position_independent_executable(&mut self);
125 fn no_position_independent_executable(&mut self);
126 fn full_relro(&mut self);
127 fn partial_relro(&mut self);
128 fn no_relro(&mut self);
129 fn optimize(&mut self);
130 fn pgo_gen(&mut self);
131 fn debuginfo(&mut self);
132 fn no_default_libraries(&mut self);
133 fn build_dylib(&mut self, out_filename: &Path);
134 fn build_static_executable(&mut self);
135 fn args(&mut self, args: &[String]);
136 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
137 fn subsystem(&mut self, subsystem: &str);
138 fn group_start(&mut self);
139 fn group_end(&mut self);
140 fn cross_lang_lto(&mut self);
141 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
142 fn finalize(&mut self) -> Command;
145 pub struct GccLinker<'a> {
148 info: &'a LinkerInfo,
149 hinted_static: bool, // Keeps track of the current hinting mode.
155 impl<'a> GccLinker<'a> {
156 /// Argument that must be passed *directly* to the linker
158 /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
159 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
160 where S: AsRef<OsStr>
163 let mut os = OsString::from("-Wl,");
164 os.push(arg.as_ref());
172 fn takes_hints(&self) -> bool {
173 !self.sess.target.target.options.is_like_osx
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_cross_lang_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: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}", lib)); }
220 fn link_staticlib(&mut self, lib: &str) {
221 self.hint_static(); self.cmd.arg(format!("-l{}", lib));
223 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
224 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
225 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
226 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
227 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
228 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
229 fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
230 fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
231 fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
232 fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
233 fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
234 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
236 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
238 self.cmd.arg(format!("-l{}", lib));
241 fn link_framework(&mut self, framework: &str) {
243 self.cmd.arg("-framework").arg(framework);
246 // Here we explicitly ask that the entire archive is included into the
247 // result artifact. For more details see #15460, but the gist is that
248 // the linker will strip away any unused objects in the archive if we
249 // don't otherwise explicitly reference them. This can occur for
250 // libraries which are just providing bindings, libraries with generic
252 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
254 let target = &self.sess.target.target;
255 if !target.options.is_like_osx {
256 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
257 self.linker_arg("--no-whole-archive");
259 // -force_load is the macOS equivalent of --whole-archive, but it
260 // involves passing the full path to the library to link.
261 self.linker_arg("-force_load");
262 let lib = archive::find_library(lib, search_path, &self.sess);
263 self.linker_arg(&lib);
267 fn link_whole_rlib(&mut self, lib: &Path) {
269 if self.sess.target.target.options.is_like_osx {
270 self.linker_arg("-force_load");
271 self.linker_arg(&lib);
273 self.linker_arg("--whole-archive").cmd.arg(lib);
274 self.linker_arg("--no-whole-archive");
278 fn gc_sections(&mut self, keep_metadata: bool) {
279 // The dead_strip option to the linker specifies that functions and data
280 // unreachable by the entry point will be removed. This is quite useful
281 // with Rust's compilation model of compiling libraries at a time into
282 // one object file. For example, this brings hello world from 1.7MB to
285 // Note that this is done for both executables and dynamic libraries. We
286 // won't get much benefit from dylibs because LLVM will have already
287 // stripped away as much as it could. This has not been seen to impact
288 // link times negatively.
290 // -dead_strip can't be part of the pre_link_args because it's also used
291 // for partial linking when using multiple codegen units (-r). So we
293 if self.sess.target.target.options.is_like_osx {
294 self.linker_arg("-dead_strip");
295 } else if self.sess.target.target.options.is_like_solaris {
296 self.linker_arg("-zignore");
298 // If we're building a dylib, we don't use --gc-sections because LLVM
299 // has already done the best it can do, and we also don't want to
300 // eliminate the metadata. If we're building an executable, however,
301 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
303 } else if !keep_metadata {
304 self.linker_arg("--gc-sections");
308 fn optimize(&mut self) {
309 if !self.sess.target.target.options.linker_is_gnu { return }
311 // GNU-style linkers support optimization with -O. GNU ld doesn't
312 // need a numeric argument, but other linkers do.
313 if self.sess.opts.optimize == config::OptLevel::Default ||
314 self.sess.opts.optimize == config::OptLevel::Aggressive {
315 self.linker_arg("-O1");
319 fn pgo_gen(&mut self) {
320 if !self.sess.target.target.options.linker_is_gnu { return }
322 // If we're doing PGO generation stuff and on a GNU-like linker, use the
323 // "-u" flag to properly pull in the profiler runtime bits.
325 // This is because LLVM otherwise won't add the needed initialization
326 // for us on Linux (though the extra flag should be harmless if it
329 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
331 // Though it may be worth to try to revert those changes upstream, since
332 // the overhead of the initialization should be minor.
334 self.cmd.arg("__llvm_profile_runtime");
337 fn debuginfo(&mut self) {
338 if let DebugInfo::None = self.sess.opts.debuginfo {
339 // If we are building without debuginfo enabled and we were called with
340 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
341 // found when linking to get rid of symbols from libstd.
342 if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
343 self.linker_arg("-S");
348 fn no_default_libraries(&mut self) {
350 self.cmd.arg("-nodefaultlibs");
354 fn build_dylib(&mut self, out_filename: &Path) {
355 // On mac we need to tell the linker to let this library be rpathed
356 if self.sess.target.target.options.is_like_osx {
357 self.cmd.arg("-dynamiclib");
358 self.linker_arg("-dylib");
360 // Note that the `osx_rpath_install_name` option here is a hack
361 // purely to support rustbuild right now, we should get a more
362 // principled solution at some point to force the compiler to pass
363 // the right `-Wl,-install_name` with an `@rpath` in it.
364 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
365 self.linker_arg("-install_name");
366 let mut v = OsString::from("@rpath/");
367 v.push(out_filename.file_name().unwrap());
371 self.cmd.arg("-shared");
375 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
376 // If we're compiling a dylib, then we let symbol visibility in object
377 // files to take care of whether they're exported or not.
379 // If we're compiling a cdylib, however, we manually create a list of
380 // exported symbols to ensure we don't expose any more. The object files
381 // have far more public symbols than we actually want to export, so we
382 // hide them all here.
383 if crate_type == CrateType::Dylib ||
384 crate_type == CrateType::ProcMacro {
388 let mut arg = OsString::new();
389 let path = tmpdir.join("list");
391 debug!("EXPORTED SYMBOLS:");
393 if self.sess.target.target.options.is_like_osx {
394 // Write a plain, newline-separated list of symbols
395 let res = (|| -> io::Result<()> {
396 let mut f = BufWriter::new(File::create(&path)?);
397 for sym in self.info.exports[&crate_type].iter() {
399 writeln!(f, "_{}", sym)?;
403 if let Err(e) = res {
404 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
407 // Write an LD version script
408 let res = (|| -> io::Result<()> {
409 let mut f = BufWriter::new(File::create(&path)?);
410 writeln!(f, "{{\n global:")?;
411 for sym in self.info.exports[&crate_type].iter() {
413 writeln!(f, " {};", sym)?;
415 writeln!(f, "\n local:\n *;\n}};")?;
418 if let Err(e) = res {
419 self.sess.fatal(&format!("failed to write version script: {}", e));
423 if self.sess.target.target.options.is_like_osx {
427 arg.push("-exported_symbols_list,");
428 } else if self.sess.target.target.options.is_like_solaris {
437 arg.push("--version-script=");
444 fn subsystem(&mut self, subsystem: &str) {
445 self.linker_arg("--subsystem");
446 self.linker_arg(&subsystem);
449 fn finalize(&mut self) -> Command {
450 self.hint_dynamic(); // Reset to default before returning the composed command line.
452 ::std::mem::replace(&mut self.cmd, Command::new(""))
455 fn group_start(&mut self) {
456 if !self.sess.target.target.options.is_like_osx {
457 self.linker_arg("--start-group");
461 fn group_end(&mut self) {
462 if !self.sess.target.target.options.is_like_osx {
463 self.linker_arg("--end-group");
467 fn cross_lang_lto(&mut self) {
468 match self.sess.opts.debugging_opts.cross_lang_lto {
469 CrossLangLto::Disabled => {
472 CrossLangLto::LinkerPluginAuto => {
473 self.push_cross_lang_lto_args(None);
475 CrossLangLto::LinkerPlugin(ref path) => {
476 self.push_cross_lang_lto_args(Some(path.as_os_str()));
482 pub struct MsvcLinker<'a> {
488 impl<'a> Linker for MsvcLinker<'a> {
489 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
490 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
491 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
493 fn build_dylib(&mut self, out_filename: &Path) {
494 self.cmd.arg("/DLL");
495 let mut arg: OsString = "/IMPLIB:".into();
496 arg.push(out_filename.with_extension("dll.lib"));
500 fn build_static_executable(&mut self) {
504 fn gc_sections(&mut self, _keep_metadata: bool) {
505 // MSVC's ICF (Identical COMDAT Folding) link optimization is
506 // slow for Rust and thus we disable it by default when not in
507 // optimization build.
508 if self.sess.opts.optimize != config::OptLevel::No {
509 self.cmd.arg("/OPT:REF,ICF");
511 // It is necessary to specify NOICF here, because /OPT:REF
512 // implies ICF by default.
513 self.cmd.arg("/OPT:REF,NOICF");
517 fn link_dylib(&mut self, lib: &str) {
518 self.cmd.arg(&format!("{}.lib", lib));
521 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
522 // When producing a dll, the MSVC linker may not actually emit a
523 // `foo.lib` file if the dll doesn't actually export any symbols, so we
524 // check to see if the file is there and just omit linking to it if it's
526 let name = format!("{}.dll.lib", lib);
527 if fs::metadata(&path.join(&name)).is_ok() {
532 fn link_staticlib(&mut self, lib: &str) {
533 self.cmd.arg(&format!("{}.lib", lib));
536 fn position_independent_executable(&mut self) {
540 fn no_position_independent_executable(&mut self) {
544 fn full_relro(&mut self) {
548 fn partial_relro(&mut self) {
552 fn no_relro(&mut self) {
556 fn no_default_libraries(&mut self) {
557 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
558 // as there's been trouble in the past of linking the C++ standard
559 // library required by LLVM. This likely needs to happen one day, but
560 // in general Windows is also a more controlled environment than
561 // Unix, so it's not necessarily as critical that this be implemented.
563 // Note that there are also some licensing worries about statically
564 // linking some libraries which require a specific agreement, so it may
565 // not ever be possible for us to pass this flag.
568 fn include_path(&mut self, path: &Path) {
569 let mut arg = OsString::from("/LIBPATH:");
574 fn output_filename(&mut self, path: &Path) {
575 let mut arg = OsString::from("/OUT:");
580 fn framework_path(&mut self, _path: &Path) {
581 bug!("frameworks are not supported on windows")
583 fn link_framework(&mut self, _framework: &str) {
584 bug!("frameworks are not supported on windows")
587 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
589 self.link_staticlib(lib);
591 fn link_whole_rlib(&mut self, path: &Path) {
593 self.link_rlib(path);
595 fn optimize(&mut self) {
596 // Needs more investigation of `/OPT` arguments
599 fn pgo_gen(&mut self) {
600 // Nothing needed here.
603 fn debuginfo(&mut self) {
604 // This will cause the Microsoft linker to generate a PDB file
605 // from the CodeView line tables in the object files.
606 self.cmd.arg("/DEBUG");
608 // This will cause the Microsoft linker to embed .natvis info into the PDB file
609 let sysroot = self.sess.sysroot();
610 let natvis_dir_path = sysroot.join("lib\\rustlib\\etc");
611 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
612 // LLVM 5.0.0's lld-link frontend doesn't yet recognize, and chokes
613 // on, the /NATVIS:... flags. LLVM 6 (or earlier) should at worst ignore
614 // them, eventually mooting this workaround, per this landed patch:
615 // https://github.com/llvm-mirror/lld/commit/27b9c4285364d8d76bb43839daa100
616 if let Some(ref linker_path) = self.sess.opts.cg.linker {
617 if let Some(linker_name) = Path::new(&linker_path).file_stem() {
618 if linker_name.to_str().unwrap().to_lowercase() == "lld-link" {
619 self.sess.warn("not embedding natvis: lld-link may not support the flag");
624 for entry in natvis_dir {
627 let path = entry.path();
628 if path.extension() == Some("natvis".as_ref()) {
629 let mut arg = OsString::from("/NATVIS:");
635 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
642 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
643 // export symbols from a dynamic library. When building a dynamic library,
644 // however, we're going to want some symbols exported, so this function
645 // generates a DEF file which lists all the symbols.
647 // The linker will read this `*.def` file and export all the symbols from
648 // the dynamic library. Note that this is not as simple as just exporting
649 // all the symbols in the current crate (as specified by `codegen.reachable`)
650 // but rather we also need to possibly export the symbols of upstream
651 // crates. Upstream rlibs may be linked statically to this dynamic library,
652 // in which case they may continue to transitively be used and hence need
653 // their symbols exported.
654 fn export_symbols(&mut self,
656 crate_type: CrateType) {
657 let path = tmpdir.join("lib.def");
658 let res = (|| -> io::Result<()> {
659 let mut f = BufWriter::new(File::create(&path)?);
661 // Start off with the standard module name header and then go
662 // straight to exports.
663 writeln!(f, "LIBRARY")?;
664 writeln!(f, "EXPORTS")?;
665 for symbol in self.info.exports[&crate_type].iter() {
666 debug!(" _{}", symbol);
667 writeln!(f, " {}", symbol)?;
671 if let Err(e) = res {
672 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
674 let mut arg = OsString::from("/DEF:");
679 fn subsystem(&mut self, subsystem: &str) {
680 // Note that previous passes of the compiler validated this subsystem,
681 // so we just blindly pass it to the linker.
682 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
684 // Windows has two subsystems we're interested in right now, the console
685 // and windows subsystems. These both implicitly have different entry
686 // points (starting symbols). The console entry point starts with
687 // `mainCRTStartup` and the windows entry point starts with
688 // `WinMainCRTStartup`. These entry points, defined in system libraries,
689 // will then later probe for either `main` or `WinMain`, respectively to
690 // start the application.
692 // In Rust we just always generate a `main` function so we want control
693 // to always start there, so we force the entry point on the windows
694 // subsystem to be `mainCRTStartup` to get everything booted up
697 // For more information see RFC #1665
698 if subsystem == "windows" {
699 self.cmd.arg("/ENTRY:mainCRTStartup");
703 fn finalize(&mut self) -> Command {
704 ::std::mem::replace(&mut self.cmd, Command::new(""))
707 // MSVC doesn't need group indicators
708 fn group_start(&mut self) {}
709 fn group_end(&mut self) {}
711 fn cross_lang_lto(&mut self) {
716 pub struct EmLinker<'a> {
722 impl<'a> Linker for EmLinker<'a> {
723 fn include_path(&mut self, path: &Path) {
724 self.cmd.arg("-L").arg(path);
727 fn link_staticlib(&mut self, lib: &str) {
728 self.cmd.arg("-l").arg(lib);
731 fn output_filename(&mut self, path: &Path) {
732 self.cmd.arg("-o").arg(path);
735 fn add_object(&mut self, path: &Path) {
739 fn link_dylib(&mut self, lib: &str) {
740 // Emscripten always links statically
741 self.link_staticlib(lib);
744 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
746 self.link_staticlib(lib);
749 fn link_whole_rlib(&mut self, lib: &Path) {
754 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
755 self.link_dylib(lib);
758 fn link_rlib(&mut self, lib: &Path) {
759 self.add_object(lib);
762 fn position_independent_executable(&mut self) {
766 fn no_position_independent_executable(&mut self) {
770 fn full_relro(&mut self) {
774 fn partial_relro(&mut self) {
778 fn no_relro(&mut self) {
782 fn args(&mut self, args: &[String]) {
786 fn framework_path(&mut self, _path: &Path) {
787 bug!("frameworks are not supported on Emscripten")
790 fn link_framework(&mut self, _framework: &str) {
791 bug!("frameworks are not supported on Emscripten")
794 fn gc_sections(&mut self, _keep_metadata: bool) {
798 fn optimize(&mut self) {
799 // Emscripten performs own optimizations
800 self.cmd.arg(match self.sess.opts.optimize {
801 OptLevel::No => "-O0",
802 OptLevel::Less => "-O1",
803 OptLevel::Default => "-O2",
804 OptLevel::Aggressive => "-O3",
805 OptLevel::Size => "-Os",
806 OptLevel::SizeMin => "-Oz"
808 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
809 self.cmd.args(&["--memory-init-file", "0"]);
812 fn pgo_gen(&mut self) {
813 // noop, but maybe we need something like the gnu linker?
816 fn debuginfo(&mut self) {
817 // Preserve names or generate source maps depending on debug info
818 self.cmd.arg(match self.sess.opts.debuginfo {
819 DebugInfo::None => "-g0",
820 DebugInfo::Limited => "-g3",
821 DebugInfo::Full => "-g4"
825 fn no_default_libraries(&mut self) {
826 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
829 fn build_dylib(&mut self, _out_filename: &Path) {
830 bug!("building dynamic library is unsupported on Emscripten")
833 fn build_static_executable(&mut self) {
837 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
838 let symbols = &self.info.exports[&crate_type];
840 debug!("EXPORTED SYMBOLS:");
844 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
845 let mut encoded = String::new();
848 let mut encoder = json::Encoder::new(&mut encoded);
849 let res = encoder.emit_seq(symbols.len(), |encoder| {
850 for (i, sym) in symbols.iter().enumerate() {
851 encoder.emit_seq_elt(i, |encoder| {
852 encoder.emit_str(&("_".to_owned() + sym))
857 if let Err(e) = res {
858 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
861 debug!("{}", encoded);
867 fn subsystem(&mut self, _subsystem: &str) {
871 fn finalize(&mut self) -> Command {
872 ::std::mem::replace(&mut self.cmd, Command::new(""))
875 // Appears not necessary on Emscripten
876 fn group_start(&mut self) {}
877 fn group_end(&mut self) {}
879 fn cross_lang_lto(&mut self) {
884 pub struct WasmLd<'a> {
887 info: &'a LinkerInfo,
890 impl<'a> Linker for WasmLd<'a> {
891 fn link_dylib(&mut self, lib: &str) {
892 self.cmd.arg("-l").arg(lib);
895 fn link_staticlib(&mut self, lib: &str) {
896 self.cmd.arg("-l").arg(lib);
899 fn link_rlib(&mut self, lib: &Path) {
903 fn include_path(&mut self, path: &Path) {
904 self.cmd.arg("-L").arg(path);
907 fn framework_path(&mut self, _path: &Path) {
908 panic!("frameworks not supported")
911 fn output_filename(&mut self, path: &Path) {
912 self.cmd.arg("-o").arg(path);
915 fn add_object(&mut self, path: &Path) {
919 fn position_independent_executable(&mut self) {
922 fn full_relro(&mut self) {
925 fn partial_relro(&mut self) {
928 fn no_relro(&mut self) {
931 fn build_static_executable(&mut self) {
934 fn args(&mut self, args: &[String]) {
938 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
939 self.cmd.arg("-l").arg(lib);
942 fn link_framework(&mut self, _framework: &str) {
943 panic!("frameworks not supported")
946 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
947 self.cmd.arg("-l").arg(lib);
950 fn link_whole_rlib(&mut self, lib: &Path) {
954 fn gc_sections(&mut self, _keep_metadata: bool) {
955 self.cmd.arg("--gc-sections");
958 fn optimize(&mut self) {
959 self.cmd.arg(match self.sess.opts.optimize {
960 OptLevel::No => "-O0",
961 OptLevel::Less => "-O1",
962 OptLevel::Default => "-O2",
963 OptLevel::Aggressive => "-O3",
964 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
966 OptLevel::Size => "-O2",
967 OptLevel::SizeMin => "-O2"
971 fn pgo_gen(&mut self) {
974 fn debuginfo(&mut self) {
977 fn no_default_libraries(&mut self) {
980 fn build_dylib(&mut self, _out_filename: &Path) {
983 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
984 for sym in self.info.exports[&crate_type].iter() {
985 self.cmd.arg("--export").arg(&sym);
989 fn subsystem(&mut self, _subsystem: &str) {
992 fn no_position_independent_executable(&mut self) {
995 fn finalize(&mut self) -> Command {
996 // There have been reports in the wild (rustwasm/wasm-bindgen#119) of
997 // using threads causing weird hangs and bugs. Disable it entirely as
998 // this isn't yet the bottleneck of compilation at all anyway.
999 self.cmd.arg("--no-threads");
1001 // By default LLD only gives us one page of stack (64k) which is a
1002 // little small. Default to a larger stack closer to other PC platforms
1003 // (1MB) and users can always inject their own link-args to override this.
1004 self.cmd.arg("-z").arg("stack-size=1048576");
1006 // By default LLD's memory layout is:
1008 // 1. First, a blank page
1009 // 2. Next, all static data
1010 // 3. Finally, the main stack (which grows down)
1012 // This has the unfortunate consequence that on stack overflows you
1013 // corrupt static data and can cause some exceedingly weird bugs. To
1014 // help detect this a little sooner we instead request that the stack is
1015 // placed before static data.
1017 // This means that we'll generate slightly larger binaries as references
1018 // to static data will take more bytes in the ULEB128 encoding, but
1019 // stack overflow will be guaranteed to trap as it underflows instead of
1020 // corrupting static data.
1021 self.cmd.arg("--stack-first");
1023 // FIXME we probably shouldn't pass this but instead pass an explicit
1024 // whitelist of symbols we'll allow to be undefined. Unfortunately
1025 // though we can't handle symbols like `log10` that LLVM injects at a
1026 // super late date without actually parsing object files. For now let's
1027 // stick to this and hopefully fix it before stabilization happens.
1028 self.cmd.arg("--allow-undefined");
1030 // For now we just never have an entry symbol
1031 self.cmd.arg("--no-entry");
1033 // Make the default table accessible
1034 self.cmd.arg("--export-table");
1036 // Rust code should never have warnings, and warnings are often
1037 // indicative of bugs, let's prevent them.
1038 self.cmd.arg("--fatal-warnings");
1040 // The symbol visibility story is a bit in flux right now with LLD.
1041 // It's... not entirely clear to me what's going on, but this looks to
1042 // make everything work when `export_symbols` isn't otherwise called for
1043 // things like executables.
1044 self.cmd.arg("--export-dynamic");
1046 // LLD only implements C++-like demangling, which doesn't match our own
1047 // mangling scheme. Tell LLD to not demangle anything and leave it up to
1048 // us to demangle these symbols later.
1049 self.cmd.arg("--no-demangle");
1051 ::std::mem::replace(&mut self.cmd, Command::new(""))
1054 // Not needed for now with LLD
1055 fn group_start(&mut self) {}
1056 fn group_end(&mut self) {}
1058 fn cross_lang_lto(&mut self) {
1059 // Do nothing for now
1063 fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
1064 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1065 return exports.clone()
1068 let mut symbols = Vec::new();
1070 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1071 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1072 if level.is_below_threshold(export_threshold) {
1073 symbols.push(symbol.symbol_name(tcx).to_string());
1077 let formats = tcx.sess.dependency_formats.borrow();
1078 let deps = formats[&crate_type].iter();
1080 for (index, dep_format) in deps.enumerate() {
1081 let cnum = CrateNum::new(index + 1);
1082 // For each dependency that we are linking to statically ...
1083 if *dep_format == Linkage::Static {
1084 // ... we add its symbol list to our export list.
1085 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1086 if level.is_below_threshold(export_threshold) {
1087 symbols.push(symbol.symbol_name(tcx).to_string());