]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/linker.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_codegen_ssa / back / linker.rs
1 use super::archive;
2 use super::command::Command;
3 use super::symbol_export;
4
5 use std::ffi::{OsStr, OsString};
6 use std::fs::{self, File};
7 use std::io::prelude::*;
8 use std::io::{self, BufWriter};
9 use std::path::{Path, PathBuf};
10
11 use rustc::middle::dependency_format::Linkage;
12 use rustc::ty::TyCtxt;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
15 use rustc_serialize::{json, Encoder};
16 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
17 use rustc_session::Session;
18 use rustc_span::symbol::Symbol;
19 use rustc_target::spec::{LinkerFlavor, LldFlavor};
20
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 #[derive(RustcEncodable, RustcDecodable)]
24 pub struct LinkerInfo {
25     exports: FxHashMap<CrateType, Vec<String>>,
26 }
27
28 impl LinkerInfo {
29     pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
30         LinkerInfo {
31             exports: tcx
32                 .sess
33                 .crate_types
34                 .borrow()
35                 .iter()
36                 .map(|&c| (c, exported_symbols(tcx, c)))
37                 .collect(),
38         }
39     }
40
41     pub fn to_linker<'a>(
42         &'a self,
43         cmd: Command,
44         sess: &'a Session,
45         flavor: LinkerFlavor,
46         target_cpu: &'a str,
47     ) -> Box<dyn Linker + 'a> {
48         match flavor {
49             LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
50                 Box::new(MsvcLinker { cmd, sess, info: self }) as Box<dyn Linker>
51             }
52             LinkerFlavor::Em => Box::new(EmLinker { cmd, sess, info: self }) as Box<dyn Linker>,
53             LinkerFlavor::Gcc => Box::new(GccLinker {
54                 cmd,
55                 sess,
56                 info: self,
57                 hinted_static: false,
58                 is_ld: false,
59                 target_cpu,
60             }) as Box<dyn Linker>,
61
62             LinkerFlavor::Lld(LldFlavor::Ld)
63             | LinkerFlavor::Lld(LldFlavor::Ld64)
64             | LinkerFlavor::Ld => Box::new(GccLinker {
65                 cmd,
66                 sess,
67                 info: self,
68                 hinted_static: false,
69                 is_ld: true,
70                 target_cpu,
71             }) as Box<dyn Linker>,
72
73             LinkerFlavor::Lld(LldFlavor::Wasm) => {
74                 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
75             }
76
77             LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
78         }
79     }
80 }
81
82 /// Linker abstraction used by `back::link` to build up the command to invoke a
83 /// linker.
84 ///
85 /// This trait is the total list of requirements needed by `back::link` and
86 /// represents the meaning of each option being passed down. This trait is then
87 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
88 /// MSVC linker (e.g., `link.exe`) is being used.
89 pub trait Linker {
90     fn link_dylib(&mut self, lib: Symbol);
91     fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
92     fn link_framework(&mut self, framework: Symbol);
93     fn link_staticlib(&mut self, lib: Symbol);
94     fn link_rlib(&mut self, lib: &Path);
95     fn link_whole_rlib(&mut self, lib: &Path);
96     fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]);
97     fn include_path(&mut self, path: &Path);
98     fn framework_path(&mut self, path: &Path);
99     fn output_filename(&mut self, path: &Path);
100     fn add_object(&mut self, path: &Path);
101     fn gc_sections(&mut self, keep_metadata: bool);
102     fn position_independent_executable(&mut self);
103     fn no_position_independent_executable(&mut self);
104     fn full_relro(&mut self);
105     fn partial_relro(&mut self);
106     fn no_relro(&mut self);
107     fn optimize(&mut self);
108     fn pgo_gen(&mut self);
109     fn control_flow_guard(&mut self);
110     fn debuginfo(&mut self);
111     fn no_default_libraries(&mut self);
112     fn build_dylib(&mut self, out_filename: &Path);
113     fn build_static_executable(&mut self);
114     fn args(&mut self, args: &[String]);
115     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
116     fn subsystem(&mut self, subsystem: &str);
117     fn group_start(&mut self);
118     fn group_end(&mut self);
119     fn linker_plugin_lto(&mut self);
120     // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
121     fn finalize(&mut self) -> Command;
122 }
123
124 pub struct GccLinker<'a> {
125     cmd: Command,
126     sess: &'a Session,
127     info: &'a LinkerInfo,
128     hinted_static: bool, // Keeps track of the current hinting mode.
129     // Link as ld
130     is_ld: bool,
131     target_cpu: &'a str,
132 }
133
134 impl<'a> GccLinker<'a> {
135     /// Argument that must be passed *directly* to the linker
136     ///
137     /// These arguments need to be prepended with `-Wl`, when a GCC-style linker is used.
138     fn linker_arg<S>(&mut self, arg: S) -> &mut Self
139     where
140         S: AsRef<OsStr>,
141     {
142         if !self.is_ld {
143             let mut os = OsString::from("-Wl,");
144             os.push(arg.as_ref());
145             self.cmd.arg(os);
146         } else {
147             self.cmd.arg(arg);
148         }
149         self
150     }
151
152     fn takes_hints(&self) -> bool {
153         // Really this function only returns true if the underlying linker
154         // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
155         // don't really have a foolproof way to detect that, so rule out some
156         // platforms where currently this is guaranteed to *not* be the case:
157         //
158         // * On OSX they have their own linker, not binutils'
159         // * For WebAssembly the only functional linker is LLD, which doesn't
160         //   support hint flags
161         !self.sess.target.target.options.is_like_osx && self.sess.target.target.arch != "wasm32"
162     }
163
164     // Some platforms take hints about whether a library is static or dynamic.
165     // For those that support this, we ensure we pass the option if the library
166     // was flagged "static" (most defaults are dynamic) to ensure that if
167     // libfoo.a and libfoo.so both exist that the right one is chosen.
168     fn hint_static(&mut self) {
169         if !self.takes_hints() {
170             return;
171         }
172         if !self.hinted_static {
173             self.linker_arg("-Bstatic");
174             self.hinted_static = true;
175         }
176     }
177
178     fn hint_dynamic(&mut self) {
179         if !self.takes_hints() {
180             return;
181         }
182         if self.hinted_static {
183             self.linker_arg("-Bdynamic");
184             self.hinted_static = false;
185         }
186     }
187
188     fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
189         if let Some(plugin_path) = plugin_path {
190             let mut arg = OsString::from("-plugin=");
191             arg.push(plugin_path);
192             self.linker_arg(&arg);
193         }
194
195         let opt_level = match self.sess.opts.optimize {
196             config::OptLevel::No => "O0",
197             config::OptLevel::Less => "O1",
198             config::OptLevel::Default => "O2",
199             config::OptLevel::Aggressive => "O3",
200             config::OptLevel::Size => "Os",
201             config::OptLevel::SizeMin => "Oz",
202         };
203
204         self.linker_arg(&format!("-plugin-opt={}", opt_level));
205         let target_cpu = self.target_cpu;
206         self.linker_arg(&format!("-plugin-opt=mcpu={}", target_cpu));
207     }
208 }
209
210 impl<'a> Linker for GccLinker<'a> {
211     fn link_dylib(&mut self, lib: Symbol) {
212         self.hint_dynamic();
213         self.cmd.arg(format!("-l{}", lib));
214     }
215     fn link_staticlib(&mut self, lib: Symbol) {
216         self.hint_static();
217         self.cmd.arg(format!("-l{}", lib));
218     }
219     fn link_rlib(&mut self, lib: &Path) {
220         self.hint_static();
221         self.cmd.arg(lib);
222     }
223     fn include_path(&mut self, path: &Path) {
224         self.cmd.arg("-L").arg(path);
225     }
226     fn framework_path(&mut self, path: &Path) {
227         self.cmd.arg("-F").arg(path);
228     }
229     fn output_filename(&mut self, path: &Path) {
230         self.cmd.arg("-o").arg(path);
231     }
232     fn add_object(&mut self, path: &Path) {
233         self.cmd.arg(path);
234     }
235     fn position_independent_executable(&mut self) {
236         self.cmd.arg("-pie");
237     }
238     fn no_position_independent_executable(&mut self) {
239         self.cmd.arg("-no-pie");
240     }
241     fn full_relro(&mut self) {
242         self.linker_arg("-zrelro");
243         self.linker_arg("-znow");
244     }
245     fn partial_relro(&mut self) {
246         self.linker_arg("-zrelro");
247     }
248     fn no_relro(&mut self) {
249         self.linker_arg("-znorelro");
250     }
251     fn build_static_executable(&mut self) {
252         self.cmd.arg("-static");
253     }
254     fn args(&mut self, args: &[String]) {
255         self.cmd.args(args);
256     }
257
258     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
259         self.hint_dynamic();
260         self.cmd.arg(format!("-l{}", lib));
261     }
262
263     fn link_framework(&mut self, framework: Symbol) {
264         self.hint_dynamic();
265         self.cmd.arg("-framework").sym_arg(framework);
266     }
267
268     // Here we explicitly ask that the entire archive is included into the
269     // result artifact. For more details see #15460, but the gist is that
270     // the linker will strip away any unused objects in the archive if we
271     // don't otherwise explicitly reference them. This can occur for
272     // libraries which are just providing bindings, libraries with generic
273     // functions, etc.
274     fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
275         self.hint_static();
276         let target = &self.sess.target.target;
277         if !target.options.is_like_osx {
278             self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib));
279             self.linker_arg("--no-whole-archive");
280         } else {
281             // -force_load is the macOS equivalent of --whole-archive, but it
282             // involves passing the full path to the library to link.
283             self.linker_arg("-force_load");
284             let lib = archive::find_library(lib, search_path, &self.sess);
285             self.linker_arg(&lib);
286         }
287     }
288
289     fn link_whole_rlib(&mut self, lib: &Path) {
290         self.hint_static();
291         if self.sess.target.target.options.is_like_osx {
292             self.linker_arg("-force_load");
293             self.linker_arg(&lib);
294         } else {
295             self.linker_arg("--whole-archive").cmd.arg(lib);
296             self.linker_arg("--no-whole-archive");
297         }
298     }
299
300     fn gc_sections(&mut self, keep_metadata: bool) {
301         // The dead_strip option to the linker specifies that functions and data
302         // unreachable by the entry point will be removed. This is quite useful
303         // with Rust's compilation model of compiling libraries at a time into
304         // one object file. For example, this brings hello world from 1.7MB to
305         // 458K.
306         //
307         // Note that this is done for both executables and dynamic libraries. We
308         // won't get much benefit from dylibs because LLVM will have already
309         // stripped away as much as it could. This has not been seen to impact
310         // link times negatively.
311         //
312         // -dead_strip can't be part of the pre_link_args because it's also used
313         // for partial linking when using multiple codegen units (-r).  So we
314         // insert it here.
315         if self.sess.target.target.options.is_like_osx {
316             self.linker_arg("-dead_strip");
317         } else if self.sess.target.target.options.is_like_solaris {
318             self.linker_arg("-zignore");
319
320         // If we're building a dylib, we don't use --gc-sections because LLVM
321         // has already done the best it can do, and we also don't want to
322         // eliminate the metadata. If we're building an executable, however,
323         // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
324         // reduction.
325         } else if !keep_metadata {
326             self.linker_arg("--gc-sections");
327         }
328     }
329
330     fn optimize(&mut self) {
331         if !self.sess.target.target.options.linker_is_gnu {
332             return;
333         }
334
335         // GNU-style linkers support optimization with -O. GNU ld doesn't
336         // need a numeric argument, but other linkers do.
337         if self.sess.opts.optimize == config::OptLevel::Default
338             || self.sess.opts.optimize == config::OptLevel::Aggressive
339         {
340             self.linker_arg("-O1");
341         }
342     }
343
344     fn pgo_gen(&mut self) {
345         if !self.sess.target.target.options.linker_is_gnu {
346             return;
347         }
348
349         // If we're doing PGO generation stuff and on a GNU-like linker, use the
350         // "-u" flag to properly pull in the profiler runtime bits.
351         //
352         // This is because LLVM otherwise won't add the needed initialization
353         // for us on Linux (though the extra flag should be harmless if it
354         // does).
355         //
356         // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
357         //
358         // Though it may be worth to try to revert those changes upstream, since
359         // the overhead of the initialization should be minor.
360         self.cmd.arg("-u");
361         self.cmd.arg("__llvm_profile_runtime");
362     }
363
364     fn control_flow_guard(&mut self) {
365         self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
366     }
367
368     fn debuginfo(&mut self) {
369         if let DebugInfo::None = self.sess.opts.debuginfo {
370             // If we are building without debuginfo enabled and we were called with
371             // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
372             // found when linking to get rid of symbols from libstd.
373             if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
374                 self.linker_arg("-S");
375             }
376         };
377     }
378
379     fn no_default_libraries(&mut self) {
380         if !self.is_ld {
381             self.cmd.arg("-nodefaultlibs");
382         }
383     }
384
385     fn build_dylib(&mut self, out_filename: &Path) {
386         // On mac we need to tell the linker to let this library be rpathed
387         if self.sess.target.target.options.is_like_osx {
388             self.cmd.arg("-dynamiclib");
389             self.linker_arg("-dylib");
390
391             // Note that the `osx_rpath_install_name` option here is a hack
392             // purely to support rustbuild right now, we should get a more
393             // principled solution at some point to force the compiler to pass
394             // the right `-Wl,-install_name` with an `@rpath` in it.
395             if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
396                 self.linker_arg("-install_name");
397                 let mut v = OsString::from("@rpath/");
398                 v.push(out_filename.file_name().unwrap());
399                 self.linker_arg(&v);
400             }
401         } else {
402             self.cmd.arg("-shared");
403             if self.sess.target.target.options.is_like_windows {
404                 // The output filename already contains `dll_suffix` so
405                 // the resulting import library will have a name in the
406                 // form of libfoo.dll.a
407                 let implib_name =
408                     out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
409                         format!(
410                             "{}{}{}",
411                             self.sess.target.target.options.staticlib_prefix,
412                             file,
413                             self.sess.target.target.options.staticlib_suffix
414                         )
415                     });
416                 if let Some(implib_name) = implib_name {
417                     let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
418                     if let Some(implib) = implib {
419                         self.linker_arg(&format!("--out-implib,{}", (*implib).to_str().unwrap()));
420                     }
421                 }
422             }
423         }
424     }
425
426     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
427         // Symbol visibility in object files typically takes care of this.
428         if crate_type == CrateType::Executable
429             && self.sess.target.target.options.override_export_symbols.is_none()
430         {
431             return;
432         }
433
434         // We manually create a list of exported symbols to ensure we don't expose any more.
435         // The object files have far more public symbols than we actually want to export,
436         // so we hide them all here.
437
438         if !self.sess.target.target.options.limit_rdylib_exports {
439             return;
440         }
441
442         if crate_type == CrateType::ProcMacro {
443             return;
444         }
445
446         let mut arg = OsString::new();
447         let path = tmpdir.join("list");
448
449         debug!("EXPORTED SYMBOLS:");
450
451         if self.sess.target.target.options.is_like_osx {
452             // Write a plain, newline-separated list of symbols
453             let res: io::Result<()> = try {
454                 let mut f = BufWriter::new(File::create(&path)?);
455                 for sym in self.info.exports[&crate_type].iter() {
456                     debug!("  _{}", sym);
457                     writeln!(f, "_{}", sym)?;
458                 }
459             };
460             if let Err(e) = res {
461                 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
462             }
463         } else {
464             // Write an LD version script
465             let res: io::Result<()> = try {
466                 let mut f = BufWriter::new(File::create(&path)?);
467                 writeln!(f, "{{")?;
468                 if !self.info.exports[&crate_type].is_empty() {
469                     writeln!(f, "  global:")?;
470                     for sym in self.info.exports[&crate_type].iter() {
471                         debug!("    {};", sym);
472                         writeln!(f, "    {};", sym)?;
473                     }
474                 }
475                 writeln!(f, "\n  local:\n    *;\n}};")?;
476             };
477             if let Err(e) = res {
478                 self.sess.fatal(&format!("failed to write version script: {}", e));
479             }
480         }
481
482         if self.sess.target.target.options.is_like_osx {
483             if !self.is_ld {
484                 arg.push("-Wl,")
485             }
486             arg.push("-exported_symbols_list,");
487         } else if self.sess.target.target.options.is_like_solaris {
488             if !self.is_ld {
489                 arg.push("-Wl,")
490             }
491             arg.push("-M,");
492         } else {
493             if !self.is_ld {
494                 arg.push("-Wl,")
495             }
496             arg.push("--version-script=");
497         }
498
499         arg.push(&path);
500         self.cmd.arg(arg);
501     }
502
503     fn subsystem(&mut self, subsystem: &str) {
504         self.linker_arg("--subsystem");
505         self.linker_arg(&subsystem);
506     }
507
508     fn finalize(&mut self) -> Command {
509         self.hint_dynamic(); // Reset to default before returning the composed command line.
510
511         ::std::mem::replace(&mut self.cmd, Command::new(""))
512     }
513
514     fn group_start(&mut self) {
515         if self.takes_hints() {
516             self.linker_arg("--start-group");
517         }
518     }
519
520     fn group_end(&mut self) {
521         if self.takes_hints() {
522             self.linker_arg("--end-group");
523         }
524     }
525
526     fn linker_plugin_lto(&mut self) {
527         match self.sess.opts.cg.linker_plugin_lto {
528             LinkerPluginLto::Disabled => {
529                 // Nothing to do
530             }
531             LinkerPluginLto::LinkerPluginAuto => {
532                 self.push_linker_plugin_lto_args(None);
533             }
534             LinkerPluginLto::LinkerPlugin(ref path) => {
535                 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
536             }
537         }
538     }
539 }
540
541 pub struct MsvcLinker<'a> {
542     cmd: Command,
543     sess: &'a Session,
544     info: &'a LinkerInfo,
545 }
546
547 impl<'a> Linker for MsvcLinker<'a> {
548     fn link_rlib(&mut self, lib: &Path) {
549         self.cmd.arg(lib);
550     }
551     fn add_object(&mut self, path: &Path) {
552         self.cmd.arg(path);
553     }
554     fn args(&mut self, args: &[String]) {
555         self.cmd.args(args);
556     }
557
558     fn build_dylib(&mut self, out_filename: &Path) {
559         self.cmd.arg("/DLL");
560         let mut arg: OsString = "/IMPLIB:".into();
561         arg.push(out_filename.with_extension("dll.lib"));
562         self.cmd.arg(arg);
563     }
564
565     fn build_static_executable(&mut self) {
566         // noop
567     }
568
569     fn gc_sections(&mut self, _keep_metadata: bool) {
570         // MSVC's ICF (Identical COMDAT Folding) link optimization is
571         // slow for Rust and thus we disable it by default when not in
572         // optimization build.
573         if self.sess.opts.optimize != config::OptLevel::No {
574             self.cmd.arg("/OPT:REF,ICF");
575         } else {
576             // It is necessary to specify NOICF here, because /OPT:REF
577             // implies ICF by default.
578             self.cmd.arg("/OPT:REF,NOICF");
579         }
580     }
581
582     fn link_dylib(&mut self, lib: Symbol) {
583         self.cmd.arg(&format!("{}.lib", lib));
584     }
585
586     fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
587         // When producing a dll, the MSVC linker may not actually emit a
588         // `foo.lib` file if the dll doesn't actually export any symbols, so we
589         // check to see if the file is there and just omit linking to it if it's
590         // not present.
591         let name = format!("{}.dll.lib", lib);
592         if fs::metadata(&path.join(&name)).is_ok() {
593             self.cmd.arg(name);
594         }
595     }
596
597     fn link_staticlib(&mut self, lib: Symbol) {
598         self.cmd.arg(&format!("{}.lib", lib));
599     }
600
601     fn position_independent_executable(&mut self) {
602         // noop
603     }
604
605     fn no_position_independent_executable(&mut self) {
606         // noop
607     }
608
609     fn full_relro(&mut self) {
610         // noop
611     }
612
613     fn partial_relro(&mut self) {
614         // noop
615     }
616
617     fn no_relro(&mut self) {
618         // noop
619     }
620
621     fn no_default_libraries(&mut self) {
622         // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
623         // as there's been trouble in the past of linking the C++ standard
624         // library required by LLVM. This likely needs to happen one day, but
625         // in general Windows is also a more controlled environment than
626         // Unix, so it's not necessarily as critical that this be implemented.
627         //
628         // Note that there are also some licensing worries about statically
629         // linking some libraries which require a specific agreement, so it may
630         // not ever be possible for us to pass this flag.
631     }
632
633     fn include_path(&mut self, path: &Path) {
634         let mut arg = OsString::from("/LIBPATH:");
635         arg.push(path);
636         self.cmd.arg(&arg);
637     }
638
639     fn output_filename(&mut self, path: &Path) {
640         let mut arg = OsString::from("/OUT:");
641         arg.push(path);
642         self.cmd.arg(&arg);
643     }
644
645     fn framework_path(&mut self, _path: &Path) {
646         bug!("frameworks are not supported on windows")
647     }
648     fn link_framework(&mut self, _framework: Symbol) {
649         bug!("frameworks are not supported on windows")
650     }
651
652     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
653         // not supported?
654         self.link_staticlib(lib);
655     }
656     fn link_whole_rlib(&mut self, path: &Path) {
657         // not supported?
658         self.link_rlib(path);
659     }
660     fn optimize(&mut self) {
661         // Needs more investigation of `/OPT` arguments
662     }
663
664     fn pgo_gen(&mut self) {
665         // Nothing needed here.
666     }
667
668     fn control_flow_guard(&mut self) {
669         self.cmd.arg("/guard:cf");
670     }
671
672     fn debuginfo(&mut self) {
673         // This will cause the Microsoft linker to generate a PDB file
674         // from the CodeView line tables in the object files.
675         self.cmd.arg("/DEBUG");
676
677         // This will cause the Microsoft linker to embed .natvis info into the PDB file
678         let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
679         if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
680             for entry in natvis_dir {
681                 match entry {
682                     Ok(entry) => {
683                         let path = entry.path();
684                         if path.extension() == Some("natvis".as_ref()) {
685                             let mut arg = OsString::from("/NATVIS:");
686                             arg.push(path);
687                             self.cmd.arg(arg);
688                         }
689                     }
690                     Err(err) => {
691                         self.sess.warn(&format!("error enumerating natvis directory: {}", err));
692                     }
693                 }
694             }
695         }
696     }
697
698     // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
699     // export symbols from a dynamic library. When building a dynamic library,
700     // however, we're going to want some symbols exported, so this function
701     // generates a DEF file which lists all the symbols.
702     //
703     // The linker will read this `*.def` file and export all the symbols from
704     // the dynamic library. Note that this is not as simple as just exporting
705     // all the symbols in the current crate (as specified by `codegen.reachable`)
706     // but rather we also need to possibly export the symbols of upstream
707     // crates. Upstream rlibs may be linked statically to this dynamic library,
708     // in which case they may continue to transitively be used and hence need
709     // their symbols exported.
710     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
711         // Symbol visibility takes care of this typically
712         if crate_type == CrateType::Executable {
713             return;
714         }
715
716         let path = tmpdir.join("lib.def");
717         let res: io::Result<()> = try {
718             let mut f = BufWriter::new(File::create(&path)?);
719
720             // Start off with the standard module name header and then go
721             // straight to exports.
722             writeln!(f, "LIBRARY")?;
723             writeln!(f, "EXPORTS")?;
724             for symbol in self.info.exports[&crate_type].iter() {
725                 debug!("  _{}", symbol);
726                 writeln!(f, "  {}", symbol)?;
727             }
728         };
729         if let Err(e) = res {
730             self.sess.fatal(&format!("failed to write lib.def file: {}", e));
731         }
732         let mut arg = OsString::from("/DEF:");
733         arg.push(path);
734         self.cmd.arg(&arg);
735     }
736
737     fn subsystem(&mut self, subsystem: &str) {
738         // Note that previous passes of the compiler validated this subsystem,
739         // so we just blindly pass it to the linker.
740         self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
741
742         // Windows has two subsystems we're interested in right now, the console
743         // and windows subsystems. These both implicitly have different entry
744         // points (starting symbols). The console entry point starts with
745         // `mainCRTStartup` and the windows entry point starts with
746         // `WinMainCRTStartup`. These entry points, defined in system libraries,
747         // will then later probe for either `main` or `WinMain`, respectively to
748         // start the application.
749         //
750         // In Rust we just always generate a `main` function so we want control
751         // to always start there, so we force the entry point on the windows
752         // subsystem to be `mainCRTStartup` to get everything booted up
753         // correctly.
754         //
755         // For more information see RFC #1665
756         if subsystem == "windows" {
757             self.cmd.arg("/ENTRY:mainCRTStartup");
758         }
759     }
760
761     fn finalize(&mut self) -> Command {
762         ::std::mem::replace(&mut self.cmd, Command::new(""))
763     }
764
765     // MSVC doesn't need group indicators
766     fn group_start(&mut self) {}
767     fn group_end(&mut self) {}
768
769     fn linker_plugin_lto(&mut self) {
770         // Do nothing
771     }
772 }
773
774 pub struct EmLinker<'a> {
775     cmd: Command,
776     sess: &'a Session,
777     info: &'a LinkerInfo,
778 }
779
780 impl<'a> Linker for EmLinker<'a> {
781     fn include_path(&mut self, path: &Path) {
782         self.cmd.arg("-L").arg(path);
783     }
784
785     fn link_staticlib(&mut self, lib: Symbol) {
786         self.cmd.arg("-l").sym_arg(lib);
787     }
788
789     fn output_filename(&mut self, path: &Path) {
790         self.cmd.arg("-o").arg(path);
791     }
792
793     fn add_object(&mut self, path: &Path) {
794         self.cmd.arg(path);
795     }
796
797     fn link_dylib(&mut self, lib: Symbol) {
798         // Emscripten always links statically
799         self.link_staticlib(lib);
800     }
801
802     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
803         // not supported?
804         self.link_staticlib(lib);
805     }
806
807     fn link_whole_rlib(&mut self, lib: &Path) {
808         // not supported?
809         self.link_rlib(lib);
810     }
811
812     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
813         self.link_dylib(lib);
814     }
815
816     fn link_rlib(&mut self, lib: &Path) {
817         self.add_object(lib);
818     }
819
820     fn position_independent_executable(&mut self) {
821         // noop
822     }
823
824     fn no_position_independent_executable(&mut self) {
825         // noop
826     }
827
828     fn full_relro(&mut self) {
829         // noop
830     }
831
832     fn partial_relro(&mut self) {
833         // noop
834     }
835
836     fn no_relro(&mut self) {
837         // noop
838     }
839
840     fn args(&mut self, args: &[String]) {
841         self.cmd.args(args);
842     }
843
844     fn framework_path(&mut self, _path: &Path) {
845         bug!("frameworks are not supported on Emscripten")
846     }
847
848     fn link_framework(&mut self, _framework: Symbol) {
849         bug!("frameworks are not supported on Emscripten")
850     }
851
852     fn gc_sections(&mut self, _keep_metadata: bool) {
853         // noop
854     }
855
856     fn optimize(&mut self) {
857         // Emscripten performs own optimizations
858         self.cmd.arg(match self.sess.opts.optimize {
859             OptLevel::No => "-O0",
860             OptLevel::Less => "-O1",
861             OptLevel::Default => "-O2",
862             OptLevel::Aggressive => "-O3",
863             OptLevel::Size => "-Os",
864             OptLevel::SizeMin => "-Oz",
865         });
866         // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
867         self.cmd.args(&["--memory-init-file", "0"]);
868     }
869
870     fn pgo_gen(&mut self) {
871         // noop, but maybe we need something like the gnu linker?
872     }
873
874     fn control_flow_guard(&mut self) {
875         self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
876     }
877
878     fn debuginfo(&mut self) {
879         // Preserve names or generate source maps depending on debug info
880         self.cmd.arg(match self.sess.opts.debuginfo {
881             DebugInfo::None => "-g0",
882             DebugInfo::Limited => "-g3",
883             DebugInfo::Full => "-g4",
884         });
885     }
886
887     fn no_default_libraries(&mut self) {
888         self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
889     }
890
891     fn build_dylib(&mut self, _out_filename: &Path) {
892         bug!("building dynamic library is unsupported on Emscripten")
893     }
894
895     fn build_static_executable(&mut self) {
896         // noop
897     }
898
899     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
900         let symbols = &self.info.exports[&crate_type];
901
902         debug!("EXPORTED SYMBOLS:");
903
904         self.cmd.arg("-s");
905
906         let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
907         let mut encoded = String::new();
908
909         {
910             let mut encoder = json::Encoder::new(&mut encoded);
911             let res = encoder.emit_seq(symbols.len(), |encoder| {
912                 for (i, sym) in symbols.iter().enumerate() {
913                     encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
914                 }
915                 Ok(())
916             });
917             if let Err(e) = res {
918                 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
919             }
920         }
921         debug!("{}", encoded);
922         arg.push(encoded);
923
924         self.cmd.arg(arg);
925     }
926
927     fn subsystem(&mut self, _subsystem: &str) {
928         // noop
929     }
930
931     fn finalize(&mut self) -> Command {
932         ::std::mem::replace(&mut self.cmd, Command::new(""))
933     }
934
935     // Appears not necessary on Emscripten
936     fn group_start(&mut self) {}
937     fn group_end(&mut self) {}
938
939     fn linker_plugin_lto(&mut self) {
940         // Do nothing
941     }
942 }
943
944 pub struct WasmLd<'a> {
945     cmd: Command,
946     sess: &'a Session,
947     info: &'a LinkerInfo,
948 }
949
950 impl<'a> WasmLd<'a> {
951     fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
952         // If the atomics feature is enabled for wasm then we need a whole bunch
953         // of flags:
954         //
955         // * `--shared-memory` - the link won't even succeed without this, flags
956         //   the one linear memory as `shared`
957         //
958         // * `--max-memory=1G` - when specifying a shared memory this must also
959         //   be specified. We conservatively choose 1GB but users should be able
960         //   to override this with `-C link-arg`.
961         //
962         // * `--import-memory` - it doesn't make much sense for memory to be
963         //   exported in a threaded module because typically you're
964         //   sharing memory and instantiating the module multiple times. As a
965         //   result if it were exported then we'd just have no sharing.
966         //
967         // * `--passive-segments` - all memory segments should be passive to
968         //   prevent each module instantiation from reinitializing memory.
969         //
970         // * `--export=__wasm_init_memory` - when using `--passive-segments` the
971         //   linker will synthesize this function, and so we need to make sure
972         //   that our usage of `--export` below won't accidentally cause this
973         //   function to get deleted.
974         //
975         // * `--export=*tls*` - when `#[thread_local]` symbols are used these
976         //   symbols are how the TLS segments are initialized and configured.
977         let atomics = sess.opts.cg.target_feature.contains("+atomics")
978             || sess.target.target.options.features.contains("+atomics");
979         if atomics {
980             cmd.arg("--shared-memory");
981             cmd.arg("--max-memory=1073741824");
982             cmd.arg("--import-memory");
983             cmd.arg("--passive-segments");
984             cmd.arg("--export=__wasm_init_memory");
985             cmd.arg("--export=__wasm_init_tls");
986             cmd.arg("--export=__tls_size");
987             cmd.arg("--export=__tls_align");
988             cmd.arg("--export=__tls_base");
989         }
990         WasmLd { cmd, sess, info }
991     }
992 }
993
994 impl<'a> Linker for WasmLd<'a> {
995     fn link_dylib(&mut self, lib: Symbol) {
996         self.cmd.arg("-l").sym_arg(lib);
997     }
998
999     fn link_staticlib(&mut self, lib: Symbol) {
1000         self.cmd.arg("-l").sym_arg(lib);
1001     }
1002
1003     fn link_rlib(&mut self, lib: &Path) {
1004         self.cmd.arg(lib);
1005     }
1006
1007     fn include_path(&mut self, path: &Path) {
1008         self.cmd.arg("-L").arg(path);
1009     }
1010
1011     fn framework_path(&mut self, _path: &Path) {
1012         panic!("frameworks not supported")
1013     }
1014
1015     fn output_filename(&mut self, path: &Path) {
1016         self.cmd.arg("-o").arg(path);
1017     }
1018
1019     fn add_object(&mut self, path: &Path) {
1020         self.cmd.arg(path);
1021     }
1022
1023     fn position_independent_executable(&mut self) {}
1024
1025     fn full_relro(&mut self) {}
1026
1027     fn partial_relro(&mut self) {}
1028
1029     fn no_relro(&mut self) {}
1030
1031     fn build_static_executable(&mut self) {}
1032
1033     fn args(&mut self, args: &[String]) {
1034         self.cmd.args(args);
1035     }
1036
1037     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1038         self.cmd.arg("-l").sym_arg(lib);
1039     }
1040
1041     fn link_framework(&mut self, _framework: Symbol) {
1042         panic!("frameworks not supported")
1043     }
1044
1045     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1046         self.cmd.arg("-l").sym_arg(lib);
1047     }
1048
1049     fn link_whole_rlib(&mut self, lib: &Path) {
1050         self.cmd.arg(lib);
1051     }
1052
1053     fn gc_sections(&mut self, _keep_metadata: bool) {
1054         self.cmd.arg("--gc-sections");
1055     }
1056
1057     fn optimize(&mut self) {
1058         self.cmd.arg(match self.sess.opts.optimize {
1059             OptLevel::No => "-O0",
1060             OptLevel::Less => "-O1",
1061             OptLevel::Default => "-O2",
1062             OptLevel::Aggressive => "-O3",
1063             // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1064             // instead.
1065             OptLevel::Size => "-O2",
1066             OptLevel::SizeMin => "-O2",
1067         });
1068     }
1069
1070     fn pgo_gen(&mut self) {}
1071
1072     fn debuginfo(&mut self) {}
1073
1074     fn control_flow_guard(&mut self) {
1075         self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
1076     }
1077
1078     fn no_default_libraries(&mut self) {}
1079
1080     fn build_dylib(&mut self, _out_filename: &Path) {
1081         self.cmd.arg("--no-entry");
1082     }
1083
1084     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1085         for sym in self.info.exports[&crate_type].iter() {
1086             self.cmd.arg("--export").arg(&sym);
1087         }
1088
1089         // LLD will hide these otherwise-internal symbols since our `--export`
1090         // list above is a whitelist of what to export. Various bits and pieces
1091         // of tooling use this, so be sure these symbols make their way out of
1092         // the linker as well.
1093         self.cmd.arg("--export=__heap_base");
1094         self.cmd.arg("--export=__data_end");
1095     }
1096
1097     fn subsystem(&mut self, _subsystem: &str) {}
1098
1099     fn no_position_independent_executable(&mut self) {}
1100
1101     fn finalize(&mut self) -> Command {
1102         ::std::mem::replace(&mut self.cmd, Command::new(""))
1103     }
1104
1105     // Not needed for now with LLD
1106     fn group_start(&mut self) {}
1107     fn group_end(&mut self) {}
1108
1109     fn linker_plugin_lto(&mut self) {
1110         // Do nothing for now
1111     }
1112 }
1113
1114 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1115     if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1116         return exports.clone();
1117     }
1118
1119     let mut symbols = Vec::new();
1120
1121     let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1122     for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1123         if level.is_below_threshold(export_threshold) {
1124             symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1125                 tcx,
1126                 symbol,
1127                 LOCAL_CRATE,
1128             ));
1129         }
1130     }
1131
1132     let formats = tcx.dependency_formats(LOCAL_CRATE);
1133     let deps = formats
1134         .iter()
1135         .filter_map(|(t, list)| if *t == crate_type { Some(list) } else { None })
1136         .next()
1137         .unwrap();
1138
1139     for (index, dep_format) in deps.iter().enumerate() {
1140         let cnum = CrateNum::new(index + 1);
1141         // For each dependency that we are linking to statically ...
1142         if *dep_format == Linkage::Static {
1143             // ... we add its symbol list to our export list.
1144             for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1145                 if !level.is_below_threshold(export_threshold) {
1146                     continue;
1147                 }
1148
1149                 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1150             }
1151         }
1152     }
1153
1154     symbols
1155 }
1156
1157 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1158 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1159 pub struct PtxLinker<'a> {
1160     cmd: Command,
1161     sess: &'a Session,
1162 }
1163
1164 impl<'a> Linker for PtxLinker<'a> {
1165     fn link_rlib(&mut self, path: &Path) {
1166         self.cmd.arg("--rlib").arg(path);
1167     }
1168
1169     fn link_whole_rlib(&mut self, path: &Path) {
1170         self.cmd.arg("--rlib").arg(path);
1171     }
1172
1173     fn include_path(&mut self, path: &Path) {
1174         self.cmd.arg("-L").arg(path);
1175     }
1176
1177     fn debuginfo(&mut self) {
1178         self.cmd.arg("--debug");
1179     }
1180
1181     fn add_object(&mut self, path: &Path) {
1182         self.cmd.arg("--bitcode").arg(path);
1183     }
1184
1185     fn args(&mut self, args: &[String]) {
1186         self.cmd.args(args);
1187     }
1188
1189     fn optimize(&mut self) {
1190         match self.sess.lto() {
1191             Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1192                 self.cmd.arg("-Olto");
1193             }
1194
1195             Lto::No => {}
1196         };
1197     }
1198
1199     fn output_filename(&mut self, path: &Path) {
1200         self.cmd.arg("-o").arg(path);
1201     }
1202
1203     fn finalize(&mut self) -> Command {
1204         // Provide the linker with fallback to internal `target-cpu`.
1205         self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1206             Some(ref s) => s,
1207             None => &self.sess.target.target.options.cpu,
1208         });
1209
1210         ::std::mem::replace(&mut self.cmd, Command::new(""))
1211     }
1212
1213     fn link_dylib(&mut self, _lib: Symbol) {
1214         panic!("external dylibs not supported")
1215     }
1216
1217     fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1218         panic!("external dylibs not supported")
1219     }
1220
1221     fn link_staticlib(&mut self, _lib: Symbol) {
1222         panic!("staticlibs not supported")
1223     }
1224
1225     fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1226         panic!("staticlibs not supported")
1227     }
1228
1229     fn framework_path(&mut self, _path: &Path) {
1230         panic!("frameworks not supported")
1231     }
1232
1233     fn link_framework(&mut self, _framework: Symbol) {
1234         panic!("frameworks not supported")
1235     }
1236
1237     fn position_independent_executable(&mut self) {}
1238
1239     fn full_relro(&mut self) {}
1240
1241     fn partial_relro(&mut self) {}
1242
1243     fn no_relro(&mut self) {}
1244
1245     fn build_static_executable(&mut self) {}
1246
1247     fn gc_sections(&mut self, _keep_metadata: bool) {}
1248
1249     fn pgo_gen(&mut self) {}
1250
1251     fn no_default_libraries(&mut self) {}
1252
1253     fn control_flow_guard(&mut self) {
1254         self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
1255     }
1256
1257     fn build_dylib(&mut self, _out_filename: &Path) {}
1258
1259     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {}
1260
1261     fn subsystem(&mut self, _subsystem: &str) {}
1262
1263     fn no_position_independent_executable(&mut self) {}
1264
1265     fn group_start(&mut self) {}
1266
1267     fn group_end(&mut self) {}
1268
1269     fn linker_plugin_lto(&mut self) {}
1270 }