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