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
;
20 use monomorphize
::Instance
;
23 use middle
::dependency_format
::Linkage
;
24 use rustc
::hir
::def_id
::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 reachable
: &[String
]) -> LinkerInfo
{
39 exports
: scx
.sess().crate_types
.borrow().iter().map(|&c
| {
40 (c
, exported_symbols(scx
, reachable
, 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 if self.sess
.target
.target
.options
.is_like_solaris
{
257 let res
= (|| -> io
::Result
<()> {
258 let mut f
= BufWriter
::new(File
::create(&path
)?
);
259 writeln
!(f
, "{{\n global:")?
;
260 for sym
in self.info
.exports
[&crate_type
].iter() {
261 writeln
!(f
, " {};", sym
)?
;
263 writeln
!(f
, "\n local:\n *;\n}};")?
;
266 if let Err(e
) = res
{
267 self.sess
.fatal(&format
!("failed to write version script: {}", e
));
273 let prefix
= if self.sess
.target
.target
.options
.is_like_osx
{
278 let res
= (|| -> io
::Result
<()> {
279 let mut f
= BufWriter
::new(File
::create(&path
)?
);
280 for sym
in self.info
.exports
[&crate_type
].iter() {
281 writeln
!(f
, "{}{}", prefix
, sym
)?
;
285 if let Err(e
) = res
{
286 self.sess
.fatal(&format
!("failed to write lib.def file: {}", e
));
288 if self.sess
.target
.target
.options
.is_like_osx
{
289 arg
.push("-Wl,-exported_symbols_list,");
291 arg
.push("-Wl,--retain-symbols-file=");
299 fn subsystem(&mut self, subsystem
: &str) {
300 self.cmd
.arg(&format
!("-Wl,--subsystem,{}", subsystem
));
304 pub struct MsvcLinker
<'a
> {
305 cmd
: &'a
mut Command
,
310 impl<'a
> Linker
for MsvcLinker
<'a
> {
311 fn link_rlib(&mut self, lib
: &Path
) { self.cmd.arg(lib); }
312 fn add_object(&mut self, path
: &Path
) { self.cmd.arg(path); }
313 fn args(&mut self, args
: &[String
]) { self.cmd.args(args); }
315 fn build_dylib(&mut self, out_filename
: &Path
) {
316 self.cmd
.arg("/DLL");
317 let mut arg
: OsString
= "/IMPLIB:".into();
318 arg
.push(out_filename
.with_extension("dll.lib"));
322 fn gc_sections(&mut self, _keep_metadata
: bool
) {
323 self.cmd
.arg("/OPT:REF,ICF");
326 fn link_dylib(&mut self, lib
: &str) {
327 self.cmd
.arg(&format
!("{}.lib", lib
));
330 fn link_rust_dylib(&mut self, lib
: &str, path
: &Path
) {
331 // When producing a dll, the MSVC linker may not actually emit a
332 // `foo.lib` file if the dll doesn't actually export any symbols, so we
333 // check to see if the file is there and just omit linking to it if it's
335 let name
= format
!("{}.dll.lib", lib
);
336 if fs
::metadata(&path
.join(&name
)).is_ok() {
341 fn link_staticlib(&mut self, lib
: &str) {
342 self.cmd
.arg(&format
!("{}.lib", lib
));
345 fn position_independent_executable(&mut self) {
349 fn no_default_libraries(&mut self) {
350 // Currently we don't pass the /NODEFAULTLIB flag to the linker on MSVC
351 // as there's been trouble in the past of linking the C++ standard
352 // library required by LLVM. This likely needs to happen one day, but
353 // in general Windows is also a more controlled environment than
354 // Unix, so it's not necessarily as critical that this be implemented.
356 // Note that there are also some licensing worries about statically
357 // linking some libraries which require a specific agreement, so it may
358 // not ever be possible for us to pass this flag.
361 fn include_path(&mut self, path
: &Path
) {
362 let mut arg
= OsString
::from("/LIBPATH:");
367 fn output_filename(&mut self, path
: &Path
) {
368 let mut arg
= OsString
::from("/OUT:");
373 fn framework_path(&mut self, _path
: &Path
) {
374 bug
!("frameworks are not supported on windows")
376 fn link_framework(&mut self, _framework
: &str) {
377 bug
!("frameworks are not supported on windows")
380 fn link_whole_staticlib(&mut self, lib
: &str, _search_path
: &[PathBuf
]) {
382 self.link_staticlib(lib
);
384 fn link_whole_rlib(&mut self, path
: &Path
) {
386 self.link_rlib(path
);
388 fn optimize(&mut self) {
389 // Needs more investigation of `/OPT` arguments
392 fn debuginfo(&mut self) {
393 // This will cause the Microsoft linker to generate a PDB file
394 // from the CodeView line tables in the object files.
395 self.cmd
.arg("/DEBUG");
398 fn whole_archives(&mut self) {
399 // hints not supported?
401 fn no_whole_archives(&mut self) {
402 // hints not supported?
405 // On windows static libraries are of the form `foo.lib` and dynamic
406 // libraries are not linked against directly, but rather through their
407 // import libraries also called `foo.lib`. As a result there's no
408 // possibility for a native library to appear both dynamically and
409 // statically in the same folder so we don't have to worry about hints like
410 // we do on Unix platforms.
411 fn hint_static(&mut self) {}
412 fn hint_dynamic(&mut self) {}
414 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
415 // export symbols from a dynamic library. When building a dynamic library,
416 // however, we're going to want some symbols exported, so this function
417 // generates a DEF file which lists all the symbols.
419 // The linker will read this `*.def` file and export all the symbols from
420 // the dynamic library. Note that this is not as simple as just exporting
421 // all the symbols in the current crate (as specified by `trans.reachable`)
422 // but rather we also need to possibly export the symbols of upstream
423 // crates. Upstream rlibs may be linked statically to this dynamic library,
424 // in which case they may continue to transitively be used and hence need
425 // their symbols exported.
426 fn export_symbols(&mut self,
428 crate_type
: CrateType
) {
429 let path
= tmpdir
.join("lib.def");
430 let res
= (|| -> io
::Result
<()> {
431 let mut f
= BufWriter
::new(File
::create(&path
)?
);
433 // Start off with the standard module name header and then go
434 // straight to exports.
435 writeln
!(f
, "LIBRARY")?
;
436 writeln
!(f
, "EXPORTS")?
;
437 for symbol
in self.info
.exports
[&crate_type
].iter() {
438 writeln
!(f
, " {}", symbol
)?
;
442 if let Err(e
) = res
{
443 self.sess
.fatal(&format
!("failed to write lib.def file: {}", e
));
445 let mut arg
= OsString
::from("/DEF:");
450 fn subsystem(&mut self, subsystem
: &str) {
451 // Note that previous passes of the compiler validated this subsystem,
452 // so we just blindly pass it to the linker.
453 self.cmd
.arg(&format
!("/SUBSYSTEM:{}", subsystem
));
455 // Windows has two subsystems we're interested in right now, the console
456 // and windows subsystems. These both implicitly have different entry
457 // points (starting symbols). The console entry point starts with
458 // `mainCRTStartup` and the windows entry point starts with
459 // `WinMainCRTStartup`. These entry points, defined in system libraries,
460 // will then later probe for either `main` or `WinMain`, respectively to
461 // start the application.
463 // In Rust we just always generate a `main` function so we want control
464 // to always start there, so we force the entry point on the windows
465 // subsystem to be `mainCRTStartup` to get everything booted up
468 // For more information see RFC #1665
469 if subsystem
== "windows" {
470 self.cmd
.arg("/ENTRY:mainCRTStartup");
475 fn exported_symbols(scx
: &SharedCrateContext
,
476 reachable
: &[String
],
477 crate_type
: CrateType
)
479 // See explanation in GnuLinker::export_symbols, for
480 // why we don't ever need dylib symbols on non-MSVC.
481 if crate_type
== CrateType
::CrateTypeDylib
||
482 crate_type
== CrateType
::CrateTypeProcMacro
{
483 if !scx
.sess().target
.target
.options
.is_like_msvc
{
488 let mut symbols
= reachable
.to_vec();
490 // If we're producing anything other than a dylib then the `reachable` array
491 // above is the exhaustive set of symbols we should be exporting.
493 // For dylibs, however, we need to take a look at how all upstream crates
494 // are linked into this dynamic library. For all statically linked
495 // libraries we take all their reachable symbols and emit them as well.
496 if crate_type
!= CrateType
::CrateTypeDylib
{
500 let cstore
= &scx
.sess().cstore
;
501 let formats
= scx
.sess().dependency_formats
.borrow();
502 let deps
= formats
[&crate_type
].iter();
503 symbols
.extend(deps
.enumerate().filter_map(|(i
, f
)| {
504 if *f
== Linkage
::Static
{
505 Some(CrateNum
::new(i
+ 1))
510 cstore
.reachable_ids(cnum
)
511 }).map(|did
| -> String
{
512 Instance
::mono(scx
, did
).symbol_name(scx
)