]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/linker.rs
Auto merge of #74404 - lcnr:ty-dep-path-cleanup-aaaaa, r=eddyb
[rust.git] / src / librustc_codegen_ssa / back / linker.rs
1 use super::archive;
2 use super::command::Command;
3 use super::symbol_export;
4 use rustc_span::symbol::sym;
5
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::mem;
11 use std::path::{Path, PathBuf};
12
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};
22
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");
32     // MSVC's `link.exe`.
33     linker.env("VSLANG", "1033");
34 }
35
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>>,
41 }
42
43 impl LinkerInfo {
44     pub fn new(tcx: TyCtxt<'_>) -> LinkerInfo {
45         LinkerInfo {
46             exports: tcx
47                 .sess
48                 .crate_types()
49                 .iter()
50                 .map(|&c| (c, exported_symbols(tcx, c)))
51                 .collect(),
52         }
53     }
54
55     pub fn to_linker<'a>(
56         &'a self,
57         cmd: Command,
58         sess: &'a Session,
59         flavor: LinkerFlavor,
60         target_cpu: &'a str,
61     ) -> Box<dyn Linker + 'a> {
62         match flavor {
63             LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
64                 Box::new(MsvcLinker { cmd, sess, info: self }) as Box<dyn Linker>
65             }
66             LinkerFlavor::Em => Box::new(EmLinker { cmd, sess, info: self }) as Box<dyn Linker>,
67             LinkerFlavor::Gcc => Box::new(GccLinker {
68                 cmd,
69                 sess,
70                 info: self,
71                 hinted_static: false,
72                 is_ld: false,
73                 target_cpu,
74             }) as Box<dyn Linker>,
75
76             LinkerFlavor::Lld(LldFlavor::Ld)
77             | LinkerFlavor::Lld(LldFlavor::Ld64)
78             | LinkerFlavor::Ld => Box::new(GccLinker {
79                 cmd,
80                 sess,
81                 info: self,
82                 hinted_static: false,
83                 is_ld: true,
84                 target_cpu,
85             }) as Box<dyn Linker>,
86
87             LinkerFlavor::Lld(LldFlavor::Wasm) => {
88                 Box::new(WasmLd::new(cmd, sess, self)) as Box<dyn Linker>
89             }
90
91             LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
92         }
93     }
94 }
95
96 /// Linker abstraction used by `back::link` to build up the command to invoke a
97 /// linker.
98 ///
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.
103 pub trait Linker {
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);
134 }
135
136 impl dyn Linker + '_ {
137     pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
138         self.cmd().arg(arg);
139     }
140
141     pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
142         self.cmd().args(args);
143     }
144
145     pub fn take_cmd(&mut self) -> Command {
146         mem::replace(self.cmd(), Command::new(""))
147     }
148 }
149
150 pub struct GccLinker<'a> {
151     cmd: Command,
152     sess: &'a Session,
153     info: &'a LinkerInfo,
154     hinted_static: bool, // Keeps track of the current hinting mode.
155     // Link as ld
156     is_ld: bool,
157     target_cpu: &'a str,
158 }
159
160 impl<'a> GccLinker<'a> {
161     /// Argument that must be passed *directly* to the linker
162     ///
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
165     where
166         S: AsRef<OsStr>,
167     {
168         if !self.is_ld {
169             let mut os = OsString::from("-Wl,");
170             os.push(arg.as_ref());
171             self.cmd.arg(os);
172         } else {
173             self.cmd.arg(arg);
174         }
175         self
176     }
177
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:
183         //
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"
188     }
189
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() {
196             return;
197         }
198         if !self.hinted_static {
199             self.linker_arg("-Bstatic");
200             self.hinted_static = true;
201         }
202     }
203
204     fn hint_dynamic(&mut self) {
205         if !self.takes_hints() {
206             return;
207         }
208         if self.hinted_static {
209             self.linker_arg("-Bdynamic");
210             self.hinted_static = false;
211         }
212     }
213
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);
219         }
220
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",
228         };
229
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));
233     }
234
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");
240
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());
249                 self.linker_arg(&v);
250             }
251         } else {
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
257                 let implib_name =
258                     out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
259                         format!(
260                             "{}{}{}",
261                             self.sess.target.target.options.staticlib_prefix,
262                             file,
263                             self.sess.target.target.options.staticlib_suffix
264                         )
265                     });
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()));
270                     }
271                 }
272             }
273         }
274     }
275 }
276
277 impl<'a> Linker for GccLinker<'a> {
278     fn cmd(&mut self) -> &mut Command {
279         &mut self.cmd
280     }
281
282     fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
283         match output_kind {
284             LinkOutputKind::DynamicNoPicExe => {
285                 if !self.is_ld && self.sess.target.target.options.linker_is_gnu {
286                     self.cmd.arg("-no-pie");
287                 }
288             }
289             LinkOutputKind::DynamicPicExe => {
290                 // `-pie` works for both gcc wrapper and ld.
291                 self.cmd.arg("-pie");
292             }
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");
298                 }
299             }
300             LinkOutputKind::StaticPicExe => {
301                 if !self.is_ld {
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");
305                 } else {
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"]);
312                 }
313             }
314             LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
315             LinkOutputKind::StaticDylib => {
316                 self.cmd.arg("-static");
317                 self.build_dylib(out_filename);
318             }
319         }
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"
326             && matches!(
327                 output_kind,
328                 LinkOutputKind::StaticNoPicExe
329                     | LinkOutputKind::StaticPicExe
330                     | LinkOutputKind::StaticDylib
331             )
332         {
333             self.cmd.arg("--static-crt");
334         }
335     }
336
337     fn link_dylib(&mut self, lib: Symbol) {
338         self.hint_dynamic();
339         self.cmd.arg(format!("-l{}", lib));
340     }
341     fn link_staticlib(&mut self, lib: Symbol) {
342         self.hint_static();
343         self.cmd.arg(format!("-l{}", lib));
344     }
345     fn link_rlib(&mut self, lib: &Path) {
346         self.hint_static();
347         self.cmd.arg(lib);
348     }
349     fn include_path(&mut self, path: &Path) {
350         self.cmd.arg("-L").arg(path);
351     }
352     fn framework_path(&mut self, path: &Path) {
353         self.cmd.arg("-F").arg(path);
354     }
355     fn output_filename(&mut self, path: &Path) {
356         self.cmd.arg("-o").arg(path);
357     }
358     fn add_object(&mut self, path: &Path) {
359         self.cmd.arg(path);
360     }
361     fn full_relro(&mut self) {
362         self.linker_arg("-zrelro");
363         self.linker_arg("-znow");
364     }
365     fn partial_relro(&mut self) {
366         self.linker_arg("-zrelro");
367     }
368     fn no_relro(&mut self) {
369         self.linker_arg("-znorelro");
370     }
371
372     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
373         self.hint_dynamic();
374         self.cmd.arg(format!("-l{}", lib));
375     }
376
377     fn link_framework(&mut self, framework: Symbol) {
378         self.hint_dynamic();
379         self.cmd.arg("-framework").sym_arg(framework);
380     }
381
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
387     // functions, etc.
388     fn link_whole_staticlib(&mut self, lib: Symbol, search_path: &[PathBuf]) {
389         self.hint_static();
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");
394         } else {
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);
400         }
401     }
402
403     fn link_whole_rlib(&mut self, lib: &Path) {
404         self.hint_static();
405         if self.sess.target.target.options.is_like_osx {
406             self.linker_arg("-force_load");
407             self.linker_arg(&lib);
408         } else {
409             self.linker_arg("--whole-archive").cmd.arg(lib);
410             self.linker_arg("--no-whole-archive");
411         }
412     }
413
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
419         // 458K.
420         //
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.
425         //
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
428         // insert it here.
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");
433
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%
438         // reduction.
439         } else if !keep_metadata {
440             self.linker_arg("--gc-sections");
441         }
442     }
443
444     fn optimize(&mut self) {
445         if !self.sess.target.target.options.linker_is_gnu {
446             return;
447         }
448
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
453         {
454             self.linker_arg("-O1");
455         }
456     }
457
458     fn pgo_gen(&mut self) {
459         if !self.sess.target.target.options.linker_is_gnu {
460             return;
461         }
462
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.
465         //
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
468         // does).
469         //
470         // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
471         //
472         // Though it may be worth to try to revert those changes upstream, since
473         // the overhead of the initialization should be minor.
474         self.cmd.arg("-u");
475         self.cmd.arg("__llvm_profile_runtime");
476     }
477
478     fn control_flow_guard(&mut self) {}
479
480     fn debuginfo(&mut self, strip: Strip) {
481         match strip {
482             Strip::None => {}
483             Strip::Debuginfo => {
484                 // MacOS linker does not support longhand argument --strip-debug
485                 self.linker_arg("-S");
486             }
487             Strip::Symbols => {
488                 // MacOS linker does not support longhand argument --strip-all
489                 self.linker_arg("-s");
490             }
491         }
492     }
493
494     fn no_crt_objects(&mut self) {
495         if !self.is_ld {
496             self.cmd.arg("-nostartfiles");
497         }
498     }
499
500     fn no_default_libraries(&mut self) {
501         if !self.is_ld {
502             self.cmd.arg("-nodefaultlibs");
503         }
504     }
505
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()
510         {
511             return;
512         }
513
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.
517
518         if !self.sess.target.target.options.limit_rdylib_exports {
519             return;
520         }
521
522         if crate_type == CrateType::ProcMacro {
523             return;
524         }
525
526         let mut arg = OsString::new();
527         let path = tmpdir.join("list");
528
529         debug!("EXPORTED SYMBOLS:");
530
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() {
536                     debug!("  _{}", sym);
537                     writeln!(f, "_{}", sym)?;
538                 }
539             };
540             if let Err(e) = res {
541                 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
542             }
543         } else {
544             // Write an LD version script
545             let res: io::Result<()> = try {
546                 let mut f = BufWriter::new(File::create(&path)?);
547                 writeln!(f, "{{")?;
548                 if !self.info.exports[&crate_type].is_empty() {
549                     writeln!(f, "  global:")?;
550                     for sym in self.info.exports[&crate_type].iter() {
551                         debug!("    {};", sym);
552                         writeln!(f, "    {};", sym)?;
553                     }
554                 }
555                 writeln!(f, "\n  local:\n    *;\n}};")?;
556             };
557             if let Err(e) = res {
558                 self.sess.fatal(&format!("failed to write version script: {}", e));
559             }
560         }
561
562         if self.sess.target.target.options.is_like_osx {
563             if !self.is_ld {
564                 arg.push("-Wl,")
565             }
566             arg.push("-exported_symbols_list,");
567         } else if self.sess.target.target.options.is_like_solaris {
568             if !self.is_ld {
569                 arg.push("-Wl,")
570             }
571             arg.push("-M,");
572         } else {
573             if !self.is_ld {
574                 arg.push("-Wl,")
575             }
576             arg.push("--version-script=");
577         }
578
579         arg.push(&path);
580         self.cmd.arg(arg);
581     }
582
583     fn subsystem(&mut self, subsystem: &str) {
584         self.linker_arg("--subsystem");
585         self.linker_arg(&subsystem);
586     }
587
588     fn finalize(&mut self) {
589         self.hint_dynamic(); // Reset to default before returning the composed command line.
590     }
591
592     fn group_start(&mut self) {
593         if self.takes_hints() {
594             self.linker_arg("--start-group");
595         }
596     }
597
598     fn group_end(&mut self) {
599         if self.takes_hints() {
600             self.linker_arg("--end-group");
601         }
602     }
603
604     fn linker_plugin_lto(&mut self) {
605         match self.sess.opts.cg.linker_plugin_lto {
606             LinkerPluginLto::Disabled => {
607                 // Nothing to do
608             }
609             LinkerPluginLto::LinkerPluginAuto => {
610                 self.push_linker_plugin_lto_args(None);
611             }
612             LinkerPluginLto::LinkerPlugin(ref path) => {
613                 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
614             }
615         }
616     }
617
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         if !self.sess.target.target.options.is_like_osx
623             && !self.sess.target.target.options.is_like_windows
624             && !self.sess.target.target.options.is_like_solaris
625             && self.sess.target.target.target_os != "uefi"
626         {
627             self.linker_arg("--eh-frame-hdr");
628         }
629     }
630 }
631
632 pub struct MsvcLinker<'a> {
633     cmd: Command,
634     sess: &'a Session,
635     info: &'a LinkerInfo,
636 }
637
638 impl<'a> Linker for MsvcLinker<'a> {
639     fn cmd(&mut self) -> &mut Command {
640         &mut self.cmd
641     }
642
643     fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
644         match output_kind {
645             LinkOutputKind::DynamicNoPicExe
646             | LinkOutputKind::DynamicPicExe
647             | LinkOutputKind::StaticNoPicExe
648             | LinkOutputKind::StaticPicExe => {}
649             LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
650                 self.cmd.arg("/DLL");
651                 let mut arg: OsString = "/IMPLIB:".into();
652                 arg.push(out_filename.with_extension("dll.lib"));
653                 self.cmd.arg(arg);
654             }
655         }
656     }
657
658     fn link_rlib(&mut self, lib: &Path) {
659         self.cmd.arg(lib);
660     }
661     fn add_object(&mut self, path: &Path) {
662         self.cmd.arg(path);
663     }
664
665     fn gc_sections(&mut self, _keep_metadata: bool) {
666         // MSVC's ICF (Identical COMDAT Folding) link optimization is
667         // slow for Rust and thus we disable it by default when not in
668         // optimization build.
669         if self.sess.opts.optimize != config::OptLevel::No {
670             self.cmd.arg("/OPT:REF,ICF");
671         } else {
672             // It is necessary to specify NOICF here, because /OPT:REF
673             // implies ICF by default.
674             self.cmd.arg("/OPT:REF,NOICF");
675         }
676     }
677
678     fn link_dylib(&mut self, lib: Symbol) {
679         self.cmd.arg(&format!("{}.lib", lib));
680     }
681
682     fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
683         // When producing a dll, the MSVC linker may not actually emit a
684         // `foo.lib` file if the dll doesn't actually export any symbols, so we
685         // check to see if the file is there and just omit linking to it if it's
686         // not present.
687         let name = format!("{}.dll.lib", lib);
688         if fs::metadata(&path.join(&name)).is_ok() {
689             self.cmd.arg(name);
690         }
691     }
692
693     fn link_staticlib(&mut self, lib: Symbol) {
694         self.cmd.arg(&format!("{}.lib", lib));
695     }
696
697     fn full_relro(&mut self) {
698         // noop
699     }
700
701     fn partial_relro(&mut self) {
702         // noop
703     }
704
705     fn no_relro(&mut self) {
706         // noop
707     }
708
709     fn no_crt_objects(&mut self) {
710         // noop
711     }
712
713     fn no_default_libraries(&mut self) {
714         self.cmd.arg("/NODEFAULTLIB");
715     }
716
717     fn include_path(&mut self, path: &Path) {
718         let mut arg = OsString::from("/LIBPATH:");
719         arg.push(path);
720         self.cmd.arg(&arg);
721     }
722
723     fn output_filename(&mut self, path: &Path) {
724         let mut arg = OsString::from("/OUT:");
725         arg.push(path);
726         self.cmd.arg(&arg);
727     }
728
729     fn framework_path(&mut self, _path: &Path) {
730         bug!("frameworks are not supported on windows")
731     }
732     fn link_framework(&mut self, _framework: Symbol) {
733         bug!("frameworks are not supported on windows")
734     }
735
736     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
737         self.link_staticlib(lib);
738         self.cmd.arg(format!("/WHOLEARCHIVE:{}.lib", lib));
739     }
740     fn link_whole_rlib(&mut self, path: &Path) {
741         self.link_rlib(path);
742         let mut arg = OsString::from("/WHOLEARCHIVE:");
743         arg.push(path);
744         self.cmd.arg(arg);
745     }
746     fn optimize(&mut self) {
747         // Needs more investigation of `/OPT` arguments
748     }
749
750     fn pgo_gen(&mut self) {
751         // Nothing needed here.
752     }
753
754     fn control_flow_guard(&mut self) {
755         self.cmd.arg("/guard:cf");
756     }
757
758     fn debuginfo(&mut self, strip: Strip) {
759         match strip {
760             Strip::None => {
761                 // This will cause the Microsoft linker to generate a PDB file
762                 // from the CodeView line tables in the object files.
763                 self.cmd.arg("/DEBUG");
764
765                 // This will cause the Microsoft linker to embed .natvis info into the PDB file
766                 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
767                 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
768                     for entry in natvis_dir {
769                         match entry {
770                             Ok(entry) => {
771                                 let path = entry.path();
772                                 if path.extension() == Some("natvis".as_ref()) {
773                                     let mut arg = OsString::from("/NATVIS:");
774                                     arg.push(path);
775                                     self.cmd.arg(arg);
776                                 }
777                             }
778                             Err(err) => {
779                                 self.sess
780                                     .warn(&format!("error enumerating natvis directory: {}", err));
781                             }
782                         }
783                     }
784                 }
785             }
786             Strip::Debuginfo | Strip::Symbols => {
787                 self.cmd.arg("/DEBUG:NONE");
788             }
789         }
790     }
791
792     // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
793     // export symbols from a dynamic library. When building a dynamic library,
794     // however, we're going to want some symbols exported, so this function
795     // generates a DEF file which lists all the symbols.
796     //
797     // The linker will read this `*.def` file and export all the symbols from
798     // the dynamic library. Note that this is not as simple as just exporting
799     // all the symbols in the current crate (as specified by `codegen.reachable`)
800     // but rather we also need to possibly export the symbols of upstream
801     // crates. Upstream rlibs may be linked statically to this dynamic library,
802     // in which case they may continue to transitively be used and hence need
803     // their symbols exported.
804     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
805         // Symbol visibility takes care of this typically
806         if crate_type == CrateType::Executable {
807             return;
808         }
809
810         let path = tmpdir.join("lib.def");
811         let res: io::Result<()> = try {
812             let mut f = BufWriter::new(File::create(&path)?);
813
814             // Start off with the standard module name header and then go
815             // straight to exports.
816             writeln!(f, "LIBRARY")?;
817             writeln!(f, "EXPORTS")?;
818             for symbol in self.info.exports[&crate_type].iter() {
819                 debug!("  _{}", symbol);
820                 writeln!(f, "  {}", symbol)?;
821             }
822         };
823         if let Err(e) = res {
824             self.sess.fatal(&format!("failed to write lib.def file: {}", e));
825         }
826         let mut arg = OsString::from("/DEF:");
827         arg.push(path);
828         self.cmd.arg(&arg);
829     }
830
831     fn subsystem(&mut self, subsystem: &str) {
832         // Note that previous passes of the compiler validated this subsystem,
833         // so we just blindly pass it to the linker.
834         self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
835
836         // Windows has two subsystems we're interested in right now, the console
837         // and windows subsystems. These both implicitly have different entry
838         // points (starting symbols). The console entry point starts with
839         // `mainCRTStartup` and the windows entry point starts with
840         // `WinMainCRTStartup`. These entry points, defined in system libraries,
841         // will then later probe for either `main` or `WinMain`, respectively to
842         // start the application.
843         //
844         // In Rust we just always generate a `main` function so we want control
845         // to always start there, so we force the entry point on the windows
846         // subsystem to be `mainCRTStartup` to get everything booted up
847         // correctly.
848         //
849         // For more information see RFC #1665
850         if subsystem == "windows" {
851             self.cmd.arg("/ENTRY:mainCRTStartup");
852         }
853     }
854
855     fn finalize(&mut self) {}
856
857     // MSVC doesn't need group indicators
858     fn group_start(&mut self) {}
859     fn group_end(&mut self) {}
860
861     fn linker_plugin_lto(&mut self) {
862         // Do nothing
863     }
864 }
865
866 pub struct EmLinker<'a> {
867     cmd: Command,
868     sess: &'a Session,
869     info: &'a LinkerInfo,
870 }
871
872 impl<'a> Linker for EmLinker<'a> {
873     fn cmd(&mut self) -> &mut Command {
874         &mut self.cmd
875     }
876
877     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
878
879     fn include_path(&mut self, path: &Path) {
880         self.cmd.arg("-L").arg(path);
881     }
882
883     fn link_staticlib(&mut self, lib: Symbol) {
884         self.cmd.arg("-l").sym_arg(lib);
885     }
886
887     fn output_filename(&mut self, path: &Path) {
888         self.cmd.arg("-o").arg(path);
889     }
890
891     fn add_object(&mut self, path: &Path) {
892         self.cmd.arg(path);
893     }
894
895     fn link_dylib(&mut self, lib: Symbol) {
896         // Emscripten always links statically
897         self.link_staticlib(lib);
898     }
899
900     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
901         // not supported?
902         self.link_staticlib(lib);
903     }
904
905     fn link_whole_rlib(&mut self, lib: &Path) {
906         // not supported?
907         self.link_rlib(lib);
908     }
909
910     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
911         self.link_dylib(lib);
912     }
913
914     fn link_rlib(&mut self, lib: &Path) {
915         self.add_object(lib);
916     }
917
918     fn full_relro(&mut self) {
919         // noop
920     }
921
922     fn partial_relro(&mut self) {
923         // noop
924     }
925
926     fn no_relro(&mut self) {
927         // noop
928     }
929
930     fn framework_path(&mut self, _path: &Path) {
931         bug!("frameworks are not supported on Emscripten")
932     }
933
934     fn link_framework(&mut self, _framework: Symbol) {
935         bug!("frameworks are not supported on Emscripten")
936     }
937
938     fn gc_sections(&mut self, _keep_metadata: bool) {
939         // noop
940     }
941
942     fn optimize(&mut self) {
943         // Emscripten performs own optimizations
944         self.cmd.arg(match self.sess.opts.optimize {
945             OptLevel::No => "-O0",
946             OptLevel::Less => "-O1",
947             OptLevel::Default => "-O2",
948             OptLevel::Aggressive => "-O3",
949             OptLevel::Size => "-Os",
950             OptLevel::SizeMin => "-Oz",
951         });
952         // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
953         self.cmd.args(&["--memory-init-file", "0"]);
954     }
955
956     fn pgo_gen(&mut self) {
957         // noop, but maybe we need something like the gnu linker?
958     }
959
960     fn control_flow_guard(&mut self) {}
961
962     fn debuginfo(&mut self, _strip: Strip) {
963         // Preserve names or generate source maps depending on debug info
964         self.cmd.arg(match self.sess.opts.debuginfo {
965             DebugInfo::None => "-g0",
966             DebugInfo::Limited => "-g3",
967             DebugInfo::Full => "-g4",
968         });
969     }
970
971     fn no_crt_objects(&mut self) {}
972
973     fn no_default_libraries(&mut self) {
974         self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
975     }
976
977     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
978         let symbols = &self.info.exports[&crate_type];
979
980         debug!("EXPORTED SYMBOLS:");
981
982         self.cmd.arg("-s");
983
984         let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
985         let mut encoded = String::new();
986
987         {
988             let mut encoder = json::Encoder::new(&mut encoded);
989             let res = encoder.emit_seq(symbols.len(), |encoder| {
990                 for (i, sym) in symbols.iter().enumerate() {
991                     encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
992                 }
993                 Ok(())
994             });
995             if let Err(e) = res {
996                 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
997             }
998         }
999         debug!("{}", encoded);
1000         arg.push(encoded);
1001
1002         self.cmd.arg(arg);
1003     }
1004
1005     fn subsystem(&mut self, _subsystem: &str) {
1006         // noop
1007     }
1008
1009     fn finalize(&mut self) {}
1010
1011     // Appears not necessary on Emscripten
1012     fn group_start(&mut self) {}
1013     fn group_end(&mut self) {}
1014
1015     fn linker_plugin_lto(&mut self) {
1016         // Do nothing
1017     }
1018 }
1019
1020 pub struct WasmLd<'a> {
1021     cmd: Command,
1022     sess: &'a Session,
1023     info: &'a LinkerInfo,
1024 }
1025
1026 impl<'a> WasmLd<'a> {
1027     fn new(mut cmd: Command, sess: &'a Session, info: &'a LinkerInfo) -> WasmLd<'a> {
1028         // If the atomics feature is enabled for wasm then we need a whole bunch
1029         // of flags:
1030         //
1031         // * `--shared-memory` - the link won't even succeed without this, flags
1032         //   the one linear memory as `shared`
1033         //
1034         // * `--max-memory=1G` - when specifying a shared memory this must also
1035         //   be specified. We conservatively choose 1GB but users should be able
1036         //   to override this with `-C link-arg`.
1037         //
1038         // * `--import-memory` - it doesn't make much sense for memory to be
1039         //   exported in a threaded module because typically you're
1040         //   sharing memory and instantiating the module multiple times. As a
1041         //   result if it were exported then we'd just have no sharing.
1042         //
1043         // * `--export=__wasm_init_memory` - when using `--passive-segments` the
1044         //   linker will synthesize this function, and so we need to make sure
1045         //   that our usage of `--export` below won't accidentally cause this
1046         //   function to get deleted.
1047         //
1048         // * `--export=*tls*` - when `#[thread_local]` symbols are used these
1049         //   symbols are how the TLS segments are initialized and configured.
1050         if sess.target_features.contains(&sym::atomics) {
1051             cmd.arg("--shared-memory");
1052             cmd.arg("--max-memory=1073741824");
1053             cmd.arg("--import-memory");
1054             cmd.arg("--export=__wasm_init_memory");
1055             cmd.arg("--export=__wasm_init_tls");
1056             cmd.arg("--export=__tls_size");
1057             cmd.arg("--export=__tls_align");
1058             cmd.arg("--export=__tls_base");
1059         }
1060         WasmLd { cmd, sess, info }
1061     }
1062 }
1063
1064 impl<'a> Linker for WasmLd<'a> {
1065     fn cmd(&mut self) -> &mut Command {
1066         &mut self.cmd
1067     }
1068
1069     fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1070         match output_kind {
1071             LinkOutputKind::DynamicNoPicExe
1072             | LinkOutputKind::DynamicPicExe
1073             | LinkOutputKind::StaticNoPicExe
1074             | LinkOutputKind::StaticPicExe => {}
1075             LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1076                 self.cmd.arg("--no-entry");
1077             }
1078         }
1079     }
1080
1081     fn link_dylib(&mut self, lib: Symbol) {
1082         self.cmd.arg("-l").sym_arg(lib);
1083     }
1084
1085     fn link_staticlib(&mut self, lib: Symbol) {
1086         self.cmd.arg("-l").sym_arg(lib);
1087     }
1088
1089     fn link_rlib(&mut self, lib: &Path) {
1090         self.cmd.arg(lib);
1091     }
1092
1093     fn include_path(&mut self, path: &Path) {
1094         self.cmd.arg("-L").arg(path);
1095     }
1096
1097     fn framework_path(&mut self, _path: &Path) {
1098         panic!("frameworks not supported")
1099     }
1100
1101     fn output_filename(&mut self, path: &Path) {
1102         self.cmd.arg("-o").arg(path);
1103     }
1104
1105     fn add_object(&mut self, path: &Path) {
1106         self.cmd.arg(path);
1107     }
1108
1109     fn full_relro(&mut self) {}
1110
1111     fn partial_relro(&mut self) {}
1112
1113     fn no_relro(&mut self) {}
1114
1115     fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1116         self.cmd.arg("-l").sym_arg(lib);
1117     }
1118
1119     fn link_framework(&mut self, _framework: Symbol) {
1120         panic!("frameworks not supported")
1121     }
1122
1123     fn link_whole_staticlib(&mut self, lib: Symbol, _search_path: &[PathBuf]) {
1124         self.cmd.arg("-l").sym_arg(lib);
1125     }
1126
1127     fn link_whole_rlib(&mut self, lib: &Path) {
1128         self.cmd.arg(lib);
1129     }
1130
1131     fn gc_sections(&mut self, _keep_metadata: bool) {
1132         self.cmd.arg("--gc-sections");
1133     }
1134
1135     fn optimize(&mut self) {
1136         self.cmd.arg(match self.sess.opts.optimize {
1137             OptLevel::No => "-O0",
1138             OptLevel::Less => "-O1",
1139             OptLevel::Default => "-O2",
1140             OptLevel::Aggressive => "-O3",
1141             // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1142             // instead.
1143             OptLevel::Size => "-O2",
1144             OptLevel::SizeMin => "-O2",
1145         });
1146     }
1147
1148     fn pgo_gen(&mut self) {}
1149
1150     fn debuginfo(&mut self, strip: Strip) {
1151         match strip {
1152             Strip::None => {}
1153             Strip::Debuginfo => {
1154                 self.cmd.arg("--strip-debug");
1155             }
1156             Strip::Symbols => {
1157                 self.cmd.arg("--strip-all");
1158             }
1159         }
1160     }
1161
1162     fn control_flow_guard(&mut self) {}
1163
1164     fn no_crt_objects(&mut self) {}
1165
1166     fn no_default_libraries(&mut self) {}
1167
1168     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
1169         for sym in self.info.exports[&crate_type].iter() {
1170             self.cmd.arg("--export").arg(&sym);
1171         }
1172
1173         // LLD will hide these otherwise-internal symbols since it only exports
1174         // symbols explicity passed via the `--export` flags above and hides all
1175         // others. Various bits and pieces of tooling use this, so be sure these
1176         // symbols make their way out of the linker as well.
1177         self.cmd.arg("--export=__heap_base");
1178         self.cmd.arg("--export=__data_end");
1179     }
1180
1181     fn subsystem(&mut self, _subsystem: &str) {}
1182
1183     fn finalize(&mut self) {}
1184
1185     // Not needed for now with LLD
1186     fn group_start(&mut self) {}
1187     fn group_end(&mut self) {}
1188
1189     fn linker_plugin_lto(&mut self) {
1190         // Do nothing for now
1191     }
1192 }
1193
1194 fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1195     if let Some(ref exports) = tcx.sess.target.target.options.override_export_symbols {
1196         return exports.clone();
1197     }
1198
1199     let mut symbols = Vec::new();
1200
1201     let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1202     for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1203         if level.is_below_threshold(export_threshold) {
1204             symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1205                 tcx,
1206                 symbol,
1207                 LOCAL_CRATE,
1208             ));
1209         }
1210     }
1211
1212     let formats = tcx.dependency_formats(LOCAL_CRATE);
1213     let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1214
1215     for (index, dep_format) in deps.iter().enumerate() {
1216         let cnum = CrateNum::new(index + 1);
1217         // For each dependency that we are linking to statically ...
1218         if *dep_format == Linkage::Static {
1219             // ... we add its symbol list to our export list.
1220             for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
1221                 if !level.is_below_threshold(export_threshold) {
1222                     continue;
1223                 }
1224
1225                 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1226             }
1227         }
1228     }
1229
1230     symbols
1231 }
1232
1233 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1234 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1235 pub struct PtxLinker<'a> {
1236     cmd: Command,
1237     sess: &'a Session,
1238 }
1239
1240 impl<'a> Linker for PtxLinker<'a> {
1241     fn cmd(&mut self) -> &mut Command {
1242         &mut self.cmd
1243     }
1244
1245     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1246
1247     fn link_rlib(&mut self, path: &Path) {
1248         self.cmd.arg("--rlib").arg(path);
1249     }
1250
1251     fn link_whole_rlib(&mut self, path: &Path) {
1252         self.cmd.arg("--rlib").arg(path);
1253     }
1254
1255     fn include_path(&mut self, path: &Path) {
1256         self.cmd.arg("-L").arg(path);
1257     }
1258
1259     fn debuginfo(&mut self, _strip: Strip) {
1260         self.cmd.arg("--debug");
1261     }
1262
1263     fn add_object(&mut self, path: &Path) {
1264         self.cmd.arg("--bitcode").arg(path);
1265     }
1266
1267     fn optimize(&mut self) {
1268         match self.sess.lto() {
1269             Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1270                 self.cmd.arg("-Olto");
1271             }
1272
1273             Lto::No => {}
1274         };
1275     }
1276
1277     fn output_filename(&mut self, path: &Path) {
1278         self.cmd.arg("-o").arg(path);
1279     }
1280
1281     fn finalize(&mut self) {
1282         // Provide the linker with fallback to internal `target-cpu`.
1283         self.cmd.arg("--fallback-arch").arg(match self.sess.opts.cg.target_cpu {
1284             Some(ref s) => s,
1285             None => &self.sess.target.target.options.cpu,
1286         });
1287     }
1288
1289     fn link_dylib(&mut self, _lib: Symbol) {
1290         panic!("external dylibs not supported")
1291     }
1292
1293     fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1294         panic!("external dylibs not supported")
1295     }
1296
1297     fn link_staticlib(&mut self, _lib: Symbol) {
1298         panic!("staticlibs not supported")
1299     }
1300
1301     fn link_whole_staticlib(&mut self, _lib: Symbol, _search_path: &[PathBuf]) {
1302         panic!("staticlibs not supported")
1303     }
1304
1305     fn framework_path(&mut self, _path: &Path) {
1306         panic!("frameworks not supported")
1307     }
1308
1309     fn link_framework(&mut self, _framework: Symbol) {
1310         panic!("frameworks not supported")
1311     }
1312
1313     fn full_relro(&mut self) {}
1314
1315     fn partial_relro(&mut self) {}
1316
1317     fn no_relro(&mut self) {}
1318
1319     fn gc_sections(&mut self, _keep_metadata: bool) {}
1320
1321     fn pgo_gen(&mut self) {}
1322
1323     fn no_crt_objects(&mut self) {}
1324
1325     fn no_default_libraries(&mut self) {}
1326
1327     fn control_flow_guard(&mut self) {}
1328
1329     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {}
1330
1331     fn subsystem(&mut self, _subsystem: &str) {}
1332
1333     fn group_start(&mut self) {}
1334
1335     fn group_end(&mut self) {}
1336
1337     fn linker_plugin_lto(&mut self) {}
1338 }