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::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 middle::dependency_format::Linkage;
24 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
26 use session::config::CrateType;
29 /// For all the linkers we support, and information they might
30 /// need out of the shared crate context before we get rid of it.
31 pub struct LinkerInfo {
32 exports: HashMap<CrateType, Vec<String>>,
35 impl<'a, 'tcx> LinkerInfo {
36 pub fn new(scx: &SharedCrateContext<'a, 'tcx>,
37 exports: &ExportedSymbols) -> LinkerInfo {
39 exports: scx.sess().crate_types.borrow().iter().map(|&c| {
40 (c, exported_symbols(scx, exports, c))
45 pub fn to_linker(&'a self,
47 sess: &'a Session) -> Box<Linker+'a> {
48 if sess.target.target.options.is_like_msvc {
64 /// Linker abstraction used by back::link to build up the command to invoke a
67 /// This trait is the total list of requirements needed by `back::link` and
68 /// represents the meaning of each option being passed down. This trait is then
69 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
70 /// MSVC linker (e.g. `link.exe`) is being used.
72 fn link_dylib(&mut self, lib: &str);
73 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
74 fn link_framework(&mut self, framework: &str);
75 fn link_staticlib(&mut self, lib: &str);
76 fn link_rlib(&mut self, lib: &Path);
77 fn link_whole_rlib(&mut self, lib: &Path);
78 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]);
79 fn include_path(&mut self, path: &Path);
80 fn framework_path(&mut self, path: &Path);
81 fn output_filename(&mut self, path: &Path);
82 fn add_object(&mut self, path: &Path);
83 fn gc_sections(&mut self, keep_metadata: bool);
84 fn position_independent_executable(&mut self);
85 fn optimize(&mut self);
86 fn debuginfo(&mut self);
87 fn no_default_libraries(&mut self);
88 fn build_dylib(&mut self, out_filename: &Path);
89 fn args(&mut self, args: &[String]);
90 fn hint_static(&mut self);
91 fn hint_dynamic(&mut self);
92 fn whole_archives(&mut self);
93 fn no_whole_archives(&mut self);
94 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType);
95 fn subsystem(&mut self, subsystem: &str);
98 pub struct GnuLinker<'a> {
104 impl<'a> GnuLinker<'a> {
105 fn takes_hints(&self) -> bool {
106 !self.sess.target.target.options.is_like_osx
110 impl<'a> Linker for GnuLinker<'a> {
111 fn link_dylib(&mut self, lib: &str) { self.cmd.arg("-l").arg(lib); }
112 fn link_staticlib(&mut self, lib: &str) { self.cmd.arg("-l").arg(lib); }
113 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
114 fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); }
115 fn framework_path(&mut self, path: &Path) { self.cmd.arg("-F").arg(path); }
116 fn output_filename(&mut self, path: &Path) { self.cmd.arg("-o").arg(path); }
117 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
118 fn position_independent_executable(&mut self) { self.cmd.arg("-pie"); }
119 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
121 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
122 self.cmd.arg("-l").arg(lib);
125 fn link_framework(&mut self, framework: &str) {
126 self.cmd.arg("-framework").arg(framework);
129 fn link_whole_staticlib(&mut self, lib: &str, search_path: &[PathBuf]) {
130 let target = &self.sess.target.target;
131 if !target.options.is_like_osx {
132 self.cmd.arg("-Wl,--whole-archive")
134 .arg("-Wl,--no-whole-archive");
136 // -force_load is the OSX equivalent of --whole-archive, but it
137 // involves passing the full path to the library to link.
138 let mut v = OsString::from("-Wl,-force_load,");
139 v.push(&archive::find_library(lib, search_path, &self.sess));
144 fn link_whole_rlib(&mut self, lib: &Path) {
145 if self.sess.target.target.options.is_like_osx {
146 let mut v = OsString::from("-Wl,-force_load,");
150 self.cmd.arg("-Wl,--whole-archive").arg(lib)
151 .arg("-Wl,--no-whole-archive");
155 fn gc_sections(&mut self, keep_metadata: bool) {
156 // The dead_strip option to the linker specifies that functions and data
157 // unreachable by the entry point will be removed. This is quite useful
158 // with Rust's compilation model of compiling libraries at a time into
159 // one object file. For example, this brings hello world from 1.7MB to
162 // Note that this is done for both executables and dynamic libraries. We
163 // won't get much benefit from dylibs because LLVM will have already
164 // stripped away as much as it could. This has not been seen to impact
165 // link times negatively.
167 // -dead_strip can't be part of the pre_link_args because it's also used
168 // for partial linking when using multiple codegen units (-r). So we
170 if self.sess.target.target.options.is_like_osx {
171 self.cmd.arg("-Wl,-dead_strip");
172 } else if self.sess.target.target.options.is_like_solaris {
173 self.cmd.arg("-Wl,-z");
174 self.cmd.arg("-Wl,ignore");
176 // If we're building a dylib, we don't use --gc-sections because LLVM
177 // has already done the best it can do, and we also don't want to
178 // eliminate the metadata. If we're building an executable, however,
179 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
181 } else if !keep_metadata {
182 self.cmd.arg("-Wl,--gc-sections");
186 fn optimize(&mut self) {
187 if !self.sess.target.target.options.linker_is_gnu { return }
189 // GNU-style linkers support optimization with -O. GNU ld doesn't
190 // need a numeric argument, but other linkers do.
191 if self.sess.opts.optimize == config::OptLevel::Default ||
192 self.sess.opts.optimize == config::OptLevel::Aggressive {
193 self.cmd.arg("-Wl,-O1");
197 fn debuginfo(&mut self) {
198 // Don't do anything special here for GNU-style linkers.
201 fn no_default_libraries(&mut self) {
202 self.cmd.arg("-nodefaultlibs");
205 fn build_dylib(&mut self, out_filename: &Path) {
206 // On mac we need to tell the linker to let this library be rpathed
207 if self.sess.target.target.options.is_like_osx {
208 self.cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
210 if self.sess.opts.cg.rpath {
211 let mut v = OsString::from("-Wl,-install_name,@rpath/");
212 v.push(out_filename.file_name().unwrap());
216 self.cmd.arg("-shared");
220 fn whole_archives(&mut self) {
221 if !self.takes_hints() { return }
222 self.cmd.arg("-Wl,--whole-archive");
225 fn no_whole_archives(&mut self) {
226 if !self.takes_hints() { return }
227 self.cmd.arg("-Wl,--no-whole-archive");
230 fn hint_static(&mut self) {
231 if !self.takes_hints() { return }
232 self.cmd.arg("-Wl,-Bstatic");
235 fn hint_dynamic(&mut self) {
236 if !self.takes_hints() { return }
237 self.cmd.arg("-Wl,-Bdynamic");
240 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) {
241 // If we're compiling a dylib, then we let symbol visibility in object
242 // files to take care of whether they're exported or not.
244 // If we're compiling a cdylib, however, we manually create a list of
245 // exported symbols to ensure we don't expose any more. The object files
246 // have far more public symbols than we actually want to export, so we
247 // hide them all here.
248 if crate_type == CrateType::CrateTypeDylib ||
249 crate_type == CrateType::CrateTypeProcMacro {
253 let mut arg = OsString::new();
254 let path = tmpdir.join("list");
256 debug!("EXPORTED SYMBOLS:");
258 if self.sess.target.target.options.is_like_osx {
259 // Write a plain, newline-separated list of symbols
260 let res = (|| -> io::Result<()> {
261 let mut f = BufWriter::new(File::create(&path)?);
262 for sym in self.info.exports[&crate_type].iter() {
264 writeln!(f, "_{}", sym)?;
268 if let Err(e) = res {
269 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
272 // Write an LD version script
273 let res = (|| -> io::Result<()> {
274 let mut f = BufWriter::new(File::create(&path)?);
275 writeln!(f, "{{\n global:")?;
276 for sym in self.info.exports[&crate_type].iter() {
278 writeln!(f, " {};", sym)?;
280 writeln!(f, "\n local:\n *;\n}};")?;
283 if let Err(e) = res {
284 self.sess.fatal(&format!("failed to write version script: {}", e));
288 if self.sess.target.target.options.is_like_osx {
289 arg.push("-Wl,-exported_symbols_list,");
290 } else if self.sess.target.target.options.is_like_solaris {
293 arg.push("-Wl,--version-script=");
300 fn subsystem(&mut self, subsystem: &str) {
301 self.cmd.arg(&format!("-Wl,--subsystem,{}", subsystem));
305 pub struct MsvcLinker<'a> {
306 cmd: &'a mut Command,
311 impl<'a> Linker for MsvcLinker<'a> {
312 fn link_rlib(&mut self, lib: &Path) { self.cmd.arg(lib); }
313 fn add_object(&mut self, path: &Path) { self.cmd.arg(path); }
314 fn args(&mut self, args: &[String]) { self.cmd.args(args); }
316 fn build_dylib(&mut self, out_filename: &Path) {
317 self.cmd.arg("/DLL");
318 let mut arg: OsString = "/IMPLIB:".into();
319 arg.push(out_filename.with_extension("dll.lib"));
323 fn gc_sections(&mut self, _keep_metadata: bool) {
324 self.cmd.arg("/OPT:REF,ICF");
327 fn link_dylib(&mut self, lib: &str) {
328 self.cmd.arg(&format!("{}.lib", lib));
331 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
332 // When producing a dll, the MSVC linker may not actually emit a
333 // `foo.lib` file if the dll doesn't actually export any symbols, so we
334 // check to see if the file is there and just omit linking to it if it's
336 let name = format!("{}.dll.lib", lib);
337 if fs::metadata(&path.join(&name)).is_ok() {
342 fn link_staticlib(&mut self, lib: &str) {
343 self.cmd.arg(&format!("{}.lib", lib));
346 fn position_independent_executable(&mut self) {
350 fn no_default_libraries(&mut self) {
351 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
352 // as there's been trouble in the past of linking the C++ standard
353 // library required by LLVM. This likely needs to happen one day, but
354 // in general Windows is also a more controlled environment than
355 // Unix, so it's not necessarily as critical that this be implemented.
357 // Note that there are also some licensing worries about statically
358 // linking some libraries which require a specific agreement, so it may
359 // not ever be possible for us to pass this flag.
362 fn include_path(&mut self, path: &Path) {
363 let mut arg = OsString::from("/LIBPATH:");
368 fn output_filename(&mut self, path: &Path) {
369 let mut arg = OsString::from("/OUT:");
374 fn framework_path(&mut self, _path: &Path) {
375 bug!("frameworks are not supported on windows")
377 fn link_framework(&mut self, _framework: &str) {
378 bug!("frameworks are not supported on windows")
381 fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
383 self.link_staticlib(lib);
385 fn link_whole_rlib(&mut self, path: &Path) {
387 self.link_rlib(path);
389 fn optimize(&mut self) {
390 // Needs more investigation of `/OPT` arguments
393 fn debuginfo(&mut self) {
394 // This will cause the Microsoft linker to generate a PDB file
395 // from the CodeView line tables in the object files.
396 self.cmd.arg("/DEBUG");
399 fn whole_archives(&mut self) {
400 // hints not supported?
402 fn no_whole_archives(&mut self) {
403 // hints not supported?
406 // On windows static libraries are of the form `foo.lib` and dynamic
407 // libraries are not linked against directly, but rather through their
408 // import libraries also called `foo.lib`. As a result there's no
409 // possibility for a native library to appear both dynamically and
410 // statically in the same folder so we don't have to worry about hints like
411 // we do on Unix platforms.
412 fn hint_static(&mut self) {}
413 fn hint_dynamic(&mut self) {}
415 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
416 // export symbols from a dynamic library. When building a dynamic library,
417 // however, we're going to want some symbols exported, so this function
418 // generates a DEF file which lists all the symbols.
420 // The linker will read this `*.def` file and export all the symbols from
421 // the dynamic library. Note that this is not as simple as just exporting
422 // all the symbols in the current crate (as specified by `trans.reachable`)
423 // but rather we also need to possibly export the symbols of upstream
424 // crates. Upstream rlibs may be linked statically to this dynamic library,
425 // in which case they may continue to transitively be used and hence need
426 // their symbols exported.
427 fn export_symbols(&mut self,
429 crate_type: CrateType) {
430 let path = tmpdir.join("lib.def");
431 let res = (|| -> io::Result<()> {
432 let mut f = BufWriter::new(File::create(&path)?);
434 // Start off with the standard module name header and then go
435 // straight to exports.
436 writeln!(f, "LIBRARY")?;
437 writeln!(f, "EXPORTS")?;
438 for symbol in self.info.exports[&crate_type].iter() {
439 writeln!(f, " {}", symbol)?;
443 if let Err(e) = res {
444 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
446 let mut arg = OsString::from("/DEF:");
451 fn subsystem(&mut self, subsystem: &str) {
452 // Note that previous passes of the compiler validated this subsystem,
453 // so we just blindly pass it to the linker.
454 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
456 // Windows has two subsystems we're interested in right now, the console
457 // and windows subsystems. These both implicitly have different entry
458 // points (starting symbols). The console entry point starts with
459 // `mainCRTStartup` and the windows entry point starts with
460 // `WinMainCRTStartup`. These entry points, defined in system libraries,
461 // will then later probe for either `main` or `WinMain`, respectively to
462 // start the application.
464 // In Rust we just always generate a `main` function so we want control
465 // to always start there, so we force the entry point on the windows
466 // subsystem to be `mainCRTStartup` to get everything booted up
469 // For more information see RFC #1665
470 if subsystem == "windows" {
471 self.cmd.arg("/ENTRY:mainCRTStartup");
476 fn exported_symbols(scx: &SharedCrateContext,
477 exported_symbols: &ExportedSymbols,
478 crate_type: CrateType)
480 let export_threshold = symbol_export::crate_export_threshold(crate_type);
482 let mut symbols = Vec::new();
483 exported_symbols.for_each_exported_symbol(LOCAL_CRATE, export_threshold, |name, _| {
484 symbols.push(name.to_owned());
487 let formats = scx.sess().dependency_formats.borrow();
488 let deps = formats[&crate_type].iter();
490 for (index, dep_format) in deps.enumerate() {
491 let cnum = CrateNum::new(index + 1);
492 // For each dependency that we are linking to statically ...
493 if *dep_format == Linkage::Static {
494 // ... we add its symbol list to our export list.
495 exported_symbols.for_each_exported_symbol(cnum, export_threshold, |name, _| {
496 symbols.push(name.to_owned());