]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/linker.rs
Linking: Include export lists in debug output.
[rust.git] / src / librustc_trans / 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 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;
18
19 use context::SharedCrateContext;
20
21 use back::archive;
22 use back::symbol_export::{self, ExportedSymbols};
23 use middle::dependency_format::Linkage;
24 use rustc::hir::def_id::{LOCAL_CRATE, CrateNum};
25 use session::Session;
26 use session::config::CrateType;
27 use session::config;
28
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>>,
33 }
34
35 impl<'a, 'tcx> LinkerInfo {
36     pub fn new(scx: &SharedCrateContext<'a, 'tcx>,
37                exports: &ExportedSymbols) -> LinkerInfo {
38         LinkerInfo {
39             exports: scx.sess().crate_types.borrow().iter().map(|&c| {
40                 (c, exported_symbols(scx, exports, c))
41             }).collect(),
42         }
43     }
44
45     pub fn to_linker(&'a self,
46                      cmd: &'a mut Command,
47                      sess: &'a Session) -> Box<Linker+'a> {
48         if sess.target.target.options.is_like_msvc {
49             Box::new(MsvcLinker {
50                 cmd: cmd,
51                 sess: sess,
52                 info: self
53             }) as Box<Linker>
54         } else {
55             Box::new(GnuLinker {
56                 cmd: cmd,
57                 sess: sess,
58                 info: self
59             }) as Box<Linker>
60         }
61     }
62 }
63
64 /// Linker abstraction used by back::link to build up the command to invoke a
65 /// linker.
66 ///
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.
71 pub trait Linker {
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);
96 }
97
98 pub struct GnuLinker<'a> {
99     cmd: &'a mut Command,
100     sess: &'a Session,
101     info: &'a LinkerInfo
102 }
103
104 impl<'a> GnuLinker<'a> {
105     fn takes_hints(&self) -> bool {
106         !self.sess.target.target.options.is_like_osx
107     }
108 }
109
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); }
120
121     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
122         self.cmd.arg("-l").arg(lib);
123     }
124
125     fn link_framework(&mut self, framework: &str) {
126         self.cmd.arg("-framework").arg(framework);
127     }
128
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")
133                     .arg("-l").arg(lib)
134                     .arg("-Wl,--no-whole-archive");
135         } else {
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));
140             self.cmd.arg(&v);
141         }
142     }
143
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,");
147             v.push(lib);
148             self.cmd.arg(&v);
149         } else {
150             self.cmd.arg("-Wl,--whole-archive").arg(lib)
151                     .arg("-Wl,--no-whole-archive");
152         }
153     }
154
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
160         // 458K.
161         //
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.
166         //
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
169         // insert it here.
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");
175
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%
180         // reduction.
181         } else if !keep_metadata {
182             self.cmd.arg("-Wl,--gc-sections");
183         }
184     }
185
186     fn optimize(&mut self) {
187         if !self.sess.target.target.options.linker_is_gnu { return }
188
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");
194         }
195     }
196
197     fn debuginfo(&mut self) {
198         // Don't do anything special here for GNU-style linkers.
199     }
200
201     fn no_default_libraries(&mut self) {
202         self.cmd.arg("-nodefaultlibs");
203     }
204
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"]);
209
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());
213                 self.cmd.arg(&v);
214             }
215         } else {
216             self.cmd.arg("-shared");
217         }
218     }
219
220     fn whole_archives(&mut self) {
221         if !self.takes_hints() { return }
222         self.cmd.arg("-Wl,--whole-archive");
223     }
224
225     fn no_whole_archives(&mut self) {
226         if !self.takes_hints() { return }
227         self.cmd.arg("-Wl,--no-whole-archive");
228     }
229
230     fn hint_static(&mut self) {
231         if !self.takes_hints() { return }
232         self.cmd.arg("-Wl,-Bstatic");
233     }
234
235     fn hint_dynamic(&mut self) {
236         if !self.takes_hints() { return }
237         self.cmd.arg("-Wl,-Bdynamic");
238     }
239
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.
243         //
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 {
250             return
251         }
252
253         let mut arg = OsString::new();
254         let path = tmpdir.join("list");
255
256         debug!("EXPORTED SYMBOLS:");
257
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() {
263                     debug!("  _{}", sym);
264                     writeln!(f, "_{}", sym)?;
265                 }
266                 Ok(())
267             })();
268             if let Err(e) = res {
269                 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
270             }
271         } else {
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() {
277                     debug!("    {};", sym);
278                     writeln!(f, "    {};", sym)?;
279                 }
280                 writeln!(f, "\n  local:\n    *;\n}};")?;
281                 Ok(())
282             })();
283             if let Err(e) = res {
284                 self.sess.fatal(&format!("failed to write version script: {}", e));
285             }
286         }
287
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 {
291             arg.push("-Wl,-M,");
292         } else {
293             arg.push("-Wl,--version-script=");
294         }
295
296         arg.push(&path);
297         self.cmd.arg(arg);
298     }
299
300     fn subsystem(&mut self, subsystem: &str) {
301         self.cmd.arg(&format!("-Wl,--subsystem,{}", subsystem));
302     }
303 }
304
305 pub struct MsvcLinker<'a> {
306     cmd: &'a mut Command,
307     sess: &'a Session,
308     info: &'a LinkerInfo
309 }
310
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); }
315
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"));
320         self.cmd.arg(arg);
321     }
322
323     fn gc_sections(&mut self, _keep_metadata: bool) {
324         self.cmd.arg("/OPT:REF,ICF");
325     }
326
327     fn link_dylib(&mut self, lib: &str) {
328         self.cmd.arg(&format!("{}.lib", lib));
329     }
330
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
335         // not present.
336         let name = format!("{}.dll.lib", lib);
337         if fs::metadata(&path.join(&name)).is_ok() {
338             self.cmd.arg(name);
339         }
340     }
341
342     fn link_staticlib(&mut self, lib: &str) {
343         self.cmd.arg(&format!("{}.lib", lib));
344     }
345
346     fn position_independent_executable(&mut self) {
347         // noop
348     }
349
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.
356         //
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.
360     }
361
362     fn include_path(&mut self, path: &Path) {
363         let mut arg = OsString::from("/LIBPATH:");
364         arg.push(path);
365         self.cmd.arg(&arg);
366     }
367
368     fn output_filename(&mut self, path: &Path) {
369         let mut arg = OsString::from("/OUT:");
370         arg.push(path);
371         self.cmd.arg(&arg);
372     }
373
374     fn framework_path(&mut self, _path: &Path) {
375         bug!("frameworks are not supported on windows")
376     }
377     fn link_framework(&mut self, _framework: &str) {
378         bug!("frameworks are not supported on windows")
379     }
380
381     fn link_whole_staticlib(&mut self, lib: &str, _search_path: &[PathBuf]) {
382         // not supported?
383         self.link_staticlib(lib);
384     }
385     fn link_whole_rlib(&mut self, path: &Path) {
386         // not supported?
387         self.link_rlib(path);
388     }
389     fn optimize(&mut self) {
390         // Needs more investigation of `/OPT` arguments
391     }
392
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");
397     }
398
399     fn whole_archives(&mut self) {
400         // hints not supported?
401     }
402     fn no_whole_archives(&mut self) {
403         // hints not supported?
404     }
405
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) {}
414
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.
419     //
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,
428                       tmpdir: &Path,
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)?);
433
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)?;
440             }
441             Ok(())
442         })();
443         if let Err(e) = res {
444             self.sess.fatal(&format!("failed to write lib.def file: {}", e));
445         }
446         let mut arg = OsString::from("/DEF:");
447         arg.push(path);
448         self.cmd.arg(&arg);
449     }
450
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));
455
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.
463         //
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
467         // correctly.
468         //
469         // For more information see RFC #1665
470         if subsystem == "windows" {
471             self.cmd.arg("/ENTRY:mainCRTStartup");
472         }
473     }
474 }
475
476 fn exported_symbols(scx: &SharedCrateContext,
477                     exported_symbols: &ExportedSymbols,
478                     crate_type: CrateType)
479                     -> Vec<String> {
480     let export_threshold = symbol_export::crate_export_threshold(crate_type);
481
482     let mut symbols = Vec::new();
483     exported_symbols.for_each_exported_symbol(LOCAL_CRATE, export_threshold, |name, _| {
484         symbols.push(name.to_owned());
485     });
486
487     let formats = scx.sess().dependency_formats.borrow();
488     let deps = formats[&crate_type].iter();
489
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());
497             })
498         }
499     }
500
501     symbols
502 }