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