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