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.
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.
11 use std::collections::HashMap;
12 use std::ffi::{OsStr, OsString};
13 use std::fs::{self, File};
14 use std::io::prelude::*;
15 use std::io::{self, BufWriter};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
19 use context::SharedCrateContext;
22 use back::symbol_export::{self, ExportedSymbols};
23 use rustc::middle::dependency_format::Linkage;
24 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
25 use rustc_back::LinkerFlavor;
26 use rustc::session::Session;
27 use rustc::session::config::{self, CrateType, OptLevel, DebugInfoLevel};
28 use serialize::{json, Encoder};
30 /// For all the linkers we support, and information they might
31 /// need out of the shared crate context before we get rid of it.
32 pub struct LinkerInfo {
33 exports: HashMap<CrateType, Vec<String>>,
36 impl<'a, 'tcx> LinkerInfo {
37 pub fn new(scx: &SharedCrateContext<'a, 'tcx>,
38 exports: &ExportedSymbols) -> LinkerInfo {
40 exports: scx.sess().crate_types.borrow().iter().map(|&c| {
41 (c, exported_symbols(scx, exports, c))
46 pub fn to_linker(&'a self,
48 sess: &'a Session) -> Box<Linker+'a> {
49 match sess.linker_flavor() {
50 LinkerFlavor::Msvc => {
64 LinkerFlavor::Gcc => {
86 /// Linker abstraction used by back::link to build up the command to invoke a
89 /// This trait is the total list of requirements needed by `back::link` and
90 /// represents the meaning of each option being passed down. This trait is then
91 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
92 /// MSVC linker (e.g. `link.exe`) is being used.
94 fn link_dylib(&mut self, lib: &str);
95 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
96 fn link_framework(&mut self, framework: &str);
97 fn link_staticlib(&mut self, lib: &str);
98 fn link_rlib(&mut self, lib: &Path);
99 fn link_whole_rlib(&mut self, lib: &Path);
100 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
101 fn include_path(&mut self, path: &Path);
102 fn framework_path(&mut self, path: &Path);
103 fn output_filename(&mut self, path: &Path);
104 fn add_object(&mut self, path: &Path);
105 fn gc_sections(&mut self, keep_metadata: bool);
106 fn position_independent_executable(&mut self);
107 fn full_relro(&mut self);
108 fn optimize(&mut self);
109 fn debuginfo(&mut self);
110 fn no_default_libraries(&mut self);
111 fn build_dylib(&mut self, out_filename: &Path);
112 fn args(&mut self, args: &[String]);
113 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
114 fn subsystem(&mut self, subsystem: &str);
115 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
116 fn finalize(&mut self) -> Command;
119 pub struct GccLinker<'a> {
122 info: &'a LinkerInfo,
123 hinted_static: bool, // Keeps track of the current hinting mode.
128 impl<'a> GccLinker<'a> {
129 /// Argument that must be passed *directly* to the linker
131 /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
132 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
133 where S: AsRef<OsStr>
136 let mut os = OsString::from("-Wl,");
137 os.push(arg.as_ref());
145 fn takes_hints(&self) -> bool {
146 !self.sess.target.target.options.is_like_osx
149 // Some platforms take hints about whether a library is static or dynamic.
150 // For those that support this, we ensure we pass the option if the library
151 // was flagged "static" (most defaults are dynamic) to ensure that if
152 // libfoo.a and libfoo.so both exist that the right one is chosen.
153 fn hint_static(&mut self) {
154 if !self.takes_hints() { return }
155 if !self.hinted_static {
156 self.linker_arg("-Bstatic");
157 self.hinted_static = true;
161 fn hint_dynamic(&mut self) {
162 if !self.takes_hints() { return }
163 if self.hinted_static {
164 self.linker_arg("-Bdynamic");
165 self.hinted_static = false;
170 impl<'a> Linker for GccLinker<'a> {
171 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg("-l").arg(lib); }
172 fn link_staticlib(&mut self, lib: &str) { self.hint_static(); self.cmd.arg("-l").arg(lib); }
173 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
174 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
175 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
176 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
177 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
178 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
179 fn full_relro(&mut self) { self.linker_arg("-z,relro,-z,now"); }
180 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
182 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
184 self.cmd.arg("-l").arg(lib);
187 fn link_framework(&mut self, framework: &str) {
189 self.cmd.arg("-framework").arg(framework);
192 // Here we explicitly ask that the entire archive is included into the
193 // result artifact. For more details see #15460, but the gist is that
194 // the linker will strip away any unused objects in the archive if we
195 // don't otherwise explicitly reference them. This can occur for
196 // libraries which are just providing bindings, libraries with generic
198 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
200 let target = &self.sess.target.target;
201 if !target.options.is_like_osx {
202 self.linker_arg("--whole-archive").cmd.arg("-l").arg(lib);
203 self.linker_arg("--no-whole-archive");
205 // -force_load is the macOS equivalent of --whole-archive, but it
206 // involves passing the full path to the library to link.
207 let mut v = OsString::from("-force_load,");
208 v.push(&archive::find_library(lib, search_path, &self.sess));
213 fn link_whole_rlib(&mut self, lib: &Path) {
215 if self.sess.target.target.options.is_like_osx {
216 let mut v = OsString::from("-force_load,");
220 self.linker_arg("--whole-archive").cmd.arg(lib);
221 self.linker_arg("--no-whole-archive");
225 fn gc_sections(&mut self, keep_metadata: bool) {
226 // The dead_strip option to the linker specifies that functions and data
227 // unreachable by the entry point will be removed. This is quite useful
228 // with Rust's compilation model of compiling libraries at a time into
229 // one object file. For example, this brings hello world from 1.7MB to
232 // Note that this is done for both executables and dynamic libraries. We
233 // won't get much benefit from dylibs because LLVM will have already
234 // stripped away as much as it could. This has not been seen to impact
235 // link times negatively.
237 // -dead_strip can't be part of the pre_link_args because it's also used
238 // for partial linking when using multiple codegen units (-r). So we
240 if self.sess.target.target.options.is_like_osx {
241 self.linker_arg("-dead_strip");
242 } else if self.sess.target.target.options.is_like_solaris {
243 self.linker_arg("-z");
244 self.linker_arg("ignore");
246 // If we're building a dylib, we don't use --gc-sections because LLVM
247 // has already done the best it can do, and we also don't want to
248 // eliminate the metadata. If we're building an executable, however,
249 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
251 } else if !keep_metadata {
252 self.linker_arg("--gc-sections");
256 fn optimize(&mut self) {
257 if !self.sess.target.target.options.linker_is_gnu { return }
259 // GNU-style linkers support optimization with -O. GNU ld doesn't
260 // need a numeric argument, but other linkers do.
261 if self.sess.opts.optimize == config::OptLevel::Default ||
262 self.sess.opts.optimize == config::OptLevel::Aggressive {
263 self.linker_arg("-O1");
267 fn debuginfo(&mut self) {
268 // Don't do anything special here for GNU-style linkers.
271 fn no_default_libraries(&mut self) {
273 self.cmd.arg("-nodefaultlibs");
277 fn build_dylib(&mut self, out_filename: &Path) {
278 // On mac we need to tell the linker to let this library be rpathed
279 if self.sess.target.target.options.is_like_osx {
280 self.cmd.arg("-dynamiclib");
281 self.linker_arg("-dylib");
283 // Note that the `osx_rpath_install_name` option here is a hack
284 // purely to support rustbuild right now, we should get a more
285 // principled solution at some point to force the compiler to pass
286 // the right `-Wl,-install_name` with an `@rpath` in it.
287 if self.sess.opts.cg.rpath ||
288 self.sess.opts.debugging_opts.osx_rpath_install_name {
289 let mut v = OsString::from("-install_name,@rpath/");
290 v.push(out_filename.file_name().unwrap());
294 self.cmd.arg("-shared");
298 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
299 // If we're compiling a dylib, then we let symbol visibility in object
300 // files to take care of whether they're exported or not.
302 // If we're compiling a cdylib, however, we manually create a list of
303 // exported symbols to ensure we don't expose any more. The object files
304 // have far more public symbols than we actually want to export, so we
305 // hide them all here.
306 if crate_type == CrateType::CrateTypeDylib ||
307 crate_type == CrateType::CrateTypeProcMacro {
311 let mut arg = OsString::new();
312 let path = tmpdir.join("list");
314 debug!("EXPORTED SYMBOLS:");
316 if self.sess.target.target.options.is_like_osx {
317 // Write a plain, newline-separated list of symbols
318 let res = (|| -> io::Result<()> {
319 let mut f = BufWriter::new(File::create(&path)?);
320 for sym in self.info.exports[&crate_type].iter() {
322 writeln!(f, "_{}", sym)?;
326 if let Err(e) = res {
327 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
330 // Write an LD version script
331 let res = (|| -> io::Result<()> {
332 let mut f = BufWriter::new(File::create(&path)?);
333 writeln!(f, "{{\n global:")?;
334 for sym in self.info.exports[&crate_type].iter() {
336 writeln!(f, " {};", sym)?;
338 writeln!(f, "\n local:\n *;\n}};")?;
341 if let Err(e) = res {
342 self.sess.fatal(&format!("failed to write version script: {}", e));
346 if self.sess.target.target.options.is_like_osx {
350 arg.push("-exported_symbols_list,");
351 } else if self.sess.target.target.options.is_like_solaris {
360 arg.push("--version-script=");
367 fn subsystem(&mut self, subsystem: &str) {
368 self.linker_arg(&format!("--subsystem,{}", subsystem));
371 fn finalize(&mut self) -> Command {
372 self.hint_dynamic(); // Reset to default before returning the composed command line.
373 let mut cmd = Command::new("");
374 ::std::mem::swap(&mut cmd, &mut self.cmd);
379 pub struct MsvcLinker<'a> {
385 impl<'a> Linker for MsvcLinker<'a> {
386 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
387 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
388 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
390 fn build_dylib(&mut self, out_filename: &Path) {
391 self.cmd.arg("/DLL");
392 let mut arg: OsString = "/IMPLIB:".into();
393 arg.push(out_filename.with_extension("dll.lib"));
397 fn gc_sections(&mut self, _keep_metadata: bool) {
398 // MSVC's ICF (Identical COMDAT Folding) link optimization is
399 // slow for Rust and thus we disable it by default when not in
400 // optimization build.
401 if self.sess.opts.optimize != config::OptLevel::No {
402 self.cmd.arg("/OPT:REF,ICF");
404 // It is necessary to specify NOICF here, because /OPT:REF
405 // implies ICF by default.
406 self.cmd.arg("/OPT:REF,NOICF");
410 fn link_dylib(&mut self, lib: &str) {
411 self.cmd.arg(&format!("{}.lib", lib));
414 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
415 // When producing a dll, the MSVC linker may not actually emit a
416 // `foo.lib` file if the dll doesn't actually export any symbols, so we
417 // check to see if the file is there and just omit linking to it if it's
419 let name = format!("{}.dll.lib", lib);
420 if fs::metadata(&path.join(&name)).is_ok() {
425 fn link_staticlib(&mut self, lib: &str) {
426 self.cmd.arg(&format!("{}.lib", lib));
429 fn position_independent_executable(&mut self) {
433 fn full_relro(&mut self) {
437 fn no_default_libraries(&mut self) {
438 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
439 // as there's been trouble in the past of linking the C++ standard
440 // library required by LLVM. This likely needs to happen one day, but
441 // in general Windows is also a more controlled environment than
442 // Unix, so it's not necessarily as critical that this be implemented.
444 // Note that there are also some licensing worries about statically
445 // linking some libraries which require a specific agreement, so it may
446 // not ever be possible for us to pass this flag.
449 fn include_path(&mut self, path: &Path) {
450 let mut arg = OsString::from("/LIBPATH:");
455 fn output_filename(&mut self, path: &Path) {
456 let mut arg = OsString::from("/OUT:");
461 fn framework_path(&mut self, _path: &Path) {
462 bug!("frameworks are not supported on windows")
464 fn link_framework(&mut self, _framework: &str) {
465 bug!("frameworks are not supported on windows")
468 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
470 self.link_staticlib(lib);
472 fn link_whole_rlib(&mut self, path: &Path) {
474 self.link_rlib(path);
476 fn optimize(&mut self) {
477 // Needs more investigation of `/OPT` arguments
480 fn debuginfo(&mut self) {
481 // This will cause the Microsoft linker to generate a PDB file
482 // from the CodeView line tables in the object files.
483 self.cmd.arg("/DEBUG");
486 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
487 // export symbols from a dynamic library. When building a dynamic library,
488 // however, we're going to want some symbols exported, so this function
489 // generates a DEF file which lists all the symbols.
491 // The linker will read this `*.def` file and export all the symbols from
492 // the dynamic library. Note that this is not as simple as just exporting
493 // all the symbols in the current crate (as specified by `trans.reachable`)
494 // but rather we also need to possibly export the symbols of upstream
495 // crates. Upstream rlibs may be linked statically to this dynamic library,
496 // in which case they may continue to transitively be used and hence need
497 // their symbols exported.
498 fn export_symbols(&mut self,
500 crate_type: CrateType) {
501 let path = tmpdir.join("lib.def");
502 let res = (|| -> io::Result<()> {
503 let mut f = BufWriter::new(File::create(&path)?);
505 // Start off with the standard module name header and then go
506 // straight to exports.
507 writeln!(f, "LIBRARY")?;
508 writeln!(f, "EXPORTS")?;
509 for symbol in self.info.exports[&crate_type].iter() {
510 debug!(" _{}", symbol);
511 writeln!(f, " {}", symbol)?;
515 if let Err(e) = res {
516 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
518 let mut arg = OsString::from("/DEF:");
523 fn subsystem(&mut self, subsystem: &str) {
524 // Note that previous passes of the compiler validated this subsystem,
525 // so we just blindly pass it to the linker.
526 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
528 // Windows has two subsystems we're interested in right now, the console
529 // and windows subsystems. These both implicitly have different entry
530 // points (starting symbols). The console entry point starts with
531 // `mainCRTStartup` and the windows entry point starts with
532 // `WinMainCRTStartup`. These entry points, defined in system libraries,
533 // will then later probe for either `main` or `WinMain`, respectively to
534 // start the application.
536 // In Rust we just always generate a `main` function so we want control
537 // to always start there, so we force the entry point on the windows
538 // subsystem to be `mainCRTStartup` to get everything booted up
541 // For more information see RFC #1665
542 if subsystem == "windows" {
543 self.cmd.arg("/ENTRY:mainCRTStartup");
547 fn finalize(&mut self) -> Command {
548 let mut cmd = Command::new("");
549 ::std::mem::swap(&mut cmd, &mut self.cmd);
554 pub struct EmLinker<'a> {
560 impl<'a> Linker for EmLinker<'a> {
561 fn include_path(&mut self, path: &Path) {
562 self.cmd.arg("-L").arg(path);
565 fn link_staticlib(&mut self, lib: &str) {
566 self.cmd.arg("-l").arg(lib);
569 fn output_filename(&mut self, path: &Path) {
570 self.cmd.arg("-o").arg(path);
573 fn add_object(&mut self, path: &Path) {
577 fn link_dylib(&mut self, lib: &str) {
578 // Emscripten always links statically
579 self.link_staticlib(lib);
582 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
584 self.link_staticlib(lib);
587 fn link_whole_rlib(&mut self, lib: &Path) {
592 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
593 self.link_dylib(lib);
596 fn link_rlib(&mut self, lib: &Path) {
597 self.add_object(lib);
600 fn position_independent_executable(&mut self) {
604 fn full_relro(&mut self) {
608 fn args(&mut self, args: &[String]) {
612 fn framework_path(&mut self, _path: &Path) {
613 bug!("frameworks are not supported on Emscripten")
616 fn link_framework(&mut self, _framework: &str) {
617 bug!("frameworks are not supported on Emscripten")
620 fn gc_sections(&mut self, _keep_metadata: bool) {
624 fn optimize(&mut self) {
625 // Emscripten performs own optimizations
626 self.cmd.arg(match self.sess.opts.optimize {
627 OptLevel::No => "-O0",
628 OptLevel::Less => "-O1",
629 OptLevel::Default => "-O2",
630 OptLevel::Aggressive => "-O3",
631 OptLevel::Size => "-Os",
632 OptLevel::SizeMin => "-Oz"
634 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
635 self.cmd.args(&["--memory-init-file", "0"]);
638 fn debuginfo(&mut self) {
639 // Preserve names or generate source maps depending on debug info
640 self.cmd.arg(match self.sess.opts.debuginfo {
641 DebugInfoLevel::NoDebugInfo => "-g0",
642 DebugInfoLevel::LimitedDebugInfo => "-g3",
643 DebugInfoLevel::FullDebugInfo => "-g4"
647 fn no_default_libraries(&mut self) {
648 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
651 fn build_dylib(&mut self, _out_filename: &Path) {
652 bug!("building dynamic library is unsupported on Emscripten")
655 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
656 let symbols = &self.info.exports[&crate_type];
658 debug!("EXPORTED SYMBOLS:");
662 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
663 let mut encoded = String::new();
666 let mut encoder = json::Encoder::new(&mut encoded);
667 let res = encoder.emit_seq(symbols.len(), |encoder| {
668 for (i, sym) in symbols.iter().enumerate() {
669 encoder.emit_seq_elt(i, |encoder| {
670 encoder.emit_str(&("_".to_string() + sym))
675 if let Err(e) = res {
676 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
679 debug!("{}", encoded);
685 fn subsystem(&mut self, _subsystem: &str) {
689 fn finalize(&mut self) -> Command {
690 let mut cmd = Command::new("");
691 ::std::mem::swap(&mut cmd, &mut self.cmd);
696 fn exported_symbols(scx: &SharedCrateContext,
697 exported_symbols: &ExportedSymbols,
698 crate_type: CrateType)
700 let export_threshold = symbol_export::crate_export_threshold(crate_type);
702 let mut symbols = Vec::new();
703 exported_symbols.for_each_exported_symbol(LOCAL_CRATE, export_threshold, |name, _| {
704 symbols.push(name.to_owned());
707 let formats = scx.sess().dependency_formats.borrow();
708 let deps = formats[&crate_type].iter();
710 for (index, dep_format) in deps.enumerate() {
711 let cnum = CrateNum::new(index + 1);
712 // For each dependency that we are linking to statically ...
713 if *dep_format == Linkage::Static {
714 // ... we add its symbol list to our export list.
715 exported_symbols.for_each_exported_symbol(cnum, export_threshold, |name, _| {
716 symbols.push(name.to_owned());