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 optimize(&mut self);
108 fn debuginfo(&mut self);
109 fn no_default_libraries(&mut self);
110 fn build_dylib(&mut self, out_filename: &Path);
111 fn args(&mut self, args: &[String]);
112 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
113 fn subsystem(&mut self, subsystem: &str);
114 // Should have been finalize(self), but we don't support self-by-value on trait objects (yet?).
115 fn finalize(&mut self) -> Command;
118 pub struct GccLinker<'a> {
121 info: &'a LinkerInfo,
122 hinted_static: bool, // Keeps track of the current hinting mode.
127 impl<'a> GccLinker<'a> {
128 /// Argument that must be passed *directly* to the linker
130 /// These arguments need to be prepended with '-Wl,' when a gcc-style linker is used
131 fn linker_arg<S>(&mut self, arg: S) -> &mut Self
132 where S: AsRef<OsStr>
135 let mut os = OsString::from("-Wl,");
136 os.push(arg.as_ref());
144 fn takes_hints(&self) -> bool {
145 !self.sess.target.target.options.is_like_osx
148 // Some platforms take hints about whether a library is static or dynamic.
149 // For those that support this, we ensure we pass the option if the library
150 // was flagged "static" (most defaults are dynamic) to ensure that if
151 // libfoo.a and libfoo.so both exist that the right one is chosen.
152 fn hint_static(&mut self) {
153 if !self.takes_hints() { return }
154 if !self.hinted_static {
155 self.linker_arg("-Bstatic");
156 self.hinted_static = true;
160 fn hint_dynamic(&mut self) {
161 if !self.takes_hints() { return }
162 if self.hinted_static {
163 self.linker_arg("-Bdynamic");
164 self.hinted_static = false;
169 impl<'a> Linker for GccLinker<'a> {
170 fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg("-l").arg(lib); }
171 fn link_staticlib(&mut self, lib: &str) { self.hint_static(); self.cmd.arg("-l").arg(lib); }
172 fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); }
173 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
174 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
175 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
176 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
177 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
178 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
180 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
182 self.cmd.arg("-l").arg(lib);
185 fn link_framework(&mut self, framework: &str) {
187 self.cmd.arg("-framework").arg(framework);
190 // Here we explicitly ask that the entire archive is included into the
191 // result artifact. For more details see #15460, but the gist is that
192 // the linker will strip away any unused objects in the archive if we
193 // don't otherwise explicitly reference them. This can occur for
194 // libraries which are just providing bindings, libraries with generic
196 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
198 let target = &self.sess.target.target;
199 if !target.options.is_like_osx {
200 self.linker_arg("--whole-archive").cmd.arg("-l").arg(lib);
201 self.linker_arg("--no-whole-archive");
203 // -force_load is the macOS equivalent of --whole-archive, but it
204 // involves passing the full path to the library to link.
205 let mut v = OsString::from("-force_load,");
206 v.push(&archive::find_library(lib, search_path, &self.sess));
211 fn link_whole_rlib(&mut self, lib: &Path) {
213 if self.sess.target.target.options.is_like_osx {
214 let mut v = OsString::from("-force_load,");
218 self.linker_arg("--whole-archive").cmd.arg(lib);
219 self.linker_arg("--no-whole-archive");
223 fn gc_sections(&mut self, keep_metadata: bool) {
224 // The dead_strip option to the linker specifies that functions and data
225 // unreachable by the entry point will be removed. This is quite useful
226 // with Rust's compilation model of compiling libraries at a time into
227 // one object file. For example, this brings hello world from 1.7MB to
230 // Note that this is done for both executables and dynamic libraries. We
231 // won't get much benefit from dylibs because LLVM will have already
232 // stripped away as much as it could. This has not been seen to impact
233 // link times negatively.
235 // -dead_strip can't be part of the pre_link_args because it's also used
236 // for partial linking when using multiple codegen units (-r). So we
238 if self.sess.target.target.options.is_like_osx {
239 self.linker_arg("-dead_strip");
240 } else if self.sess.target.target.options.is_like_solaris {
241 self.linker_arg("-z");
242 self.linker_arg("ignore");
244 // If we're building a dylib, we don't use --gc-sections because LLVM
245 // has already done the best it can do, and we also don't want to
246 // eliminate the metadata. If we're building an executable, however,
247 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
249 } else if !keep_metadata {
250 self.linker_arg("--gc-sections");
254 fn optimize(&mut self) {
255 if !self.sess.target.target.options.linker_is_gnu { return }
257 // GNU-style linkers support optimization with -O. GNU ld doesn't
258 // need a numeric argument, but other linkers do.
259 if self.sess.opts.optimize == config::OptLevel::Default ||
260 self.sess.opts.optimize == config::OptLevel::Aggressive {
261 self.linker_arg("-O1");
265 fn debuginfo(&mut self) {
266 // Don't do anything special here for GNU-style linkers.
269 fn no_default_libraries(&mut self) {
271 self.cmd.arg("-nodefaultlibs");
275 fn build_dylib(&mut self, out_filename: &Path) {
276 // On mac we need to tell the linker to let this library be rpathed
277 if self.sess.target.target.options.is_like_osx {
278 self.cmd.arg("-dynamiclib");
279 self.linker_arg("-dylib");
281 // Note that the `osx_rpath_install_name` option here is a hack
282 // purely to support rustbuild right now, we should get a more
283 // principled solution at some point to force the compiler to pass
284 // the right `-Wl,-install_name` with an `@rpath` in it.
285 if self.sess.opts.cg.rpath ||
286 self.sess.opts.debugging_opts.osx_rpath_install_name {
287 let mut v = OsString::from("-install_name,@rpath/");
288 v.push(out_filename.file_name().unwrap());
292 self.cmd.arg("-shared");
296 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
297 // If we're compiling a dylib, then we let symbol visibility in object
298 // files to take care of whether they're exported or not.
300 // If we're compiling a cdylib, however, we manually create a list of
301 // exported symbols to ensure we don't expose any more. The object files
302 // have far more public symbols than we actually want to export, so we
303 // hide them all here.
304 if crate_type == CrateType::CrateTypeDylib ||
305 crate_type == CrateType::CrateTypeProcMacro {
309 let mut arg = OsString::new();
310 let path = tmpdir.join("list");
312 debug!("EXPORTED SYMBOLS:");
314 if self.sess.target.target.options.is_like_osx {
315 // Write a plain, newline-separated list of symbols
316 let res = (|| -> io::Result<()> {
317 let mut f = BufWriter::new(File::create(&path)?);
318 for sym in self.info.exports[&crate_type].iter() {
320 writeln!(f, "_{}", sym)?;
324 if let Err(e) = res {
325 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
328 // Write an LD version script
329 let res = (|| -> io::Result<()> {
330 let mut f = BufWriter::new(File::create(&path)?);
331 writeln!(f, "{{\n global:")?;
332 for sym in self.info.exports[&crate_type].iter() {
334 writeln!(f, " {};", sym)?;
336 writeln!(f, "\n local:\n *;\n}};")?;
339 if let Err(e) = res {
340 self.sess.fatal(&format!("failed to write version script: {}", e));
344 if self.sess.target.target.options.is_like_osx {
348 arg.push("-exported_symbols_list,");
349 } else if self.sess.target.target.options.is_like_solaris {
358 arg.push("--version-script=");
365 fn subsystem(&mut self, subsystem: &str) {
366 self.linker_arg(&format!("--subsystem,{}", subsystem));
369 fn finalize(&mut self) -> Command {
370 self.hint_dynamic(); // Reset to default before returning the composed command line.
371 let mut cmd = Command::new("");
372 ::std::mem::swap(&mut cmd, &mut self.cmd);
377 pub struct MsvcLinker<'a> {
383 impl<'a> Linker for MsvcLinker<'a> {
384 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
385 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
386 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
388 fn build_dylib(&mut self, out_filename: &Path) {
389 self.cmd.arg("/DLL");
390 let mut arg: OsString = "/IMPLIB:".into();
391 arg.push(out_filename.with_extension("dll.lib"));
395 fn gc_sections(&mut self, _keep_metadata: bool) {
396 // MSVC's ICF (Identical COMDAT Folding) link optimization is
397 // slow for Rust and thus we disable it by default when not in
398 // optimization build.
399 if self.sess.opts.optimize != config::OptLevel::No {
400 self.cmd.arg("/OPT:REF,ICF");
402 // It is necessary to specify NOICF here, because /OPT:REF
403 // implies ICF by default.
404 self.cmd.arg("/OPT:REF,NOICF");
408 fn link_dylib(&mut self, lib: &str) {
409 self.cmd.arg(&format!("{}.lib", lib));
412 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
413 // When producing a dll, the MSVC linker may not actually emit a
414 // `foo.lib` file if the dll doesn't actually export any symbols, so we
415 // check to see if the file is there and just omit linking to it if it's
417 let name = format!("{}.dll.lib", lib);
418 if fs::metadata(&path.join(&name)).is_ok() {
423 fn link_staticlib(&mut self, lib: &str) {
424 self.cmd.arg(&format!("{}.lib", lib));
427 fn position_independent_executable(&mut self) {
431 fn no_default_libraries(&mut self) {
432 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
433 // as there's been trouble in the past of linking the C++ standard
434 // library required by LLVM. This likely needs to happen one day, but
435 // in general Windows is also a more controlled environment than
436 // Unix, so it's not necessarily as critical that this be implemented.
438 // Note that there are also some licensing worries about statically
439 // linking some libraries which require a specific agreement, so it may
440 // not ever be possible for us to pass this flag.
443 fn include_path(&mut self, path: &Path) {
444 let mut arg = OsString::from("/LIBPATH:");
449 fn output_filename(&mut self, path: &Path) {
450 let mut arg = OsString::from("/OUT:");
455 fn framework_path(&mut self, _path: &Path) {
456 bug!("frameworks are not supported on windows")
458 fn link_framework(&mut self, _framework: &str) {
459 bug!("frameworks are not supported on windows")
462 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
464 self.link_staticlib(lib);
466 fn link_whole_rlib(&mut self, path: &Path) {
468 self.link_rlib(path);
470 fn optimize(&mut self) {
471 // Needs more investigation of `/OPT` arguments
474 fn debuginfo(&mut self) {
475 // This will cause the Microsoft linker to generate a PDB file
476 // from the CodeView line tables in the object files.
477 self.cmd.arg("/DEBUG");
480 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
481 // export symbols from a dynamic library. When building a dynamic library,
482 // however, we're going to want some symbols exported, so this function
483 // generates a DEF file which lists all the symbols.
485 // The linker will read this `*.def` file and export all the symbols from
486 // the dynamic library. Note that this is not as simple as just exporting
487 // all the symbols in the current crate (as specified by `trans.reachable`)
488 // but rather we also need to possibly export the symbols of upstream
489 // crates. Upstream rlibs may be linked statically to this dynamic library,
490 // in which case they may continue to transitively be used and hence need
491 // their symbols exported.
492 fn export_symbols(&mut self,
494 crate_type: CrateType) {
495 let path = tmpdir.join("lib.def");
496 let res = (|| -> io::Result<()> {
497 let mut f = BufWriter::new(File::create(&path)?);
499 // Start off with the standard module name header and then go
500 // straight to exports.
501 writeln!(f, "LIBRARY")?;
502 writeln!(f, "EXPORTS")?;
503 for symbol in self.info.exports[&crate_type].iter() {
504 debug!(" _{}", symbol);
505 writeln!(f, " {}", symbol)?;
509 if let Err(e) = res {
510 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
512 let mut arg = OsString::from("/DEF:");
517 fn subsystem(&mut self, subsystem: &str) {
518 // Note that previous passes of the compiler validated this subsystem,
519 // so we just blindly pass it to the linker.
520 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
522 // Windows has two subsystems we're interested in right now, the console
523 // and windows subsystems. These both implicitly have different entry
524 // points (starting symbols). The console entry point starts with
525 // `mainCRTStartup` and the windows entry point starts with
526 // `WinMainCRTStartup`. These entry points, defined in system libraries,
527 // will then later probe for either `main` or `WinMain`, respectively to
528 // start the application.
530 // In Rust we just always generate a `main` function so we want control
531 // to always start there, so we force the entry point on the windows
532 // subsystem to be `mainCRTStartup` to get everything booted up
535 // For more information see RFC #1665
536 if subsystem == "windows" {
537 self.cmd.arg("/ENTRY:mainCRTStartup");
541 fn finalize(&mut self) -> Command {
542 let mut cmd = Command::new("");
543 ::std::mem::swap(&mut cmd, &mut self.cmd);
548 pub struct EmLinker<'a> {
554 impl<'a> Linker for EmLinker<'a> {
555 fn include_path(&mut self, path: &Path) {
556 self.cmd.arg("-L").arg(path);
559 fn link_staticlib(&mut self, lib: &str) {
560 self.cmd.arg("-l").arg(lib);
563 fn output_filename(&mut self, path: &Path) {
564 self.cmd.arg("-o").arg(path);
567 fn add_object(&mut self, path: &Path) {
571 fn link_dylib(&mut self, lib: &str) {
572 // Emscripten always links statically
573 self.link_staticlib(lib);
576 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
578 self.link_staticlib(lib);
581 fn link_whole_rlib(&mut self, lib: &Path) {
586 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
587 self.link_dylib(lib);
590 fn link_rlib(&mut self, lib: &Path) {
591 self.add_object(lib);
594 fn position_independent_executable(&mut self) {
598 fn args(&mut self, args: &[String]) {
602 fn framework_path(&mut self, _path: &Path) {
603 bug!("frameworks are not supported on Emscripten")
606 fn link_framework(&mut self, _framework: &str) {
607 bug!("frameworks are not supported on Emscripten")
610 fn gc_sections(&mut self, _keep_metadata: bool) {
614 fn optimize(&mut self) {
615 // Emscripten performs own optimizations
616 self.cmd.arg(match self.sess.opts.optimize {
617 OptLevel::No => "-O0",
618 OptLevel::Less => "-O1",
619 OptLevel::Default => "-O2",
620 OptLevel::Aggressive => "-O3",
621 OptLevel::Size => "-Os",
622 OptLevel::SizeMin => "-Oz"
624 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
625 self.cmd.args(&["--memory-init-file", "0"]);
628 fn debuginfo(&mut self) {
629 // Preserve names or generate source maps depending on debug info
630 self.cmd.arg(match self.sess.opts.debuginfo {
631 DebugInfoLevel::NoDebugInfo => "-g0",
632 DebugInfoLevel::LimitedDebugInfo => "-g3",
633 DebugInfoLevel::FullDebugInfo => "-g4"
637 fn no_default_libraries(&mut self) {
638 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
641 fn build_dylib(&mut self, _out_filename: &Path) {
642 bug!("building dynamic library is unsupported on Emscripten")
645 fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
646 let symbols = &self.info.exports[&crate_type];
648 debug!("EXPORTED SYMBOLS:");
652 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
653 let mut encoded = String::new();
656 let mut encoder = json::Encoder::new(&mut encoded);
657 let res = encoder.emit_seq(symbols.len(), |encoder| {
658 for (i, sym) in symbols.iter().enumerate() {
659 encoder.emit_seq_elt(i, |encoder| {
660 encoder.emit_str(&("_".to_string() + sym))
665 if let Err(e) = res {
666 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
669 debug!("{}", encoded);
675 fn subsystem(&mut self, _subsystem: &str) {
679 fn finalize(&mut self) -> Command {
680 let mut cmd = Command::new("");
681 ::std::mem::swap(&mut cmd, &mut self.cmd);
686 fn exported_symbols(scx: &SharedCrateContext,
687 exported_symbols: &ExportedSymbols,
688 crate_type: CrateType)
690 let export_threshold = symbol_export::crate_export_threshold(crate_type);
692 let mut symbols = Vec::new();
693 exported_symbols.for_each_exported_symbol(LOCAL_CRATE, export_threshold, |name, _| {
694 symbols.push(name.to_owned());
697 let formats = scx.sess().dependency_formats.borrow();
698 let deps = formats[&crate_type].iter();
700 for (index, dep_format) in deps.enumerate() {
701 let cnum = CrateNum::new(index + 1);
702 // For each dependency that we are linking to statically ...
703 if *dep_format == Linkage::Static {
704 // ... we add its symbol list to our export list.
705 exported_symbols.for_each_exported_symbol(cnum, export_threshold, |name, _| {
706 symbols.push(name.to_owned());