2 use super::command::Command;
3 use super::symbol_export;
4 use rustc_span::symbol::sym;
6 use std::ffi::{OsStr, OsString};
7 use std::fs::{self, File};
8 use std::io::prelude::*;
9 use std::io::{self, BufWriter};
11 use std::path::{Path, PathBuf};
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
15 use rustc_middle::middle::dependency_format::Linkage;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_serialize::{json, Encoder};
18 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
19 use rustc_session::Session;
20 use rustc_span::symbol::Symbol;
21 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
23 /// Disables non-English messages from localized linkers.
24 /// Such messages may cause issues with text encoding on Windows (#35785)
25 /// and prevent inspection of linker output in case of errors, which we occasionally do.
26 /// This should be acceptable because other messages from rustc are in English anyway,
27 /// and may also be desirable to improve searchability of the linker diagnostics.
28 pub fn disable_localization(linker: &mut Command) {
29 // No harm in setting both env vars simultaneously.
30 // Unix-style linkers.
31 linker.env("LC_ALL", "C");
33 linker.env("VSLANG", "1033");
36 /// For all the linkers we support, and information they might
37 /// need out of the shared crate context before we get rid of it.
38 #[derive(RustcEncodable, RustcDecodable)]
39 pub struct LinkerInfo {
40 exports: FxHashMap<CrateType, Vec<String>>,
44 pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
50 .map(|&c| (c, exported_symbols(tcx, c)))
61 ) -> Box<dyn Linker + 'a> {
63 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
64 Box::new(MsvcLinker { cmd, sess, info: self }) as Box<dyn Linker>
66 LinkerFlavor::Em => Box::new(EmLinker { cmd, sess, info: self }) as Box<dyn Linker>,
67 LinkerFlavor::Gcc => Box::new(GccLinker {
74 }) as Box<dyn Linker>,
76 LinkerFlavor::Lld(LldFlavor::Ld)
77 | LinkerFlavor::Lld(LldFlavor::Ld64)
78 | LinkerFlavor::Ld => Box::new(GccLinker {
85 }) as Box<dyn Linker>,
87 LinkerFlavor::Lld(LldFlavor::Wasm) => {
88 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
91 LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
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 cmd(&mut self) -> &mut Command;
105 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
106 fn link_dylib(&mut self, lib: Symbol);
107 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
108 fn link_framework(&mut self, framework: Symbol);
109 fn link_staticlib(&mut self, lib: Symbol);
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: Symbol, 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 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 control_flow_guard(&mut self);
124 fn debuginfo(&mut self, strip: Strip);
125 fn no_crt_objects(&mut self);
126 fn no_default_libraries(&mut self);
127 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
128 fn subsystem(&mut self, subsystem: &str);
129 fn group_start(&mut self);
130 fn group_end(&mut self);
131 fn linker_plugin_lto(&mut self);
132 fn add_eh_frame_header(&mut self) {}
133 fn finalize(&mut self);
136 impl dyn Linker + '_ {
137 pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
141 pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
142 self.cmd().args(args);
145 pub fn take_cmd(&mut self) -> Command {
146 mem::replace(self.cmd(), Command::new(""))
150 pub struct GccLinker<'a> {
153 info: &'a LinkerInfo,
154 hinted_static: bool, // Keeps track of the current hinting mode.
160 impl<'a> GccLinker<'a> {
161 /// Argument that must be passed *directly* to the linker
163 /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
164 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
169 let mut os = OsString::from("-Wl,");
170 os.push(arg.as_ref());
178 fn takes_hints(&self) -> bool {
179 // Really this function only returns true if the underlying linker
180 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
181 // don't really have a foolproof way to detect that, so rule out some
182 // platforms where currently this is guaranteed to *not* be the case:
184 // * On OSX they have their own linker, not binutils'
185 // * For WebAssembly the only functional linker is LLD, which doesn't
186 // support hint flags
187 !self.sess.target.target.options.is_like_osx && self.sess.target.target.arch != "wasm32"
190 // Some platforms take hints about whether a library is static or dynamic.
191 // For those that support this, we ensure we pass the option if the library
192 // was flagged "static" (most defaults are dynamic) to ensure that if
193 // libfoo.a and libfoo.so both exist that the right one is chosen.
194 fn hint_static(&mut self) {
195 if !self.takes_hints() {
198 if !self.hinted_static {
199 self.linker_arg("-Bstatic");
200 self.hinted_static = true;
204 fn hint_dynamic(&mut self) {
205 if !self.takes_hints() {
208 if self.hinted_static {
209 self.linker_arg("-Bdynamic");
210 self.hinted_static = false;
214 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
215 if let Some(plugin_path) = plugin_path {
216 let mut arg = OsString::from("-plugin=");
217 arg.push(plugin_path);
218 self.linker_arg(&arg);
221 let opt_level = match self.sess.opts.optimize {
222 config::OptLevel::No => "O0",
223 config::OptLevel::Less => "O1",
224 config::OptLevel::Default => "O2",
225 config::OptLevel::Aggressive => "O3",
226 config::OptLevel::Size => "Os",
227 config::OptLevel::SizeMin => "Oz",
230 self.linker_arg(&format!("-plugin-opt={}", opt_level));
231 let target_cpu = self.target_cpu;
232 self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
235 fn build_dylib(&mut self, out_filename: &Path) {
236 // On mac we need to tell the linker to let this library be rpathed
237 if self.sess.target.target.options.is_like_osx {
238 self.cmd.arg("-dynamiclib");
239 self.linker_arg("-dylib");
241 // Note that the `osx_rpath_install_name` option here is a hack
242 // purely to support rustbuild right now, we should get a more
243 // principled solution at some point to force the compiler to pass
244 // the right `-Wl,-install_name` with an `@rpath` in it.
245 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
246 self.linker_arg("-install_name");
247 let mut v = OsString::from("@rpath/");
248 v.push(out_filename.file_name().unwrap());
252 self.cmd.arg("-shared");
253 if self.sess.target.target.options.is_like_windows {
254 // The output filename already contains `dll_suffix` so
255 // the resulting import library will have a name in the
256 // form of libfoo.dll.a
258 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
261 self.sess.target.target.options.staticlib_prefix,
263 self.sess.target.target.options.staticlib_suffix
266 if let Some(implib_name) = implib_name {
267 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
268 if let Some(implib) = implib {
269 self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
277 impl<'a> Linker for GccLinker<'a> {
278 fn cmd(&mut self) -> &mut Command {
282 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
284 LinkOutputKind::DynamicNoPicExe => {
285 if !self.is_ld && self.sess.target.target.options.linker_is_gnu {
286 self.cmd.arg("-no-pie");
289 LinkOutputKind::DynamicPicExe => {
290 // `-pie` works for both gcc wrapper and ld.
291 self.cmd.arg("-pie");
293 LinkOutputKind::StaticNoPicExe => {
294 // `-static` works for both gcc wrapper and ld.
295 self.cmd.arg("-static");
296 if !self.is_ld && self.sess.target.target.options.linker_is_gnu {
297 self.cmd.arg("-no-pie");
300 LinkOutputKind::StaticPicExe => {
302 // Note that combination `-static -pie` doesn't work as expected
303 // for the gcc wrapper, `-static` in that case suppresses `-pie`.
304 self.cmd.arg("-static-pie");
306 // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
307 // a static pie, but currently passed because gcc and clang pass them.
308 // The former suppresses the `INTERP` ELF header specifying dynamic linker,
309 // which is otherwise implicitly injected by ld (but not lld).
310 // The latter doesn't change anything, only ensures that everything is pic.
311 self.cmd.args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
314 LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
315 LinkOutputKind::StaticDylib => {
316 self.cmd.arg("-static");
317 self.build_dylib(out_filename);
320 // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
321 // it switches linking for libc and similar system libraries to static without using
322 // any `#[link]` attributes in the `libc` crate, see #72782 for details.
323 // FIXME: Switch to using `#[link]` attributes in the `libc` crate
324 // similarly to other targets.
325 if self.sess.target.target.target_os == "vxworks"
328 LinkOutputKind::StaticNoPicExe
329 | LinkOutputKind::StaticPicExe
330 | LinkOutputKind::StaticDylib
333 self.cmd.arg("--static-crt");
337 fn link_dylib(&mut self, lib: Symbol) {
339 self.cmd.arg(format!("-l{}", lib));
341 fn link_staticlib(&mut self, lib: Symbol) {
343 self.cmd.arg(format!("-l{}", lib));
345 fn link_rlib(&mut self, lib: &Path) {
349 fn include_path(&mut self, path: &Path) {
350 self.cmd.arg("-L").arg(path);
352 fn framework_path(&mut self, path: &Path) {
353 self.cmd.arg("-F").arg(path);
355 fn output_filename(&mut self, path: &Path) {
356 self.cmd.arg("-o").arg(path);
358 fn add_object(&mut self, path: &Path) {
361 fn full_relro(&mut self) {
362 self.linker_arg("-zrelro");
363 self.linker_arg("-znow");
365 fn partial_relro(&mut self) {
366 self.linker_arg("-zrelro");
368 fn no_relro(&mut self) {
369 self.linker_arg("-znorelro");
372 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
374 self.cmd.arg(format!("-l{}", lib));
377 fn link_framework(&mut self, framework: Symbol) {
379 self.cmd.arg("-framework").sym_arg(framework);
382 // Here we explicitly ask that the entire archive is included into the
383 // result artifact. For more details see #15460, but the gist is that
384 // the linker will strip away any unused objects in the archive if we
385 // don't otherwise explicitly reference them. This can occur for
386 // libraries which are just providing bindings, libraries with generic
388 fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
390 let target = &self.sess.target.target;
391 if !target.options.is_like_osx {
392 self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
393 self.linker_arg("--no-whole-archive");
395 // -force_load is the macOS equivalent of --whole-archive, but it
396 // involves passing the full path to the library to link.
397 self.linker_arg("-force_load");
398 let lib = archive::find_library(lib, search_path, &self.sess);
399 self.linker_arg(&lib);
403 fn link_whole_rlib(&mut self, lib: &Path) {
405 if self.sess.target.target.options.is_like_osx {
406 self.linker_arg("-force_load");
407 self.linker_arg(&lib);
409 self.linker_arg("--whole-archive").cmd.arg(lib);
410 self.linker_arg("--no-whole-archive");
414 fn gc_sections(&mut self, keep_metadata: bool) {
415 // The dead_strip option to the linker specifies that functions and data
416 // unreachable by the entry point will be removed. This is quite useful
417 // with Rust's compilation model of compiling libraries at a time into
418 // one object file. For example, this brings hello world from 1.7MB to
421 // Note that this is done for both executables and dynamic libraries. We
422 // won't get much benefit from dylibs because LLVM will have already
423 // stripped away as much as it could. This has not been seen to impact
424 // link times negatively.
426 // -dead_strip can't be part of the pre_link_args because it's also used
427 // for partial linking when using multiple codegen units (-r). So we
429 if self.sess.target.target.options.is_like_osx {
430 self.linker_arg("-dead_strip");
431 } else if self.sess.target.target.options.is_like_solaris {
432 self.linker_arg("-zignore");
434 // If we're building a dylib, we don't use --gc-sections because LLVM
435 // has already done the best it can do, and we also don't want to
436 // eliminate the metadata. If we're building an executable, however,
437 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
439 } else if !keep_metadata {
440 self.linker_arg("--gc-sections");
444 fn optimize(&mut self) {
445 if !self.sess.target.target.options.linker_is_gnu {
449 // GNU-style linkers support optimization with -O. GNU ld doesn't
450 // need a numeric argument, but other linkers do.
451 if self.sess.opts.optimize == config::OptLevel::Default
452 || self.sess.opts.optimize == config::OptLevel::Aggressive
454 self.linker_arg("-O1");
458 fn pgo_gen(&mut self) {
459 if !self.sess.target.target.options.linker_is_gnu {
463 // If we're doing PGO generation stuff and on a GNU-like linker, use the
464 // "-u" flag to properly pull in the profiler runtime bits.
466 // This is because LLVM otherwise won't add the needed initialization
467 // for us on Linux (though the extra flag should be harmless if it
470 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
472 // Though it may be worth to try to revert those changes upstream, since
473 // the overhead of the initialization should be minor.
475 self.cmd.arg("__llvm_profile_runtime");
478 fn control_flow_guard(&mut self) {}
480 fn debuginfo(&mut self, strip: Strip) {
483 Strip::Debuginfo => {
484 // MacOS linker does not support longhand argument --strip-debug
485 self.linker_arg("-S");
488 // MacOS linker does not support longhand argument --strip-all
489 self.linker_arg("-s");
494 fn no_crt_objects(&mut self) {
496 self.cmd.arg("-nostartfiles");
500 fn no_default_libraries(&mut self) {
502 self.cmd.arg("-nodefaultlibs");
506 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
507 // Symbol visibility in object files typically takes care of this.
508 if crate_type == CrateType::Executable
509 && self.sess.target.target.options.override_export_symbols.is_none()
514 // We manually create a list of exported symbols to ensure we don't expose any more.
515 // The object files have far more public symbols than we actually want to export,
516 // so we hide them all here.
518 if !self.sess.target.target.options.limit_rdylib_exports {
522 if crate_type == CrateType::ProcMacro {
526 let mut arg = OsString::new();
527 let path = tmpdir.join("list");
529 debug!("EXPORTED SYMBOLS:");
531 if self.sess.target.target.options.is_like_osx {
532 // Write a plain, newline-separated list of symbols
533 let res: io::Result<()> = try {
534 let mut f = BufWriter::new(File::create(&path)?);
535 for sym in self.info.exports[&crate_type].iter() {
537 writeln!(f, "_{}", sym)?;
540 if let Err(e) = res {
541 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
544 // Write an LD version script
545 let res: io::Result<()> = try {
546 let mut f = BufWriter::new(File::create(&path)?);
548 if !self.info.exports[&crate_type].is_empty() {
549 writeln!(f, " global:")?;
550 for sym in self.info.exports[&crate_type].iter() {
552 writeln!(f, " {};", sym)?;
555 writeln!(f, "\n local:\n *;\n}};")?;
557 if let Err(e) = res {
558 self.sess.fatal(&format!("failed to write version script: {}", e));
562 if self.sess.target.target.options.is_like_osx {
566 arg.push("-exported_symbols_list,");
567 } else if self.sess.target.target.options.is_like_solaris {
576 arg.push("--version-script=");
583 fn subsystem(&mut self, subsystem: &str) {
584 self.linker_arg("--subsystem");
585 self.linker_arg(&subsystem);
588 fn finalize(&mut self) {
589 self.hint_dynamic(); // Reset to default before returning the composed command line.
592 fn group_start(&mut self) {
593 if self.takes_hints() {
594 self.linker_arg("--start-group");
598 fn group_end(&mut self) {
599 if self.takes_hints() {
600 self.linker_arg("--end-group");
604 fn linker_plugin_lto(&mut self) {
605 match self.sess.opts.cg.linker_plugin_lto {
606 LinkerPluginLto::Disabled => {
609 LinkerPluginLto::LinkerPluginAuto => {
610 self.push_linker_plugin_lto_args(None);
612 LinkerPluginLto::LinkerPlugin(ref path) => {
613 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
618 // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
619 // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
620 // so we just always add it.
621 fn add_eh_frame_header(&mut self) {
622 self.linker_arg("--eh-frame-hdr");
626 pub struct MsvcLinker<'a> {
629 info: &'a LinkerInfo,
632 impl<'a> Linker for MsvcLinker<'a> {
633 fn cmd(&mut self) -> &mut Command {
637 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
639 LinkOutputKind::DynamicNoPicExe
640 | LinkOutputKind::DynamicPicExe
641 | LinkOutputKind::StaticNoPicExe
642 | LinkOutputKind::StaticPicExe => {}
643 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
644 self.cmd.arg("/DLL");
645 let mut arg: OsString = "/IMPLIB:".into();
646 arg.push(out_filename.with_extension("dll.lib"));
652 fn link_rlib(&mut self, lib: &Path) {
655 fn add_object(&mut self, path: &Path) {
659 fn gc_sections(&mut self, _keep_metadata: bool) {
660 // MSVC's ICF (Identical COMDAT Folding) link optimization is
661 // slow for Rust and thus we disable it by default when not in
662 // optimization build.
663 if self.sess.opts.optimize != config::OptLevel::No {
664 self.cmd.arg("/OPT:REF,ICF");
666 // It is necessary to specify NOICF here, because /OPT:REF
667 // implies ICF by default.
668 self.cmd.arg("/OPT:REF,NOICF");
672 fn link_dylib(&mut self, lib: Symbol) {
673 self.cmd.arg(&format!("{}.lib", lib));
676 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
677 // When producing a dll, the MSVC linker may not actually emit a
678 // `foo.lib` file if the dll doesn't actually export any symbols, so we
679 // check to see if the file is there and just omit linking to it if it's
681 let name = format!("{}.dll.lib", lib);
682 if fs::metadata(&path.join(&name)).is_ok() {
687 fn link_staticlib(&mut self, lib: Symbol) {
688 self.cmd.arg(&format!("{}.lib", lib));
691 fn full_relro(&mut self) {
695 fn partial_relro(&mut self) {
699 fn no_relro(&mut self) {
703 fn no_crt_objects(&mut self) {
707 fn no_default_libraries(&mut self) {
708 self.cmd.arg("/NODEFAULTLIB");
711 fn include_path(&mut self, path: &Path) {
712 let mut arg = OsString::from("/LIBPATH:");
717 fn output_filename(&mut self, path: &Path) {
718 let mut arg = OsString::from("/OUT:");
723 fn framework_path(&mut self, _path: &Path) {
724 bug!("frameworks are not supported on windows")
726 fn link_framework(&mut self, _framework: Symbol) {
727 bug!("frameworks are not supported on windows")
730 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
731 self.link_staticlib(lib);
732 self.cmd.arg(format!("/WHOLEARCHIVE:{}.lib", lib));
734 fn link_whole_rlib(&mut self, path: &Path) {
735 self.link_rlib(path);
736 let mut arg = OsString::from("/WHOLEARCHIVE:");
740 fn optimize(&mut self) {
741 // Needs more investigation of `/OPT` arguments
744 fn pgo_gen(&mut self) {
745 // Nothing needed here.
748 fn control_flow_guard(&mut self) {
749 self.cmd.arg("/guard:cf");
752 fn debuginfo(&mut self, strip: Strip) {
755 // This will cause the Microsoft linker to generate a PDB file
756 // from the CodeView line tables in the object files.
757 self.cmd.arg("/DEBUG");
759 // This will cause the Microsoft linker to embed .natvis info into the PDB file
760 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
761 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
762 for entry in natvis_dir {
765 let path = entry.path();
766 if path.extension() == Some("natvis".as_ref()) {
767 let mut arg = OsString::from("/NATVIS:");
774 .warn(&format!("error enumerating natvis directory: {}", err));
780 Strip::Debuginfo | Strip::Symbols => {
781 self.cmd.arg("/DEBUG:NONE");
786 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
787 // export symbols from a dynamic library. When building a dynamic library,
788 // however, we're going to want some symbols exported, so this function
789 // generates a DEF file which lists all the symbols.
791 // The linker will read this `*.def` file and export all the symbols from
792 // the dynamic library. Note that this is not as simple as just exporting
793 // all the symbols in the current crate (as specified by `codegen.reachable`)
794 // but rather we also need to possibly export the symbols of upstream
795 // crates. Upstream rlibs may be linked statically to this dynamic library,
796 // in which case they may continue to transitively be used and hence need
797 // their symbols exported.
798 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
799 // Symbol visibility takes care of this typically
800 if crate_type == CrateType::Executable {
804 let path = tmpdir.join("lib.def");
805 let res: io::Result<()> = try {
806 let mut f = BufWriter::new(File::create(&path)?);
808 // Start off with the standard module name header and then go
809 // straight to exports.
810 writeln!(f, "LIBRARY")?;
811 writeln!(f, "EXPORTS")?;
812 for symbol in self.info.exports[&crate_type].iter() {
813 debug!(" _{}", symbol);
814 writeln!(f, " {}", symbol)?;
817 if let Err(e) = res {
818 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
820 let mut arg = OsString::from("/DEF:");
825 fn subsystem(&mut self, subsystem: &str) {
826 // Note that previous passes of the compiler validated this subsystem,
827 // so we just blindly pass it to the linker.
828 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
830 // Windows has two subsystems we're interested in right now, the console
831 // and windows subsystems. These both implicitly have different entry
832 // points (starting symbols). The console entry point starts with
833 // `mainCRTStartup` and the windows entry point starts with
834 // `WinMainCRTStartup`. These entry points, defined in system libraries,
835 // will then later probe for either `main` or `WinMain`, respectively to
836 // start the application.
838 // In Rust we just always generate a `main` function so we want control
839 // to always start there, so we force the entry point on the windows
840 // subsystem to be `mainCRTStartup` to get everything booted up
843 // For more information see RFC #1665
844 if subsystem == "windows" {
845 self.cmd.arg("/ENTRY:mainCRTStartup");
849 fn finalize(&mut self) {}
851 // MSVC doesn't need group indicators
852 fn group_start(&mut self) {}
853 fn group_end(&mut self) {}
855 fn linker_plugin_lto(&mut self) {
860 pub struct EmLinker<'a> {
863 info: &'a LinkerInfo,
866 impl<'a> Linker for EmLinker<'a> {
867 fn cmd(&mut self) -> &mut Command {
871 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
873 fn include_path(&mut self, path: &Path) {
874 self.cmd.arg("-L").arg(path);
877 fn link_staticlib(&mut self, lib: Symbol) {
878 self.cmd.arg("-l").sym_arg(lib);
881 fn output_filename(&mut self, path: &Path) {
882 self.cmd.arg("-o").arg(path);
885 fn add_object(&mut self, path: &Path) {
889 fn link_dylib(&mut self, lib: Symbol) {
890 // Emscripten always links statically
891 self.link_staticlib(lib);
894 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
896 self.link_staticlib(lib);
899 fn link_whole_rlib(&mut self, lib: &Path) {
904 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
905 self.link_dylib(lib);
908 fn link_rlib(&mut self, lib: &Path) {
909 self.add_object(lib);
912 fn full_relro(&mut self) {
916 fn partial_relro(&mut self) {
920 fn no_relro(&mut self) {
924 fn framework_path(&mut self, _path: &Path) {
925 bug!("frameworks are not supported on Emscripten")
928 fn link_framework(&mut self, _framework: Symbol) {
929 bug!("frameworks are not supported on Emscripten")
932 fn gc_sections(&mut self, _keep_metadata: bool) {
936 fn optimize(&mut self) {
937 // Emscripten performs own optimizations
938 self.cmd.arg(match self.sess.opts.optimize {
939 OptLevel::No => "-O0",
940 OptLevel::Less => "-O1",
941 OptLevel::Default => "-O2",
942 OptLevel::Aggressive => "-O3",
943 OptLevel::Size => "-Os",
944 OptLevel::SizeMin => "-Oz",
946 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
947 self.cmd.args(&["--memory-init-file", "0"]);
950 fn pgo_gen(&mut self) {
951 // noop, but maybe we need something like the gnu linker?
954 fn control_flow_guard(&mut self) {}
956 fn debuginfo(&mut self, _strip: Strip) {
957 // Preserve names or generate source maps depending on debug info
958 self.cmd.arg(match self.sess.opts.debuginfo {
959 DebugInfo::None => "-g0",
960 DebugInfo::Limited => "-g3",
961 DebugInfo::Full => "-g4",
965 fn no_crt_objects(&mut self) {}
967 fn no_default_libraries(&mut self) {
968 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
971 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
972 let symbols = &self.info.exports[&crate_type];
974 debug!("EXPORTED SYMBOLS:");
978 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
979 let mut encoded = String::new();
982 let mut encoder = json::Encoder::new(&mut encoded);
983 let res = encoder.emit_seq(symbols.len(), |encoder| {
984 for (i, sym) in symbols.iter().enumerate() {
985 encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
989 if let Err(e) = res {
990 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
993 debug!("{}", encoded);
999 fn subsystem(&mut self, _subsystem: &str) {
1003 fn finalize(&mut self) {}
1005 // Appears not necessary on Emscripten
1006 fn group_start(&mut self) {}
1007 fn group_end(&mut self) {}
1009 fn linker_plugin_lto(&mut self) {
1014 pub struct WasmLd<'a> {
1017 info: &'a LinkerInfo,
1020 impl<'a> WasmLd<'a> {
1021 fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
1022 // If the atomics feature is enabled for wasm then we need a whole bunch
1025 // * `--shared-memory` - the link won't even succeed without this, flags
1026 // the one linear memory as `shared`
1028 // * `--max-memory=1G` - when specifying a shared memory this must also
1029 // be specified. We conservatively choose 1GB but users should be able
1030 // to override this with `-C link-arg`.
1032 // * `--import-memory` - it doesn't make much sense for memory to be
1033 // exported in a threaded module because typically you're
1034 // sharing memory and instantiating the module multiple times. As a
1035 // result if it were exported then we'd just have no sharing.
1037 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
1038 // linker will synthesize this function, and so we need to make sure
1039 // that our usage of `--export` below won't accidentally cause this
1040 // function to get deleted.
1042 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
1043 // symbols are how the TLS segments are initialized and configured.
1044 if sess.target_features.contains(&sym::atomics) {
1045 cmd.arg("--shared-memory");
1046 cmd.arg("--max-memory=1073741824");
1047 cmd.arg("--import-memory");
1048 cmd.arg("--export=__wasm_init_memory");
1049 cmd.arg("--export=__wasm_init_tls");
1050 cmd.arg("--export=__tls_size");
1051 cmd.arg("--export=__tls_align");
1052 cmd.arg("--export=__tls_base");
1054 WasmLd { cmd, sess, info }
1058 impl<'a> Linker for WasmLd<'a> {
1059 fn cmd(&mut self) -> &mut Command {
1063 fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1065 LinkOutputKind::DynamicNoPicExe
1066 | LinkOutputKind::DynamicPicExe
1067 | LinkOutputKind::StaticNoPicExe
1068 | LinkOutputKind::StaticPicExe => {}
1069 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1070 self.cmd.arg("--no-entry");
1075 fn link_dylib(&mut self, lib: Symbol) {
1076 self.cmd.arg("-l").sym_arg(lib);
1079 fn link_staticlib(&mut self, lib: Symbol) {
1080 self.cmd.arg("-l").sym_arg(lib);
1083 fn link_rlib(&mut self, lib: &Path) {
1087 fn include_path(&mut self, path: &Path) {
1088 self.cmd.arg("-L").arg(path);
1091 fn framework_path(&mut self, _path: &Path) {
1092 panic!("frameworks not supported")
1095 fn output_filename(&mut self, path: &Path) {
1096 self.cmd.arg("-o").arg(path);
1099 fn add_object(&mut self, path: &Path) {
1103 fn full_relro(&mut self) {}
1105 fn partial_relro(&mut self) {}
1107 fn no_relro(&mut self) {}
1109 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1110 self.cmd.arg("-l").sym_arg(lib);
1113 fn link_framework(&mut self, _framework: Symbol) {
1114 panic!("frameworks not supported")
1117 fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1118 self.cmd.arg("-l").sym_arg(lib);
1121 fn link_whole_rlib(&mut self, lib: &Path) {
1125 fn gc_sections(&mut self, _keep_metadata: bool) {
1126 self.cmd.arg("--gc-sections");
1129 fn optimize(&mut self) {
1130 self.cmd.arg(match self.sess.opts.optimize {
1131 OptLevel::No => "-O0",
1132 OptLevel::Less => "-O1",
1133 OptLevel::Default => "-O2",
1134 OptLevel::Aggressive => "-O3",
1135 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1137 OptLevel::Size => "-O2",
1138 OptLevel::SizeMin => "-O2",
1142 fn pgo_gen(&mut self) {}
1144 fn debuginfo(&mut self, strip: Strip) {
1147 Strip::Debuginfo => {
1148 self.cmd.arg("--strip-debug");
1151 self.cmd.arg("--strip-all");
1156 fn control_flow_guard(&mut self) {}
1158 fn no_crt_objects(&mut self) {}
1160 fn no_default_libraries(&mut self) {}
1162 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1163 for sym in self.info.exports[&crate_type].iter() {
1164 self.cmd.arg("--export").arg(&sym);
1167 // LLD will hide these otherwise-internal symbols since it only exports
1168 // symbols explicity passed via the `--export` flags above and hides all
1169 // others. Various bits and pieces of tooling use this, so be sure these
1170 // symbols make their way out of the linker as well.
1171 self.cmd.arg("--export=__heap_base");
1172 self.cmd.arg("--export=__data_end");
1175 fn subsystem(&mut self, _subsystem: &str) {}
1177 fn finalize(&mut self) {}
1179 // Not needed for now with LLD
1180 fn group_start(&mut self) {}
1181 fn group_end(&mut self) {}
1183 fn linker_plugin_lto(&mut self) {
1184 // Do nothing for now
1188 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1189 if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1190 return exports.clone();
1193 let mut symbols = Vec::new();
1195 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1196 for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1197 if level.is_below_threshold(export_threshold) {
1198 symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1206 let formats = tcx.dependency_formats(LOCAL_CRATE);
1207 let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1209 for (index, dep_format) in deps.iter().enumerate() {
1210 let cnum = CrateNum::new(index + 1);
1211 // For each dependency that we are linking to statically ...
1212 if *dep_format == Linkage::Static {
1213 // ... we add its symbol list to our export list.
1214 for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1215 if !level.is_below_threshold(export_threshold) {
1219 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1227 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1228 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1229 pub struct PtxLinker<'a> {
1234 impl<'a> Linker for PtxLinker<'a> {
1235 fn cmd(&mut self) -> &mut Command {
1239 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1241 fn link_rlib(&mut self, path: &Path) {
1242 self.cmd.arg("--rlib").arg(path);
1245 fn link_whole_rlib(&mut self, path: &Path) {
1246 self.cmd.arg("--rlib").arg(path);
1249 fn include_path(&mut self, path: &Path) {
1250 self.cmd.arg("-L").arg(path);
1253 fn debuginfo(&mut self, _strip: Strip) {
1254 self.cmd.arg("--debug");
1257 fn add_object(&mut self, path: &Path) {
1258 self.cmd.arg("--bitcode").arg(path);
1261 fn optimize(&mut self) {
1262 match self.sess.lto() {
1263 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1264 self.cmd.arg("-Olto");
1271 fn output_filename(&mut self, path: &Path) {
1272 self.cmd.arg("-o").arg(path);
1275 fn finalize(&mut self) {
1276 // Provide the linker with fallback to internal `target-cpu`.
1277 self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1279 None => &self.sess.target.target.options.cpu,
1283 fn link_dylib(&mut self, _lib: Symbol) {
1284 panic!("external dylibs not supported")
1287 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1288 panic!("external dylibs not supported")
1291 fn link_staticlib(&mut self, _lib: Symbol) {
1292 panic!("staticlibs not supported")
1295 fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1296 panic!("staticlibs not supported")
1299 fn framework_path(&mut self, _path: &Path) {
1300 panic!("frameworks not supported")
1303 fn link_framework(&mut self, _framework: Symbol) {
1304 panic!("frameworks not supported")
1307 fn full_relro(&mut self) {}
1309 fn partial_relro(&mut self) {}
1311 fn no_relro(&mut self) {}
1313 fn gc_sections(&mut self, _keep_metadata: bool) {}
1315 fn pgo_gen(&mut self) {}
1317 fn no_crt_objects(&mut self) {}
1319 fn no_default_libraries(&mut self) {}
1321 fn control_flow_guard(&mut self) {}
1323 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {}
1325 fn subsystem(&mut self, _subsystem: &str) {}
1327 fn group_start(&mut self) {}
1329 fn group_end(&mut self) {}
1331 fn linker_plugin_lto(&mut self) {}