]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/linker.rs
0383539e7c475a0be1f25e72587d1b653e3027dc
[rust.git] / src / librustc_codegen_llvm / back / linker.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::collections::HashMap;
12 use std::ffi::{OsStr, OsString};
13 use std::fs::{self, File};
14 use std::io::prelude::*;
15 use std::io::{self, BufWriter};
16 use std::path::{Path, PathBuf};
17
18 use back::archive;
19 use back::command::Command;
20 use back::symbol_export;
21 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::session::Session;
24 use rustc::session::config::{self, CrateType, OptLevel, DebugInfoLevel,
25                              CrossLangLto};
26 use rustc::ty::TyCtxt;
27 use rustc_target::spec::{LinkerFlavor, LldFlavor};
28 use serialize::{json, Encoder};
29
30 /// For all the linkers we support, and information they might
31 /// need out of the shared crate context before we get rid of it.
32 pub struct LinkerInfo {
33     exports: HashMap<CrateType, Vec<String>>,
34 }
35
36 impl LinkerInfo {
37     pub fn new(tcx: TyCtxt) -> LinkerInfo {
38         LinkerInfo {
39             exports: tcx.sess.crate_types.borrow().iter().map(|&c| {
40                 (c, exported_symbols(tcx, c))
41             }).collect(),
42         }
43     }
44
45     pub fn to_linker<'a>(&'a self,
46                          cmd: Command,
47                          sess: &'a Session) -> Box<dyn Linker+'a> {
48         match sess.linker_flavor() {
49             LinkerFlavor::Lld(LldFlavor::Link) |
50             LinkerFlavor::Msvc => {
51                 Box::new(MsvcLinker {
52                     cmd,
53                     sess,
54                     info: self
55                 }) as Box<dyn Linker>
56             }
57             LinkerFlavor::Em =>  {
58                 Box::new(EmLinker {
59                     cmd,
60                     sess,
61                     info: self
62                 }) as Box<dyn Linker>
63             }
64             LinkerFlavor::Gcc =>  {
65                 Box::new(GccLinker {
66                     cmd,
67                     sess,
68                     info: self,
69                     hinted_static: false,
70                     is_ld: false,
71                 }) as Box<dyn Linker>
72             }
73
74             LinkerFlavor::Lld(LldFlavor::Ld) |
75             LinkerFlavor::Lld(LldFlavor::Ld64) |
76             LinkerFlavor::Ld => {
77                 Box::new(GccLinker {
78                     cmd,
79                     sess,
80                     info: self,
81                     hinted_static: false,
82                     is_ld: true,
83                 }) as Box<dyn Linker>
84             }
85
86             LinkerFlavor::Lld(LldFlavor::Wasm) => {
87                 Box::new(WasmLd {
88                     cmd,
89                     sess,
90                 }) as Box<dyn Linker>
91             }
92         }
93     }
94 }
95
96 /// Linker abstraction used by back::link to build up the command to invoke a
97 /// linker.
98 ///
99 /// This trait is the total list of requirements needed by `back::link` and
100 /// represents the meaning of each option being passed down. This trait is then
101 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
102 /// MSVC linker (e.g. `link.exe`) is being used.
103 pub trait Linker {
104     fn link_dylib(&mut self, lib: &str);
105     fn link_rust_dylib(&mut self, lib: &str, path: &Path);
106     fn link_framework(&mut self, framework: &str);
107     fn link_staticlib(&mut self, lib: &str);
108     fn link_rlib(&mut self, lib: &Path);
109     fn link_whole_rlib(&mut self, lib: &Path);
110     fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
111     fn include_path(&mut self, path: &Path);
112     fn framework_path(&mut self, path: &Path);
113     fn output_filename(&mut self, path: &Path);
114     fn add_object(&mut self, path: &Path);
115     fn gc_sections(&mut self, keep_metadata: bool);
116     fn position_independent_executable(&mut self);
117     fn no_position_independent_executable(&mut self);
118     fn full_relro(&mut self);
119     fn partial_relro(&mut self);
120     fn no_relro(&mut self);
121     fn optimize(&mut self);
122     fn pgo_gen(&mut self);
123     fn debuginfo(&mut self);
124     fn no_default_libraries(&mut self);
125     fn build_dylib(&mut self, out_filename: &Path);
126     fn build_static_executable(&mut self);
127     fn args(&mut self, args: &[String]);
128     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
129     fn subsystem(&mut self, subsystem: &str);
130     fn group_start(&mut self);
131     fn group_end(&mut self);
132     fn cross_lang_lto(&mut self);
133     // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
134     fn finalize(&mut self) -> Command;
135 }
136
137 pub struct GccLinker<'a> {
138     cmd: Command,
139     sess: &'a Session,
140     info: &'a LinkerInfo,
141     hinted_static: bool, // Keeps track of the current hinting mode.
142     // Link as ld
143     is_ld: bool,
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         !self.sess.target.target.options.is_like_osx
165     }
166
167     // Some platforms take hints about whether a library is static or dynamic.
168     // For those that support this, we ensure we pass the option if the library
169     // was flagged "static" (most defaults are dynamic) to ensure that if
170     // libfoo.a and libfoo.so both exist that the right one is chosen.
171     fn hint_static(&mut self) {
172         if !self.takes_hints() { return }
173         if !self.hinted_static {
174             self.linker_arg("-Bstatic");
175             self.hinted_static = true;
176         }
177     }
178
179     fn hint_dynamic(&mut self) {
180         if !self.takes_hints() { return }
181         if self.hinted_static {
182             self.linker_arg("-Bdynamic");
183             self.hinted_static = false;
184         }
185     }
186
187     fn push_cross_lang_lto_args(&mut self, plugin_path: Option<&OsStr>) {
188         if let Some(plugin_path) = plugin_path {
189             let mut arg = OsString::from("-plugin=");
190             arg.push(plugin_path);
191             self.linker_arg(&arg);
192         }
193
194         let opt_level = match self.sess.opts.optimize {
195             config::OptLevel::No => "O0",
196             config::OptLevel::Less => "O1",
197             config::OptLevel::Default => "O2",
198             config::OptLevel::Aggressive => "O3",
199             config::OptLevel::Size => "Os",
200             config::OptLevel::SizeMin => "Oz",
201         };
202
203         self.linker_arg(&format!("-plugin-opt={}", opt_level));
204         self.linker_arg(&format!("-plugin-opt=mcpu={}", self.sess.target_cpu()));
205
206         match self.sess.opts.cg.lto {
207             config::Lto::Thin |
208             config::Lto::ThinLocal => {
209                 self.linker_arg("-plugin-opt=thin");
210             }
211             config::Lto::Fat |
212             config::Lto::Yes |
213             config::Lto::No => {
214                 // default to regular LTO
215             }
216         }
217     }
218 }
219
220 impl<'a> Linker for GccLinker<'a> {
221     fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}",lib)); }
222     fn link_staticlib(&mut self, lib: &str) {
223         self.hint_static(); self.cmd.arg(format!("-l{}",lib));
224     }
225     fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
226     fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
227     fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
228     fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
229     fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
230     fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
231     fn no_position_independent_executable(&mut self) { self.cmd.arg("-no-pie"); }
232     fn full_relro(&mut self) { self.linker_arg("-zrelro"); self.linker_arg("-znow"); }
233     fn partial_relro(&mut self) { self.linker_arg("-zrelro"); }
234     fn no_relro(&mut self) { self.linker_arg("-znorelro"); }
235     fn build_static_executable(&mut self) { self.cmd.arg("-static"); }
236     fn args(&mut self, args: &[String]) { self.cmd.args(args); }
237
238     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
239         self.hint_dynamic();
240         self.cmd.arg(format!("-l{}",lib));
241     }
242
243     fn link_framework(&mut self, framework: &str) {
244         self.hint_dynamic();
245         self.cmd.arg("-framework").arg(framework);
246     }
247
248     // Here we explicitly ask that the entire archive is included into the
249     // result artifact. For more details see #15460, but the gist is that
250     // the linker will strip away any unused objects in the archive if we
251     // don't otherwise explicitly reference them. This can occur for
252     // libraries which are just providing bindings, libraries with generic
253     // functions, etc.
254     fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
255         self.hint_static();
256         let target = &self.sess.target.target;
257         if !target.options.is_like_osx {
258             self.linker_arg("--whole-archive").cmd.arg(format!("-l{}",lib));
259             self.linker_arg("--no-whole-archive");
260         } else {
261             // -force_load is the macOS equivalent of --whole-archive, but it
262             // involves passing the full path to the library to link.
263             self.linker_arg("-force_load");
264             let lib = archive::find_library(lib, search_path, &self.sess);
265             self.linker_arg(&lib);
266         }
267     }
268
269     fn link_whole_rlib(&mut self, lib: &Path) {
270         self.hint_static();
271         if self.sess.target.target.options.is_like_osx {
272             self.linker_arg("-force_load");
273             self.linker_arg(&lib);
274         } else {
275             self.linker_arg("--whole-archive").cmd.arg(lib);
276             self.linker_arg("--no-whole-archive");
277         }
278     }
279
280     fn gc_sections(&mut self, keep_metadata: bool) {
281         // The dead_strip option to the linker specifies that functions and data
282         // unreachable by the entry point will be removed. This is quite useful
283         // with Rust's compilation model of compiling libraries at a time into
284         // one object file. For example, this brings hello world from 1.7MB to
285         // 458K.
286         //
287         // Note that this is done for both executables and dynamic libraries. We
288         // won't get much benefit from dylibs because LLVM will have already
289         // stripped away as much as it could. This has not been seen to impact
290         // link times negatively.
291         //
292         // -dead_strip can't be part of the pre_link_args because it's also used
293         // for partial linking when using multiple codegen units (-r).  So we
294         // insert it here.
295         if self.sess.target.target.options.is_like_osx {
296             self.linker_arg("-dead_strip");
297         } else if self.sess.target.target.options.is_like_solaris {
298             self.linker_arg("-zignore");
299
300         // If we're building a dylib, we don't use --gc-sections because LLVM
301         // has already done the best it can do, and we also don't want to
302         // eliminate the metadata. If we're building an executable, however,
303         // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
304         // reduction.
305         } else if !keep_metadata {
306             self.linker_arg("--gc-sections");
307         }
308     }
309
310     fn optimize(&mut self) {
311         if !self.sess.target.target.options.linker_is_gnu { return }
312
313         // GNU-style linkers support optimization with -O. GNU ld doesn't
314         // need a numeric argument, but other linkers do.
315         if self.sess.opts.optimize == config::OptLevel::Default ||
316            self.sess.opts.optimize == config::OptLevel::Aggressive {
317             self.linker_arg("-O1");
318         }
319     }
320
321     fn pgo_gen(&mut self) {
322         if !self.sess.target.target.options.linker_is_gnu { return }
323
324         // If we're doing PGO generation stuff and on a GNU-like linker, use the
325         // "-u" flag to properly pull in the profiler runtime bits.
326         //
327         // This is because LLVM otherwise won't add the needed initialization
328         // for us on Linux (though the extra flag should be harmless if it
329         // does).
330         //
331         // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
332         //
333         // Though it may be worth to try to revert those changes upstream, since
334         // the overhead of the initialization should be minor.
335         self.cmd.arg("-u");
336         self.cmd.arg("__llvm_profile_runtime");
337     }
338
339     fn debuginfo(&mut self) {
340         match self.sess.opts.debuginfo {
341             DebugInfoLevel::NoDebugInfo => {
342                 // If we are building without debuginfo enabled and we were called with
343                 // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
344                 // found when linking to get rid of symbols from libstd.
345                 match self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
346                     Some(true) => { self.linker_arg("-S"); },
347                     _ => {},
348                 }
349             },
350             _ => {},
351         };
352     }
353
354     fn no_default_libraries(&mut self) {
355         if !self.is_ld {
356             self.cmd.arg("-nodefaultlibs");
357         }
358     }
359
360     fn build_dylib(&mut self, out_filename: &Path) {
361         // On mac we need to tell the linker to let this library be rpathed
362         if self.sess.target.target.options.is_like_osx {
363             self.cmd.arg("-dynamiclib");
364             self.linker_arg("-dylib");
365
366             // Note that the `osx_rpath_install_name` option here is a hack
367             // purely to support rustbuild right now, we should get a more
368             // principled solution at some point to force the compiler to pass
369             // the right `-Wl,-install_name` with an `@rpath` in it.
370             if self.sess.opts.cg.rpath ||
371                self.sess.opts.debugging_opts.osx_rpath_install_name {
372                 self.linker_arg("-install_name");
373                 let mut v = OsString::from("@rpath/");
374                 v.push(out_filename.file_name().unwrap());
375                 self.linker_arg(&v);
376             }
377         } else {
378             self.cmd.arg("-shared");
379         }
380     }
381
382     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
383         // If we're compiling a dylib, then we let symbol visibility in object
384         // files to take care of whether they're exported or not.
385         //
386         // If we're compiling a cdylib, however, we manually create a list of
387         // exported symbols to ensure we don't expose any more. The object files
388         // have far more public symbols than we actually want to export, so we
389         // hide them all here.
390         if crate_type == CrateType::Dylib ||
391            crate_type == CrateType::ProcMacro {
392             return
393         }
394
395         let mut arg = OsString::new();
396         let path = tmpdir.join("list");
397
398         debug!("EXPORTED SYMBOLS:");
399
400         if self.sess.target.target.options.is_like_osx {
401             // Write a plain, newline-separated list of symbols
402             let res = (|| -> io::Result<()> {
403                 let mut f = BufWriter::new(File::create(&path)?);
404                 for sym in self.info.exports[&crate_type].iter() {
405                     debug!("  _{}", sym);
406                     writeln!(f, "_{}", sym)?;
407                 }
408                 Ok(())
409             })();
410             if let Err(e) = res {
411                 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
412             }
413         } else {
414             // Write an LD version script
415             let res = (|| -> io::Result<()> {
416                 let mut f = BufWriter::new(File::create(&path)?);
417                 writeln!(f, "{{\n  global:")?;
418                 for sym in self.info.exports[&crate_type].iter() {
419                     debug!("    {};", sym);
420                     writeln!(f, "    {};", sym)?;
421                 }
422                 writeln!(f, "\n  local:\n    *;\n}};")?;
423                 Ok(())
424             })();
425             if let Err(e) = res {
426                 self.sess.fatal(&format!("failed to write version script: {}", e));
427             }
428         }
429
430         if self.sess.target.target.options.is_like_osx {
431             if !self.is_ld {
432                 arg.push("-Wl,")
433             }
434             arg.push("-exported_symbols_list,");
435         } else if self.sess.target.target.options.is_like_solaris {
436             if !self.is_ld {
437                 arg.push("-Wl,")
438             }
439             arg.push("-M,");
440         } else {
441             if !self.is_ld {
442                 arg.push("-Wl,")
443             }
444             arg.push("--version-script=");
445         }
446
447         arg.push(&path);
448         self.cmd.arg(arg);
449     }
450
451     fn subsystem(&mut self, subsystem: &str) {
452         self.linker_arg("--subsystem");
453         self.linker_arg(&subsystem);
454     }
455
456     fn finalize(&mut self) -> Command {
457         self.hint_dynamic(); // Reset to default before returning the composed command line.
458         let mut cmd = Command::new("");
459         ::std::mem::swap(&mut cmd, &mut self.cmd);
460         cmd
461     }
462
463     fn group_start(&mut self) {
464         if !self.sess.target.target.options.is_like_osx {
465             self.linker_arg("--start-group");
466         }
467     }
468
469     fn group_end(&mut self) {
470         if !self.sess.target.target.options.is_like_osx {
471             self.linker_arg("--end-group");
472         }
473     }
474
475     fn cross_lang_lto(&mut self) {
476         match self.sess.opts.debugging_opts.cross_lang_lto {
477             CrossLangLto::Disabled => {
478                 // Nothing to do
479             }
480             CrossLangLto::LinkerPluginAuto => {
481                 self.push_cross_lang_lto_args(None);
482             }
483             CrossLangLto::LinkerPlugin(ref path) => {
484                 self.push_cross_lang_lto_args(Some(path.as_os_str()));
485             }
486         }
487     }
488 }
489
490 pub struct MsvcLinker<'a> {
491     cmd: Command,
492     sess: &'a Session,
493     info: &'a LinkerInfo
494 }
495
496 impl<'a> Linker for MsvcLinker<'a> {
497     fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
498     fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
499     fn args(&mut self, args: &[String]) { self.cmd.args(args); }
500
501     fn build_dylib(&mut self, out_filename: &Path) {
502         self.cmd.arg("/DLL");
503         let mut arg: OsString = "/IMPLIB:".into();
504         arg.push(out_filename.with_extension("dll.lib"));
505         self.cmd.arg(arg);
506     }
507
508     fn build_static_executable(&mut self) {
509         // noop
510     }
511
512     fn gc_sections(&mut self, _keep_metadata: bool) {
513         // MSVC's ICF (Identical COMDAT Folding) link optimization is
514         // slow for Rust and thus we disable it by default when not in
515         // optimization build.
516         if self.sess.opts.optimize != config::OptLevel::No {
517             self.cmd.arg("/OPT:REF,ICF");
518         } else {
519             // It is necessary to specify NOICF here, because /OPT:REF
520             // implies ICF by default.
521             self.cmd.arg("/OPT:REF,NOICF");
522         }
523     }
524
525     fn link_dylib(&mut self, lib: &str) {
526         self.cmd.arg(&format!("{}.lib", lib));
527     }
528
529     fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
530         // When producing a dll, the MSVC linker may not actually emit a
531         // `foo.lib` file if the dll doesn't actually export any symbols, so we
532         // check to see if the file is there and just omit linking to it if it's
533         // not present.
534         let name = format!("{}.dll.lib", lib);
535         if fs::metadata(&path.join(&name)).is_ok() {
536             self.cmd.arg(name);
537         }
538     }
539
540     fn link_staticlib(&mut self, lib: &str) {
541         self.cmd.arg(&format!("{}.lib", lib));
542     }
543
544     fn position_independent_executable(&mut self) {
545         // noop
546     }
547
548     fn no_position_independent_executable(&mut self) {
549         // noop
550     }
551
552     fn full_relro(&mut self) {
553         // noop
554     }
555
556     fn partial_relro(&mut self) {
557         // noop
558     }
559
560     fn no_relro(&mut self) {
561         // noop
562     }
563
564     fn no_default_libraries(&mut self) {
565         // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
566         // as there's been trouble in the past of linking the C++ standard
567         // library required by LLVM. This likely needs to happen one day, but
568         // in general Windows is also a more controlled environment than
569         // Unix, so it's not necessarily as critical that this be implemented.
570         //
571         // Note that there are also some licensing worries about statically
572         // linking some libraries which require a specific agreement, so it may
573         // not ever be possible for us to pass this flag.
574     }
575
576     fn include_path(&mut self, path: &Path) {
577         let mut arg = OsString::from("/LIBPATH:");
578         arg.push(path);
579         self.cmd.arg(&arg);
580     }
581
582     fn output_filename(&mut self, path: &Path) {
583         let mut arg = OsString::from("/OUT:");
584         arg.push(path);
585         self.cmd.arg(&arg);
586     }
587
588     fn framework_path(&mut self, _path: &Path) {
589         bug!("frameworks are not supported on windows")
590     }
591     fn link_framework(&mut self, _framework: &str) {
592         bug!("frameworks are not supported on windows")
593     }
594
595     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
596         // not supported?
597         self.link_staticlib(lib);
598     }
599     fn link_whole_rlib(&mut self, path: &Path) {
600         // not supported?
601         self.link_rlib(path);
602     }
603     fn optimize(&mut self) {
604         // Needs more investigation of `/OPT` arguments
605     }
606
607     fn pgo_gen(&mut self) {
608         // Nothing needed here.
609     }
610
611     fn debuginfo(&mut self) {
612         // This will cause the Microsoft linker to generate a PDB file
613         // from the CodeView line tables in the object files.
614         self.cmd.arg("/DEBUG");
615
616         // This will cause the Microsoft linker to embed .natvis info into the the PDB file
617         let sysroot = self.sess.sysroot();
618         let natvis_dir_path = sysroot.join("lib\\rustlib\\etc");
619         if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
620             // LLVM 5.0.0's lld-link frontend doesn't yet recognize, and chokes
621             // on, the /NATVIS:... flags.  LLVM 6 (or earlier) should at worst ignore
622             // them, eventually mooting this workaround, per this landed patch:
623             // https://github.com/llvm-mirror/lld/commit/27b9c4285364d8d76bb43839daa100
624             if let Some(ref linker_path) = self.sess.opts.cg.linker {
625                 if let Some(linker_name) = Path::new(&linker_path).file_stem() {
626                     if linker_name.to_str().unwrap().to_lowercase() == "lld-link" {
627                         self.sess.warn("not embedding natvis: lld-link may not support the flag");
628                         return;
629                     }
630                 }
631             }
632             for entry in natvis_dir {
633                 match entry {
634                     Ok(entry) => {
635                         let path = entry.path();
636                         if path.extension() == Some("natvis".as_ref()) {
637                             let mut arg = OsString::from("/NATVIS:");
638                             arg.push(path);
639                             self.cmd.arg(arg);
640                         }
641                     },
642                     Err(err) => {
643                         self.sess.warn(&format!("error enumerating natvis directory: {}", err));
644                     },
645                 }
646             }
647         }
648     }
649
650     // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
651     // export symbols from a dynamic library. When building a dynamic library,
652     // however, we're going to want some symbols exported, so this function
653     // generates a DEF file which lists all the symbols.
654     //
655     // The linker will read this `*.def` file and export all the symbols from
656     // the dynamic library. Note that this is not as simple as just exporting
657     // all the symbols in the current crate (as specified by `codegen.reachable`)
658     // but rather we also need to possibly export the symbols of upstream
659     // crates. Upstream rlibs may be linked statically to this dynamic library,
660     // in which case they may continue to transitively be used and hence need
661     // their symbols exported.
662     fn export_symbols(&mut self,
663                       tmpdir: &Path,
664                       crate_type: CrateType) {
665         let path = tmpdir.join("lib.def");
666         let res = (|| -> io::Result<()> {
667             let mut f = BufWriter::new(File::create(&path)?);
668
669             // Start off with the standard module name header and then go
670             // straight to exports.
671             writeln!(f, "LIBRARY")?;
672             writeln!(f, "EXPORTS")?;
673             for symbol in self.info.exports[&crate_type].iter() {
674                 debug!("  _{}", symbol);
675                 writeln!(f, "  {}", symbol)?;
676             }
677             Ok(())
678         })();
679         if let Err(e) = res {
680             self.sess.fatal(&format!("failed to write lib.def file: {}", e));
681         }
682         let mut arg = OsString::from("/DEF:");
683         arg.push(path);
684         self.cmd.arg(&arg);
685     }
686
687     fn subsystem(&mut self, subsystem: &str) {
688         // Note that previous passes of the compiler validated this subsystem,
689         // so we just blindly pass it to the linker.
690         self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
691
692         // Windows has two subsystems we're interested in right now, the console
693         // and windows subsystems. These both implicitly have different entry
694         // points (starting symbols). The console entry point starts with
695         // `mainCRTStartup` and the windows entry point starts with
696         // `WinMainCRTStartup`. These entry points, defined in system libraries,
697         // will then later probe for either `main` or `WinMain`, respectively to
698         // start the application.
699         //
700         // In Rust we just always generate a `main` function so we want control
701         // to always start there, so we force the entry point on the windows
702         // subsystem to be `mainCRTStartup` to get everything booted up
703         // correctly.
704         //
705         // For more information see RFC #1665
706         if subsystem == "windows" {
707             self.cmd.arg("/ENTRY:mainCRTStartup");
708         }
709     }
710
711     fn finalize(&mut self) -> Command {
712         let mut cmd = Command::new("");
713         ::std::mem::swap(&mut cmd, &mut self.cmd);
714         cmd
715     }
716
717     // MSVC doesn't need group indicators
718     fn group_start(&mut self) {}
719     fn group_end(&mut self) {}
720
721     fn cross_lang_lto(&mut self) {
722         // Do nothing
723     }
724 }
725
726 pub struct EmLinker<'a> {
727     cmd: Command,
728     sess: &'a Session,
729     info: &'a LinkerInfo
730 }
731
732 impl<'a> Linker for EmLinker<'a> {
733     fn include_path(&mut self, path: &Path) {
734         self.cmd.arg("-L").arg(path);
735     }
736
737     fn link_staticlib(&mut self, lib: &str) {
738         self.cmd.arg("-l").arg(lib);
739     }
740
741     fn output_filename(&mut self, path: &Path) {
742         self.cmd.arg("-o").arg(path);
743     }
744
745     fn add_object(&mut self, path: &Path) {
746         self.cmd.arg(path);
747     }
748
749     fn link_dylib(&mut self, lib: &str) {
750         // Emscripten always links statically
751         self.link_staticlib(lib);
752     }
753
754     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
755         // not supported?
756         self.link_staticlib(lib);
757     }
758
759     fn link_whole_rlib(&mut self, lib: &Path) {
760         // not supported?
761         self.link_rlib(lib);
762     }
763
764     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
765         self.link_dylib(lib);
766     }
767
768     fn link_rlib(&mut self, lib: &Path) {
769         self.add_object(lib);
770     }
771
772     fn position_independent_executable(&mut self) {
773         // noop
774     }
775
776     fn no_position_independent_executable(&mut self) {
777         // noop
778     }
779
780     fn full_relro(&mut self) {
781         // noop
782     }
783
784     fn partial_relro(&mut self) {
785         // noop
786     }
787
788     fn no_relro(&mut self) {
789         // noop
790     }
791
792     fn args(&mut self, args: &[String]) {
793         self.cmd.args(args);
794     }
795
796     fn framework_path(&mut self, _path: &Path) {
797         bug!("frameworks are not supported on Emscripten")
798     }
799
800     fn link_framework(&mut self, _framework: &str) {
801         bug!("frameworks are not supported on Emscripten")
802     }
803
804     fn gc_sections(&mut self, _keep_metadata: bool) {
805         // noop
806     }
807
808     fn optimize(&mut self) {
809         // Emscripten performs own optimizations
810         self.cmd.arg(match self.sess.opts.optimize {
811             OptLevel::No => "-O0",
812             OptLevel::Less => "-O1",
813             OptLevel::Default => "-O2",
814             OptLevel::Aggressive => "-O3",
815             OptLevel::Size => "-Os",
816             OptLevel::SizeMin => "-Oz"
817         });
818         // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
819         self.cmd.args(&["--memory-init-file", "0"]);
820     }
821
822     fn pgo_gen(&mut self) {
823         // noop, but maybe we need something like the gnu linker?
824     }
825
826     fn debuginfo(&mut self) {
827         // Preserve names or generate source maps depending on debug info
828         self.cmd.arg(match self.sess.opts.debuginfo {
829             DebugInfoLevel::NoDebugInfo => "-g0",
830             DebugInfoLevel::LimitedDebugInfo => "-g3",
831             DebugInfoLevel::FullDebugInfo => "-g4"
832         });
833     }
834
835     fn no_default_libraries(&mut self) {
836         self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
837     }
838
839     fn build_dylib(&mut self, _out_filename: &Path) {
840         bug!("building dynamic library is unsupported on Emscripten")
841     }
842
843     fn build_static_executable(&mut self) {
844         // noop
845     }
846
847     fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
848         let symbols = &self.info.exports[&crate_type];
849
850         debug!("EXPORTED SYMBOLS:");
851
852         self.cmd.arg("-s");
853
854         let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
855         let mut encoded = String::new();
856
857         {
858             let mut encoder = json::Encoder::new(&mut encoded);
859             let res = encoder.emit_seq(symbols.len(), |encoder| {
860                 for (i, sym) in symbols.iter().enumerate() {
861                     encoder.emit_seq_elt(i, |encoder| {
862                         encoder.emit_str(&("_".to_string() + sym))
863                     })?;
864                 }
865                 Ok(())
866             });
867             if let Err(e) = res {
868                 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
869             }
870         }
871         debug!("{}", encoded);
872         arg.push(encoded);
873
874         self.cmd.arg(arg);
875     }
876
877     fn subsystem(&mut self, _subsystem: &str) {
878         // noop
879     }
880
881     fn finalize(&mut self) -> Command {
882         let mut cmd = Command::new("");
883         ::std::mem::swap(&mut cmd, &mut self.cmd);
884         cmd
885     }
886
887     // Appears not necessary on Emscripten
888     fn group_start(&mut self) {}
889     fn group_end(&mut self) {}
890
891     fn cross_lang_lto(&mut self) {
892         // Do nothing
893     }
894 }
895
896 fn exported_symbols(tcx: TyCtxt, crate_type: CrateType) -> Vec<String> {
897     let mut symbols = Vec::new();
898
899     let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
900     for &(symbol, level) in tcx.exported_symbols(LOCAL_CRATE).iter() {
901         if level.is_below_threshold(export_threshold) {
902             symbols.push(symbol.symbol_name(tcx).to_string());
903         }
904     }
905
906     let formats = tcx.sess.dependency_formats.borrow();
907     let deps = formats[&crate_type].iter();
908
909     for (index, dep_format) in deps.enumerate() {
910         let cnum = CrateNum::new(index + 1);
911         // For each dependency that we are linking to statically ...
912         if *dep_format == Linkage::Static {
913             // ... we add its symbol list to our export list.
914             for &(symbol, level) in tcx.exported_symbols(cnum).iter() {
915                 if level.is_below_threshold(export_threshold) {
916                     symbols.push(symbol.symbol_name(tcx).to_string());
917                 }
918             }
919         }
920     }
921
922     symbols
923 }
924
925 pub struct WasmLd<'a> {
926     cmd: Command,
927     sess: &'a Session,
928 }
929
930 impl<'a> Linker for WasmLd<'a> {
931     fn link_dylib(&mut self, lib: &str) {
932         self.cmd.arg("-l").arg(lib);
933     }
934
935     fn link_staticlib(&mut self, lib: &str) {
936         self.cmd.arg("-l").arg(lib);
937     }
938
939     fn link_rlib(&mut self, lib: &Path) {
940         self.cmd.arg(lib);
941     }
942
943     fn include_path(&mut self, path: &Path) {
944         self.cmd.arg("-L").arg(path);
945     }
946
947     fn framework_path(&mut self, _path: &Path) {
948         panic!("frameworks not supported")
949     }
950
951     fn output_filename(&mut self, path: &Path) {
952         self.cmd.arg("-o").arg(path);
953     }
954
955     fn add_object(&mut self, path: &Path) {
956         self.cmd.arg(path);
957     }
958
959     fn position_independent_executable(&mut self) {
960     }
961
962     fn full_relro(&mut self) {
963     }
964
965     fn partial_relro(&mut self) {
966     }
967
968     fn no_relro(&mut self) {
969     }
970
971     fn build_static_executable(&mut self) {
972     }
973
974     fn args(&mut self, args: &[String]) {
975         self.cmd.args(args);
976     }
977
978     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
979         self.cmd.arg("-l").arg(lib);
980     }
981
982     fn link_framework(&mut self, _framework: &str) {
983         panic!("frameworks not supported")
984     }
985
986     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
987         self.cmd.arg("-l").arg(lib);
988     }
989
990     fn link_whole_rlib(&mut self, lib: &Path) {
991         self.cmd.arg(lib);
992     }
993
994     fn gc_sections(&mut self, _keep_metadata: bool) {
995         self.cmd.arg("--gc-sections");
996     }
997
998     fn optimize(&mut self) {
999         self.cmd.arg(match self.sess.opts.optimize {
1000             OptLevel::No => "-O0",
1001             OptLevel::Less => "-O1",
1002             OptLevel::Default => "-O2",
1003             OptLevel::Aggressive => "-O3",
1004             // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1005             // instead.
1006             OptLevel::Size => "-O2",
1007             OptLevel::SizeMin => "-O2"
1008         });
1009         match self.sess.opts.optimize {
1010             OptLevel::No => (),
1011             OptLevel::Less |
1012             OptLevel::Default |
1013             OptLevel::Aggressive |
1014             OptLevel::Size |
1015             OptLevel::SizeMin => {
1016                 // LLD generates incorrect debugging information when
1017                 // optimization is applied: strip debug sections.
1018                 self.cmd.arg("--strip-debug");
1019             }
1020         }
1021     }
1022
1023     fn pgo_gen(&mut self) {
1024     }
1025
1026     fn debuginfo(&mut self) {
1027     }
1028
1029     fn no_default_libraries(&mut self) {
1030     }
1031
1032     fn build_dylib(&mut self, _out_filename: &Path) {
1033     }
1034
1035     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
1036     }
1037
1038     fn subsystem(&mut self, _subsystem: &str) {
1039     }
1040
1041     fn no_position_independent_executable(&mut self) {
1042     }
1043
1044     fn finalize(&mut self) -> Command {
1045         // There have been reports in the wild (rustwasm/wasm-bindgen#119) of
1046         // using threads causing weird hangs and bugs. Disable it entirely as
1047         // this isn't yet the bottleneck of compilation at all anyway.
1048         self.cmd.arg("--no-threads");
1049
1050         // By default LLD only gives us one page of stack (64k) which is a
1051         // little small. Default to a larger stack closer to other PC platforms
1052         // (1MB) and users can always inject their own link-args to override this.
1053         self.cmd.arg("-z").arg("stack-size=1048576");
1054
1055         // By default LLD's memory layout is:
1056         //
1057         // 1. First, a blank page
1058         // 2. Next, all static data
1059         // 3. Finally, the main stack (which grows down)
1060         //
1061         // This has the unfortunate consequence that on stack overflows you
1062         // corrupt static data and can cause some exceedingly weird bugs. To
1063         // help detect this a little sooner we instead request that the stack is
1064         // placed before static data.
1065         //
1066         // This means that we'll generate slightly larger binaries as references
1067         // to static data will take more bytes in the ULEB128 encoding, but
1068         // stack overflow will be guaranteed to trap as it underflows instead of
1069         // corrupting static data.
1070         self.cmd.arg("--stack-first");
1071
1072         // FIXME we probably shouldn't pass this but instead pass an explicit
1073         // whitelist of symbols we'll allow to be undefined. Unfortunately
1074         // though we can't handle symbols like `log10` that LLVM injects at a
1075         // super late date without actually parsing object files. For now let's
1076         // stick to this and hopefully fix it before stabilization happens.
1077         self.cmd.arg("--allow-undefined");
1078
1079         // For now we just never have an entry symbol
1080         self.cmd.arg("--no-entry");
1081
1082         let mut cmd = Command::new("");
1083         ::std::mem::swap(&mut cmd, &mut self.cmd);
1084         cmd
1085     }
1086
1087     // Not needed for now with LLD
1088     fn group_start(&mut self) {}
1089     fn group_end(&mut self) {}
1090
1091     fn cross_lang_lto(&mut self) {
1092         // Do nothing for now
1093     }
1094 }