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