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