2 use super::command::Command;
3 use super::symbol_export;
5 use rustc_data_structures::fx::FxHashMap;
6 use std::ffi::{OsStr, OsString};
7 use std::fs::{self, File};
8 use std::io::prelude::*;
9 use std::io::{self, BufWriter};
10 use std::path::{Path, PathBuf};
12 use rustc::middle::dependency_format::Linkage;
13 use rustc::session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
14 use rustc::session::Session;
15 use rustc::ty::TyCtxt;
16 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
17 use rustc_serialize::{json, Encoder};
18 use rustc_span::symbol::Symbol;
19 use rustc_target::spec::{LinkerFlavor, LldFlavor};
21 /// For all the linkers we support, and information they might
22 /// need out of the shared crate context before we get rid of it.
23 pub struct LinkerInfo {
24 exports: FxHashMap<CrateType, Vec<String>>,
28 pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
35 .map(|&c| (c, exported_symbols(tcx, c)))
46 ) -> Box<dyn Linker + 'a> {
48 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
49 Box::new(MsvcLinker { cmd, sess, info: self }) as Box<dyn Linker>
51 LinkerFlavor::Em => Box::new(EmLinker { cmd, sess, info: self }) as Box<dyn Linker>,
52 LinkerFlavor::Gcc => Box::new(GccLinker {
59 }) as Box<dyn Linker>,
61 LinkerFlavor::Lld(LldFlavor::Ld)
62 | LinkerFlavor::Lld(LldFlavor::Ld64)
63 | LinkerFlavor::Ld => Box::new(GccLinker {
70 }) as Box<dyn Linker>,
72 LinkerFlavor::Lld(LldFlavor::Wasm) => {
73 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
76 LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
81 /// Linker abstraction used by `back::link` to build up the command to invoke a
84 /// This trait is the total list of requirements needed by `back::link` and
85 /// represents the meaning of each option being passed down. This trait is then
86 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
87 /// MSVC linker (e.g., `link.exe`) is being used.
89 fn link_dylib(&mut self, lib: Symbol);
90 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
91 fn link_framework(&mut self, framework: Symbol);
92 fn link_staticlib(&mut self, lib: Symbol);
93 fn link_rlib(&mut self, lib: &Path);
94 fn link_whole_rlib(&mut self, lib: &Path);
95 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]);
96 fn include_path(&mut self, path: &Path);
97 fn framework_path(&mut self, path: &Path);
98 fn output_filename(&mut self, path: &Path);
99 fn add_object(&mut self, path: &Path);
100 fn gc_sections(&mut self, keep_metadata: bool);
101 fn position_independent_executable(&mut self);
102 fn no_position_independent_executable(&mut self);
103 fn full_relro(&mut self);
104 fn partial_relro(&mut self);
105 fn no_relro(&mut self);
106 fn optimize(&mut self);
107 fn pgo_gen(&mut self);
108 fn debuginfo(&mut self);
109 fn no_default_libraries(&mut self);
110 fn build_dylib(&mut self, out_filename: &Path);
111 fn build_static_executable(&mut self);
112 fn args(&mut self, args: &[String]);
113 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
114 fn subsystem(&mut self, subsystem: &str);
115 fn group_start(&mut self);
116 fn group_end(&mut self);
117 fn linker_plugin_lto(&mut self);
118 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
119 fn finalize(&mut self) -> Command;
122 pub struct GccLinker<'a> {
125 info: &'a LinkerInfo,
126 hinted_static: bool, // Keeps track of the current hinting mode.
132 impl<'a> GccLinker<'a> {
133 /// Argument that must be passed *directly* to the linker
135 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
136 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
141 let mut os = OsString::from("-Wl,");
142 os.push(arg.as_ref());
150 fn takes_hints(&self) -> bool {
151 // Really this function only returns true if the underlying linker
152 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
153 // don't really have a foolproof way to detect that, so rule out some
154 // platforms where currently this is guaranteed to *not* be the case:
156 // * On OSX they have their own linker, not binutils'
157 // * For WebAssembly the only functional linker is LLD, which doesn't
158 // support hint flags
159 !self.sess.target.target.options.is_like_osx && self.sess.target.target.arch != "wasm32"
162 // Some platforms take hints about whether a library is static or dynamic.
163 // For those that support this, we ensure we pass the option if the library
164 // was flagged "static" (most defaults are dynamic) to ensure that if
165 // libfoo.a and libfoo.so both exist that the right one is chosen.
166 fn hint_static(&mut self) {
167 if !self.takes_hints() {
170 if !self.hinted_static {
171 self.linker_arg("-Bstatic");
172 self.hinted_static = true;
176 fn hint_dynamic(&mut self) {
177 if !self.takes_hints() {
180 if self.hinted_static {
181 self.linker_arg("-Bdynamic");
182 self.hinted_static = false;
186 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
187 if let Some(plugin_path) = plugin_path {
188 let mut arg = OsString::from("-plugin=");
189 arg.push(plugin_path);
190 self.linker_arg(&arg);
193 let opt_level = match self.sess.opts.optimize {
194 config::OptLevel::No => "O0",
195 config::OptLevel::Less => "O1",
196 config::OptLevel::Default => "O2",
197 config::OptLevel::Aggressive => "O3",
198 config::OptLevel::Size => "Os",
199 config::OptLevel::SizeMin => "Oz",
202 self.linker_arg(&format!("-plugin-opt={}", opt_level));
203 let target_cpu = self.target_cpu;
204 self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
208 impl<'a> Linker for GccLinker<'a> {
209 fn link_dylib(&mut self, lib: Symbol) {
211 self.cmd.arg(format!("-l{}", lib));
213 fn link_staticlib(&mut self, lib: Symbol) {
215 self.cmd.arg(format!("-l{}", lib));
217 fn link_rlib(&mut self, lib: &Path) {
221 fn include_path(&mut self, path: &Path) {
222 self.cmd.arg("-L").arg(path);
224 fn framework_path(&mut self, path: &Path) {
225 self.cmd.arg("-F").arg(path);
227 fn output_filename(&mut self, path: &Path) {
228 self.cmd.arg("-o").arg(path);
230 fn add_object(&mut self, path: &Path) {
233 fn position_independent_executable(&mut self) {
234 self.cmd.arg("-pie");
236 fn no_position_independent_executable(&mut self) {
237 self.cmd.arg("-no-pie");
239 fn full_relro(&mut self) {
240 self.linker_arg("-zrelro");
241 self.linker_arg("-znow");
243 fn partial_relro(&mut self) {
244 self.linker_arg("-zrelro");
246 fn no_relro(&mut self) {
247 self.linker_arg("-znorelro");
249 fn build_static_executable(&mut self) {
250 self.cmd.arg("-static");
252 fn args(&mut self, args: &[String]) {
256 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
258 self.cmd.arg(format!("-l{}", lib));
261 fn link_framework(&mut self, framework: Symbol) {
263 self.cmd.arg("-framework").sym_arg(framework);
266 // Here we explicitly ask that the entire archive is included into the
267 // result artifact. For more details see #15460, but the gist is that
268 // the linker will strip away any unused objects in the archive if we
269 // don't otherwise explicitly reference them. This can occur for
270 // libraries which are just providing bindings, libraries with generic
272 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
274 let target = &self.sess.target.target;
275 if !target.options.is_like_osx {
276 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
277 self.linker_arg("--no-whole-archive");
279 // -force_load is the macOS equivalent of --whole-archive, but it
280 // involves passing the full path to the library to link.
281 self.linker_arg("-force_load");
282 let lib = archive::find_library(lib, search_path, &self.sess);
283 self.linker_arg(&lib);
287 fn link_whole_rlib(&mut self, lib: &Path) {
289 if self.sess.target.target.options.is_like_osx {
290 self.linker_arg("-force_load");
291 self.linker_arg(&lib);
293 self.linker_arg("--whole-archive").cmd.arg(lib);
294 self.linker_arg("--no-whole-archive");
298 fn gc_sections(&mut self, keep_metadata: bool) {
299 // The dead_strip option to the linker specifies that functions and data
300 // unreachable by the entry point will be removed. This is quite useful
301 // with Rust's compilation model of compiling libraries at a time into
302 // one object file. For example, this brings hello world from 1.7MB to
305 // Note that this is done for both executables and dynamic libraries. We
306 // won't get much benefit from dylibs because LLVM will have already
307 // stripped away as much as it could. This has not been seen to impact
308 // link times negatively.
310 // -dead_strip can't be part of the pre_link_args because it's also used
311 // for partial linking when using multiple codegen units (-r). So we
313 if self.sess.target.target.options.is_like_osx {
314 self.linker_arg("-dead_strip");
315 } else if self.sess.target.target.options.is_like_solaris {
316 self.linker_arg("-zignore");
318 // If we're building a dylib, we don't use --gc-sections because LLVM
319 // has already done the best it can do, and we also don't want to
320 // eliminate the metadata. If we're building an executable, however,
321 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
323 } else if !keep_metadata {
324 self.linker_arg("--gc-sections");
328 fn optimize(&mut self) {
329 if !self.sess.target.target.options.linker_is_gnu {
333 // GNU-style linkers support optimization with -O. GNU ld doesn't
334 // need a numeric argument, but other linkers do.
335 if self.sess.opts.optimize == config::OptLevel::Default
336 || self.sess.opts.optimize == config::OptLevel::Aggressive
338 self.linker_arg("-O1");
342 fn pgo_gen(&mut self) {
343 if !self.sess.target.target.options.linker_is_gnu {
347 // If we're doing PGO generation stuff and on a GNU-like linker, use the
348 // "-u" flag to properly pull in the profiler runtime bits.
350 // This is because LLVM otherwise won't add the needed initialization
351 // for us on Linux (though the extra flag should be harmless if it
354 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
356 // Though it may be worth to try to revert those changes upstream, since
357 // the overhead of the initialization should be minor.
359 self.cmd.arg("__llvm_profile_runtime");
362 fn debuginfo(&mut self) {
363 if let DebugInfo::None = self.sess.opts.debuginfo {
364 // If we are building without debuginfo enabled and we were called with
365 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
366 // found when linking to get rid of symbols from libstd.
367 if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
368 self.linker_arg("-S");
373 fn no_default_libraries(&mut self) {
375 self.cmd.arg("-nodefaultlibs");
379 fn build_dylib(&mut self, out_filename: &Path) {
380 // On mac we need to tell the linker to let this library be rpathed
381 if self.sess.target.target.options.is_like_osx {
382 self.cmd.arg("-dynamiclib");
383 self.linker_arg("-dylib");
385 // Note that the `osx_rpath_install_name` option here is a hack
386 // purely to support rustbuild right now, we should get a more
387 // principled solution at some point to force the compiler to pass
388 // the right `-Wl,-install_name` with an `@rpath` in it.
389 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
390 self.linker_arg("-install_name");
391 let mut v = OsString::from("@rpath/");
392 v.push(out_filename.file_name().unwrap());
396 self.cmd.arg("-shared");
397 if self.sess.target.target.options.is_like_windows {
398 // The output filename already contains `dll_suffix` so
399 // the resulting import library will have a name in the
400 // form of libfoo.dll.a
402 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
405 self.sess.target.target.options.staticlib_prefix,
407 self.sess.target.target.options.staticlib_suffix
410 if let Some(implib_name) = implib_name {
411 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
412 if let Some(implib) = implib {
413 self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
420 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
421 // Symbol visibility in object files typically takes care of this.
422 if crate_type == CrateType::Executable
423 && self.sess.target.target.options.override_export_symbols.is_none()
428 // We manually create a list of exported symbols to ensure we don't expose any more.
429 // The object files have far more public symbols than we actually want to export,
430 // so we hide them all here.
432 if !self.sess.target.target.options.limit_rdylib_exports {
436 if crate_type == CrateType::ProcMacro {
440 let mut arg = OsString::new();
441 let path = tmpdir.join("list");
443 debug!("EXPORTED SYMBOLS:");
445 if self.sess.target.target.options.is_like_osx {
446 // Write a plain, newline-separated list of symbols
447 let res: io::Result<()> = try {
448 let mut f = BufWriter::new(File::create(&path)?);
449 for sym in self.info.exports[&crate_type].iter() {
451 writeln!(f, "_{}", sym)?;
454 if let Err(e) = res {
455 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
458 // Write an LD version script
459 let res: io::Result<()> = try {
460 let mut f = BufWriter::new(File::create(&path)?);
462 if !self.info.exports[&crate_type].is_empty() {
463 writeln!(f, " global:")?;
464 for sym in self.info.exports[&crate_type].iter() {
466 writeln!(f, " {};", sym)?;
469 writeln!(f, "\n local:\n *;\n}};")?;
471 if let Err(e) = res {
472 self.sess.fatal(&format!("failed to write version script: {}", e));
476 if self.sess.target.target.options.is_like_osx {
480 arg.push("-exported_symbols_list,");
481 } else if self.sess.target.target.options.is_like_solaris {
490 arg.push("--version-script=");
497 fn subsystem(&mut self, subsystem: &str) {
498 self.linker_arg("--subsystem");
499 self.linker_arg(&subsystem);
502 fn finalize(&mut self) -> Command {
503 self.hint_dynamic(); // Reset to default before returning the composed command line.
505 ::std::mem::replace(&mut self.cmd, Command::new(""))
508 fn group_start(&mut self) {
509 if self.takes_hints() {
510 self.linker_arg("--start-group");
514 fn group_end(&mut self) {
515 if self.takes_hints() {
516 self.linker_arg("--end-group");
520 fn linker_plugin_lto(&mut self) {
521 match self.sess.opts.cg.linker_plugin_lto {
522 LinkerPluginLto::Disabled => {
525 LinkerPluginLto::LinkerPluginAuto => {
526 self.push_linker_plugin_lto_args(None);
528 LinkerPluginLto::LinkerPlugin(ref path) => {
529 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
535 pub struct MsvcLinker<'a> {
538 info: &'a LinkerInfo,
541 impl<'a> Linker for MsvcLinker<'a> {
542 fn link_rlib(&mut self, lib: &Path) {
545 fn add_object(&mut self, path: &Path) {
548 fn args(&mut self, args: &[String]) {
552 fn build_dylib(&mut self, out_filename: &Path) {
553 self.cmd.arg("/DLL");
554 let mut arg: OsString = "/IMPLIB:".into();
555 arg.push(out_filename.with_extension("dll.lib"));
559 fn build_static_executable(&mut self) {
563 fn gc_sections(&mut self, _keep_metadata: bool) {
564 // MSVC's ICF (Identical COMDAT Folding) link optimization is
565 // slow for Rust and thus we disable it by default when not in
566 // optimization build.
567 if self.sess.opts.optimize != config::OptLevel::No {
568 self.cmd.arg("/OPT:REF,ICF");
570 // It is necessary to specify NOICF here, because /OPT:REF
571 // implies ICF by default.
572 self.cmd.arg("/OPT:REF,NOICF");
576 fn link_dylib(&mut self, lib: Symbol) {
577 self.cmd.arg(&format!("{}.lib", lib));
580 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
581 // When producing a dll, the MSVC linker may not actually emit a
582 // `foo.lib` file if the dll doesn't actually export any symbols, so we
583 // check to see if the file is there and just omit linking to it if it's
585 let name = format!("{}.dll.lib", lib);
586 if fs::metadata(&path.join(&name)).is_ok() {
591 fn link_staticlib(&mut self, lib: Symbol) {
592 self.cmd.arg(&format!("{}.lib", lib));
595 fn position_independent_executable(&mut self) {
599 fn no_position_independent_executable(&mut self) {
603 fn full_relro(&mut self) {
607 fn partial_relro(&mut self) {
611 fn no_relro(&mut self) {
615 fn no_default_libraries(&mut self) {
616 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
617 // as there's been trouble in the past of linking the C++ standard
618 // library required by LLVM. This likely needs to happen one day, but
619 // in general Windows is also a more controlled environment than
620 // Unix, so it's not necessarily as critical that this be implemented.
622 // Note that there are also some licensing worries about statically
623 // linking some libraries which require a specific agreement, so it may
624 // not ever be possible for us to pass this flag.
627 fn include_path(&mut self, path: &Path) {
628 let mut arg = OsString::from("/LIBPATH:");
633 fn output_filename(&mut self, path: &Path) {
634 let mut arg = OsString::from("/OUT:");
639 fn framework_path(&mut self, _path: &Path) {
640 bug!("frameworks are not supported on windows")
642 fn link_framework(&mut self, _framework: Symbol) {
643 bug!("frameworks are not supported on windows")
646 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
648 self.link_staticlib(lib);
650 fn link_whole_rlib(&mut self, path: &Path) {
652 self.link_rlib(path);
654 fn optimize(&mut self) {
655 // Needs more investigation of `/OPT` arguments
658 fn pgo_gen(&mut self) {
659 // Nothing needed here.
662 fn debuginfo(&mut self) {
663 // This will cause the Microsoft linker to generate a PDB file
664 // from the CodeView line tables in the object files.
665 self.cmd.arg("/DEBUG");
667 // This will cause the Microsoft linker to embed .natvis info into the PDB file
668 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
669 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
670 for entry in natvis_dir {
673 let path = entry.path();
674 if path.extension() == Some("natvis".as_ref()) {
675 let mut arg = OsString::from("/NATVIS:");
681 self.sess.warn(&format!("error enumerating natvis directory: {}", err));
688 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
689 // export symbols from a dynamic library. When building a dynamic library,
690 // however, we're going to want some symbols exported, so this function
691 // generates a DEF file which lists all the symbols.
693 // The linker will read this `*.def` file and export all the symbols from
694 // the dynamic library. Note that this is not as simple as just exporting
695 // all the symbols in the current crate (as specified by `codegen.reachable`)
696 // but rather we also need to possibly export the symbols of upstream
697 // crates. Upstream rlibs may be linked statically to this dynamic library,
698 // in which case they may continue to transitively be used and hence need
699 // their symbols exported.
700 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
701 // Symbol visibility takes care of this typically
702 if crate_type == CrateType::Executable {
706 let path = tmpdir.join("lib.def");
707 let res: io::Result<()> = try {
708 let mut f = BufWriter::new(File::create(&path)?);
710 // Start off with the standard module name header and then go
711 // straight to exports.
712 writeln!(f, "LIBRARY")?;
713 writeln!(f, "EXPORTS")?;
714 for symbol in self.info.exports[&crate_type].iter() {
715 debug!(" _{}", symbol);
716 writeln!(f, " {}", symbol)?;
719 if let Err(e) = res {
720 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
722 let mut arg = OsString::from("/DEF:");
727 fn subsystem(&mut self, subsystem: &str) {
728 // Note that previous passes of the compiler validated this subsystem,
729 // so we just blindly pass it to the linker.
730 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
732 // Windows has two subsystems we're interested in right now, the console
733 // and windows subsystems. These both implicitly have different entry
734 // points (starting symbols). The console entry point starts with
735 // `mainCRTStartup` and the windows entry point starts with
736 // `WinMainCRTStartup`. These entry points, defined in system libraries,
737 // will then later probe for either `main` or `WinMain`, respectively to
738 // start the application.
740 // In Rust we just always generate a `main` function so we want control
741 // to always start there, so we force the entry point on the windows
742 // subsystem to be `mainCRTStartup` to get everything booted up
745 // For more information see RFC #1665
746 if subsystem == "windows" {
747 self.cmd.arg("/ENTRY:mainCRTStartup");
751 fn finalize(&mut self) -> Command {
752 ::std::mem::replace(&mut self.cmd, Command::new(""))
755 // MSVC doesn't need group indicators
756 fn group_start(&mut self) {}
757 fn group_end(&mut self) {}
759 fn linker_plugin_lto(&mut self) {
764 pub struct EmLinker<'a> {
767 info: &'a LinkerInfo,
770 impl<'a> Linker for EmLinker<'a> {
771 fn include_path(&mut self, path: &Path) {
772 self.cmd.arg("-L").arg(path);
775 fn link_staticlib(&mut self, lib: Symbol) {
776 self.cmd.arg("-l").sym_arg(lib);
779 fn output_filename(&mut self, path: &Path) {
780 self.cmd.arg("-o").arg(path);
783 fn add_object(&mut self, path: &Path) {
787 fn link_dylib(&mut self, lib: Symbol) {
788 // Emscripten always links statically
789 self.link_staticlib(lib);
792 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
794 self.link_staticlib(lib);
797 fn link_whole_rlib(&mut self, lib: &Path) {
802 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
803 self.link_dylib(lib);
806 fn link_rlib(&mut self, lib: &Path) {
807 self.add_object(lib);
810 fn position_independent_executable(&mut self) {
814 fn no_position_independent_executable(&mut self) {
818 fn full_relro(&mut self) {
822 fn partial_relro(&mut self) {
826 fn no_relro(&mut self) {
830 fn args(&mut self, args: &[String]) {
834 fn framework_path(&mut self, _path: &Path) {
835 bug!("frameworks are not supported on Emscripten")
838 fn link_framework(&mut self, _framework: Symbol) {
839 bug!("frameworks are not supported on Emscripten")
842 fn gc_sections(&mut self, _keep_metadata: bool) {
846 fn optimize(&mut self) {
847 // Emscripten performs own optimizations
848 self.cmd.arg(match self.sess.opts.optimize {
849 OptLevel::No => "-O0",
850 OptLevel::Less => "-O1",
851 OptLevel::Default => "-O2",
852 OptLevel::Aggressive => "-O3",
853 OptLevel::Size => "-Os",
854 OptLevel::SizeMin => "-Oz",
856 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
857 self.cmd.args(&["--memory-init-file", "0"]);
860 fn pgo_gen(&mut self) {
861 // noop, but maybe we need something like the gnu linker?
864 fn debuginfo(&mut self) {
865 // Preserve names or generate source maps depending on debug info
866 self.cmd.arg(match self.sess.opts.debuginfo {
867 DebugInfo::None => "-g0",
868 DebugInfo::Limited => "-g3",
869 DebugInfo::Full => "-g4",
873 fn no_default_libraries(&mut self) {
874 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
877 fn build_dylib(&mut self, _out_filename: &Path) {
878 bug!("building dynamic library is unsupported on Emscripten")
881 fn build_static_executable(&mut self) {
885 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
886 let symbols = &self.info.exports[&crate_type];
888 debug!("EXPORTED SYMBOLS:");
892 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
893 let mut encoded = String::new();
896 let mut encoder = json::Encoder::new(&mut encoded);
897 let res = encoder.emit_seq(symbols.len(), |encoder| {
898 for (i, sym) in symbols.iter().enumerate() {
899 encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
903 if let Err(e) = res {
904 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
907 debug!("{}", encoded);
913 fn subsystem(&mut self, _subsystem: &str) {
917 fn finalize(&mut self) -> Command {
918 ::std::mem::replace(&mut self.cmd, Command::new(""))
921 // Appears not necessary on Emscripten
922 fn group_start(&mut self) {}
923 fn group_end(&mut self) {}
925 fn linker_plugin_lto(&mut self) {
930 pub struct WasmLd<'a> {
933 info: &'a LinkerInfo,
936 impl<'a> WasmLd<'a> {
937 fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
938 // If the atomics feature is enabled for wasm then we need a whole bunch
941 // * `--shared-memory` - the link won't even succeed without this, flags
942 // the one linear memory as `shared`
944 // * `--max-memory=1G` - when specifying a shared memory this must also
945 // be specified. We conservatively choose 1GB but users should be able
946 // to override this with `-C link-arg`.
948 // * `--import-memory` - it doesn't make much sense for memory to be
949 // exported in a threaded module because typically you're
950 // sharing memory and instantiating the module multiple times. As a
951 // result if it were exported then we'd just have no sharing.
953 // * `--passive-segments` - all memory segments should be passive to
954 // prevent each module instantiation from reinitializing memory.
956 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
957 // linker will synthesize this function, and so we need to make sure
958 // that our usage of `--export` below won't accidentally cause this
959 // function to get deleted.
961 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
962 // symbols are how the TLS segments are initialized and configured.
963 let atomics = sess.opts.cg.target_feature.contains("+atomics")
964 || sess.target.target.options.features.contains("+atomics");
966 cmd.arg("--shared-memory");
967 cmd.arg("--max-memory=1073741824");
968 cmd.arg("--import-memory");
969 cmd.arg("--passive-segments");
970 cmd.arg("--export=__wasm_init_memory");
971 cmd.arg("--export=__wasm_init_tls");
972 cmd.arg("--export=__tls_size");
973 cmd.arg("--export=__tls_align");
974 cmd.arg("--export=__tls_base");
976 WasmLd { cmd, sess, info }
980 impl<'a> Linker for WasmLd<'a> {
981 fn link_dylib(&mut self, lib: Symbol) {
982 self.cmd.arg("-l").sym_arg(lib);
985 fn link_staticlib(&mut self, lib: Symbol) {
986 self.cmd.arg("-l").sym_arg(lib);
989 fn link_rlib(&mut self, lib: &Path) {
993 fn include_path(&mut self, path: &Path) {
994 self.cmd.arg("-L").arg(path);
997 fn framework_path(&mut self, _path: &Path) {
998 panic!("frameworks not supported")
1001 fn output_filename(&mut self, path: &Path) {
1002 self.cmd.arg("-o").arg(path);
1005 fn add_object(&mut self, path: &Path) {
1009 fn position_independent_executable(&mut self) {}
1011 fn full_relro(&mut self) {}
1013 fn partial_relro(&mut self) {}
1015 fn no_relro(&mut self) {}
1017 fn build_static_executable(&mut self) {}
1019 fn args(&mut self, args: &[String]) {
1020 self.cmd.args(args);
1023 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1024 self.cmd.arg("-l").sym_arg(lib);
1027 fn link_framework(&mut self, _framework: Symbol) {
1028 panic!("frameworks not supported")
1031 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1032 self.cmd.arg("-l").sym_arg(lib);
1035 fn link_whole_rlib(&mut self, lib: &Path) {
1039 fn gc_sections(&mut self, _keep_metadata: bool) {
1040 self.cmd.arg("--gc-sections");
1043 fn optimize(&mut self) {
1044 self.cmd.arg(match self.sess.opts.optimize {
1045 OptLevel::No => "-O0",
1046 OptLevel::Less => "-O1",
1047 OptLevel::Default => "-O2",
1048 OptLevel::Aggressive => "-O3",
1049 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1051 OptLevel::Size => "-O2",
1052 OptLevel::SizeMin => "-O2",
1056 fn pgo_gen(&mut self) {}
1058 fn debuginfo(&mut self) {}
1060 fn no_default_libraries(&mut self) {}
1062 fn build_dylib(&mut self, _out_filename: &Path) {
1063 self.cmd.arg("--no-entry");
1066 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1067 for sym in self.info.exports[&crate_type].iter() {
1068 self.cmd.arg("--export").arg(&sym);
1071 // LLD will hide these otherwise-internal symbols since our `--export`
1072 // list above is a whitelist of what to export. Various bits and pieces
1073 // of tooling use this, so be sure these symbols make their way out of
1074 // the linker as well.
1075 self.cmd.arg("--export=__heap_base");
1076 self.cmd.arg("--export=__data_end");
1079 fn subsystem(&mut self, _subsystem: &str) {}
1081 fn no_position_independent_executable(&mut self) {}
1083 fn finalize(&mut self) -> Command {
1084 ::std::mem::replace(&mut self.cmd, Command::new(""))
1087 // Not needed for now with LLD
1088 fn group_start(&mut self) {}
1089 fn group_end(&mut self) {}
1091 fn linker_plugin_lto(&mut self) {
1092 // Do nothing for now
1096 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1097 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1098 return exports.clone();
1101 let mut symbols = Vec::new();
1103 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1104 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1105 if level.is_below_threshold(export_threshold) {
1106 symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1114 let formats = tcx.dependency_formats(LOCAL_CRATE);
1117 .filter_map(|(t, list)| if *t == crate_type { Some(list) } else { None })
1121 for (index, dep_format) in deps.iter().enumerate() {
1122 let cnum = CrateNum::new(index + 1);
1123 // For each dependency that we are linking to statically ...
1124 if *dep_format == Linkage::Static {
1125 // ... we add its symbol list to our export list.
1126 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1127 if !level.is_below_threshold(export_threshold) {
1131 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1139 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1140 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1141 pub struct PtxLinker<'a> {
1146 impl<'a> Linker for PtxLinker<'a> {
1147 fn link_rlib(&mut self, path: &Path) {
1148 self.cmd.arg("--rlib").arg(path);
1151 fn link_whole_rlib(&mut self, path: &Path) {
1152 self.cmd.arg("--rlib").arg(path);
1155 fn include_path(&mut self, path: &Path) {
1156 self.cmd.arg("-L").arg(path);
1159 fn debuginfo(&mut self) {
1160 self.cmd.arg("--debug");
1163 fn add_object(&mut self, path: &Path) {
1164 self.cmd.arg("--bitcode").arg(path);
1167 fn args(&mut self, args: &[String]) {
1168 self.cmd.args(args);
1171 fn optimize(&mut self) {
1172 match self.sess.lto() {
1173 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1174 self.cmd.arg("-Olto");
1181 fn output_filename(&mut self, path: &Path) {
1182 self.cmd.arg("-o").arg(path);
1185 fn finalize(&mut self) -> Command {
1186 // Provide the linker with fallback to internal `target-cpu`.
1187 self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1189 None => &self.sess.target.target.options.cpu,
1192 ::std::mem::replace(&mut self.cmd, Command::new(""))
1195 fn link_dylib(&mut self, _lib: Symbol) {
1196 panic!("external dylibs not supported")
1199 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1200 panic!("external dylibs not supported")
1203 fn link_staticlib(&mut self, _lib: Symbol) {
1204 panic!("staticlibs not supported")
1207 fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1208 panic!("staticlibs not supported")
1211 fn framework_path(&mut self, _path: &Path) {
1212 panic!("frameworks not supported")
1215 fn link_framework(&mut self, _framework: Symbol) {
1216 panic!("frameworks not supported")
1219 fn position_independent_executable(&mut self) {}
1221 fn full_relro(&mut self) {}
1223 fn partial_relro(&mut self) {}
1225 fn no_relro(&mut self) {}
1227 fn build_static_executable(&mut self) {}
1229 fn gc_sections(&mut self, _keep_metadata: bool) {}
1231 fn pgo_gen(&mut self) {}
1233 fn no_default_libraries(&mut self) {}
1235 fn build_dylib(&mut self, _out_filename: &Path) {}
1237 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {}
1239 fn subsystem(&mut self, _subsystem: &str) {}
1241 fn no_position_independent_executable(&mut self) {}
1243 fn group_start(&mut self) {}
1245 fn group_end(&mut self) {}
1247 fn linker_plugin_lto(&mut self) {}