]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/back/link.rs
New upstream version 1.26.0+dfsg1
[rustc.git] / src / librustc_trans / back / link.rs
1 // Copyright 2012-2014 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 back::wasm;
12 use cc::windows_registry;
13 use super::archive::{ArchiveBuilder, ArchiveConfig};
14 use super::bytecode::RLIB_BYTECODE_EXTENSION;
15 use super::linker::Linker;
16 use super::command::Command;
17 use super::rpath::RPathConfig;
18 use super::rpath;
19 use metadata::METADATA_FILENAME;
20 use rustc_back::LinkerFlavor;
21 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType, PrintRequest};
22 use rustc::session::config::{RUST_CGU_EXT, Lto};
23 use rustc::session::filesearch;
24 use rustc::session::search_paths::PathKind;
25 use rustc::session::Session;
26 use rustc::middle::cstore::{NativeLibrary, LibSource, NativeLibraryKind};
27 use rustc::middle::dependency_format::Linkage;
28 use {CrateTranslation, CrateInfo};
29 use rustc::util::common::time;
30 use rustc::util::fs::fix_windows_verbatim_for_gcc;
31 use rustc::hir::def_id::CrateNum;
32 use tempdir::TempDir;
33 use rustc_back::{PanicStrategy, RelroLevel};
34 use rustc_back::target::TargetTriple;
35 use rustc_data_structures::fx::FxHashSet;
36 use context::get_reloc_model;
37 use llvm;
38
39 use std::ascii;
40 use std::char;
41 use std::env;
42 use std::fmt;
43 use std::fs;
44 use std::io;
45 use std::path::{Path, PathBuf};
46 use std::process::{Output, Stdio};
47 use std::str;
48 use syntax::attr;
49
50 /// The LLVM module name containing crate-metadata. This includes a `.` on
51 /// purpose, so it cannot clash with the name of a user-defined module.
52 pub const METADATA_MODULE_NAME: &'static str = "crate.metadata";
53
54 // same as for metadata above, but for allocator shim
55 pub const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator";
56
57 pub use rustc_trans_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
58 invalid_output_for_target, build_link_meta, out_filename,
59 check_file_is_writeable};
60
61 // The third parameter is for env vars, used on windows to set up the
62 // path for MSVC to find its DLLs, and gcc to find its bundled
63 // toolchain
64 pub fn get_linker(sess: &Session) -> (PathBuf, Command) {
65 // If our linker looks like a batch script on Windows then to execute this
66 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
67 // emscripten where the linker is `emcc.bat` and needs to be spawned as
68 // `cmd /c emcc.bat ...`.
69 //
70 // This worked historically but is needed manually since #42436 (regression
71 // was tagged as #42791) and some more info can be found on #44443 for
72 // emscripten itself.
73 let cmd = |linker: &Path| {
74 if let Some(linker) = linker.to_str() {
75 if cfg!(windows) && linker.ends_with(".bat") {
76 return Command::bat_script(linker)
77 }
78 }
79 match sess.linker_flavor() {
80 LinkerFlavor::Lld(f) => Command::lld(linker, f),
81 _ => Command::new(linker),
82
83 }
84 };
85
86 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
87
88 let linker_path = sess.opts.cg.linker.as_ref().map(|s| &**s)
89 .or(sess.target.target.options.linker.as_ref().map(|s| s.as_ref()))
90 .unwrap_or(match sess.linker_flavor() {
91 LinkerFlavor::Msvc => {
92 msvc_tool.as_ref().map(|t| t.path()).unwrap_or("link.exe".as_ref())
93 }
94 LinkerFlavor::Em if cfg!(windows) => "emcc.bat".as_ref(),
95 LinkerFlavor::Em => "emcc".as_ref(),
96 LinkerFlavor::Gcc => "cc".as_ref(),
97 LinkerFlavor::Ld => "ld".as_ref(),
98 LinkerFlavor::Lld(_) => "lld".as_ref(),
99 });
100
101 let mut cmd = cmd(linker_path);
102
103 // The compiler's sysroot often has some bundled tools, so add it to the
104 // PATH for the child.
105 let mut new_path = sess.host_filesearch(PathKind::All)
106 .get_tools_search_paths();
107 let mut msvc_changed_path = false;
108 if sess.target.target.options.is_like_msvc {
109 if let Some(ref tool) = msvc_tool {
110 cmd.args(tool.args());
111 for &(ref k, ref v) in tool.env() {
112 if k == "PATH" {
113 new_path.extend(env::split_paths(v));
114 msvc_changed_path = true;
115 } else {
116 cmd.env(k, v);
117 }
118 }
119 }
120 }
121
122 if !msvc_changed_path {
123 if let Some(path) = env::var_os("PATH") {
124 new_path.extend(env::split_paths(&path));
125 }
126 }
127 cmd.env("PATH", env::join_paths(new_path).unwrap());
128
129 (linker_path.to_path_buf(), cmd)
130 }
131
132 pub fn remove(sess: &Session, path: &Path) {
133 match fs::remove_file(path) {
134 Ok(..) => {}
135 Err(e) => {
136 sess.err(&format!("failed to remove {}: {}",
137 path.display(),
138 e));
139 }
140 }
141 }
142
143 /// Perform the linkage portion of the compilation phase. This will generate all
144 /// of the requested outputs for this compilation session.
145 pub(crate) fn link_binary(sess: &Session,
146 trans: &CrateTranslation,
147 outputs: &OutputFilenames,
148 crate_name: &str) -> Vec<PathBuf> {
149 let mut out_filenames = Vec::new();
150 for &crate_type in sess.crate_types.borrow().iter() {
151 // Ignore executable crates if we have -Z no-trans, as they will error.
152 if (sess.opts.debugging_opts.no_trans ||
153 !sess.opts.output_types.should_trans()) &&
154 crate_type == config::CrateTypeExecutable {
155 continue;
156 }
157
158 if invalid_output_for_target(sess, crate_type) {
159 bug!("invalid output type `{:?}` for target os `{}`",
160 crate_type, sess.opts.target_triple);
161 }
162 let mut out_files = link_binary_output(sess,
163 trans,
164 crate_type,
165 outputs,
166 crate_name);
167 out_filenames.append(&mut out_files);
168 }
169
170 // Remove the temporary object file and metadata if we aren't saving temps
171 if !sess.opts.cg.save_temps {
172 if sess.opts.output_types.should_trans() &&
173 !preserve_objects_for_their_debuginfo(sess)
174 {
175 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
176 remove(sess, obj);
177 }
178 }
179 for obj in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
180 remove(sess, obj);
181 }
182 if let Some(ref obj) = trans.metadata_module.object {
183 remove(sess, obj);
184 }
185 if let Some(ref allocator) = trans.allocator_module {
186 if let Some(ref obj) = allocator.object {
187 remove(sess, obj);
188 }
189 if let Some(ref bc) = allocator.bytecode_compressed {
190 remove(sess, bc);
191 }
192 }
193 }
194
195 out_filenames
196 }
197
198 /// Returns a boolean indicating whether we should preserve the object files on
199 /// the filesystem for their debug information. This is often useful with
200 /// split-dwarf like schemes.
201 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
202 // If the objects don't have debuginfo there's nothing to preserve.
203 if sess.opts.debuginfo == NoDebugInfo {
204 return false
205 }
206
207 // If we're only producing artifacts that are archives, no need to preserve
208 // the objects as they're losslessly contained inside the archives.
209 let output_linked = sess.crate_types.borrow()
210 .iter()
211 .any(|x| *x != config::CrateTypeRlib && *x != config::CrateTypeStaticlib);
212 if !output_linked {
213 return false
214 }
215
216 // If we're on OSX then the equivalent of split dwarf is turned on by
217 // default. The final executable won't actually have any debug information
218 // except it'll have pointers to elsewhere. Historically we've always run
219 // `dsymutil` to "link all the dwarf together" but this is actually sort of
220 // a bummer for incremental compilation! (the whole point of split dwarf is
221 // that you don't do this sort of dwarf link).
222 //
223 // Basically as a result this just means that if we're on OSX and we're
224 // *not* running dsymutil then the object files are the only source of truth
225 // for debug information, so we must preserve them.
226 if sess.target.target.options.is_like_osx {
227 match sess.opts.debugging_opts.run_dsymutil {
228 // dsymutil is not being run, preserve objects
229 Some(false) => return true,
230
231 // dsymutil is being run, no need to preserve the objects
232 Some(true) => return false,
233
234 // The default historical behavior was to always run dsymutil, so
235 // we're preserving that temporarily, but we're likely to switch the
236 // default soon.
237 None => return false,
238 }
239 }
240
241 false
242 }
243
244 fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilenames) -> PathBuf {
245 let out_filename = outputs.single_output_file.clone()
246 .unwrap_or(outputs
247 .out_directory
248 .join(&format!("lib{}{}.rmeta", crate_name, sess.opts.cg.extra_filename)));
249 check_file_is_writeable(&out_filename, sess);
250 out_filename
251 }
252
253 pub(crate) fn each_linked_rlib(sess: &Session,
254 info: &CrateInfo,
255 f: &mut FnMut(CrateNum, &Path)) -> Result<(), String> {
256 let crates = info.used_crates_static.iter();
257 let fmts = sess.dependency_formats.borrow();
258 let fmts = fmts.get(&config::CrateTypeExecutable)
259 .or_else(|| fmts.get(&config::CrateTypeStaticlib))
260 .or_else(|| fmts.get(&config::CrateTypeCdylib))
261 .or_else(|| fmts.get(&config::CrateTypeProcMacro));
262 let fmts = match fmts {
263 Some(f) => f,
264 None => return Err(format!("could not find formats for rlibs"))
265 };
266 for &(cnum, ref path) in crates {
267 match fmts.get(cnum.as_usize() - 1) {
268 Some(&Linkage::NotLinked) |
269 Some(&Linkage::IncludedFromDylib) => continue,
270 Some(_) => {}
271 None => return Err(format!("could not find formats for rlibs"))
272 }
273 let name = &info.crate_name[&cnum];
274 let path = match *path {
275 LibSource::Some(ref p) => p,
276 LibSource::MetadataOnly => {
277 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
278 name))
279 }
280 LibSource::None => {
281 return Err(format!("could not find rlib for: `{}`", name))
282 }
283 };
284 f(cnum, &path);
285 }
286 Ok(())
287 }
288
289 /// Returns a boolean indicating whether the specified crate should be ignored
290 /// during LTO.
291 ///
292 /// Crates ignored during LTO are not lumped together in the "massive object
293 /// file" that we create and are linked in their normal rlib states. See
294 /// comments below for what crates do not participate in LTO.
295 ///
296 /// It's unusual for a crate to not participate in LTO. Typically only
297 /// compiler-specific and unstable crates have a reason to not participate in
298 /// LTO.
299 pub(crate) fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
300 // If our target enables builtin function lowering in LLVM then the
301 // crates providing these functions don't participate in LTO (e.g.
302 // no_builtins or compiler builtins crates).
303 !sess.target.target.options.no_builtins &&
304 (info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum))
305 }
306
307 fn link_binary_output(sess: &Session,
308 trans: &CrateTranslation,
309 crate_type: config::CrateType,
310 outputs: &OutputFilenames,
311 crate_name: &str) -> Vec<PathBuf> {
312 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
313 check_file_is_writeable(obj, sess);
314 }
315
316 let mut out_filenames = vec![];
317
318 if outputs.outputs.contains_key(&OutputType::Metadata) {
319 let out_filename = filename_for_metadata(sess, crate_name, outputs);
320 // To avoid races with another rustc process scanning the output directory,
321 // we need to write the file somewhere else and atomically move it to its
322 // final destination, with a `fs::rename` call. In order for the rename to
323 // always succeed, the temporary file needs to be on the same filesystem,
324 // which is why we create it inside the output directory specifically.
325 let metadata_tmpdir = match TempDir::new_in(out_filename.parent().unwrap(), "rmeta") {
326 Ok(tmpdir) => tmpdir,
327 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
328 };
329 let metadata = emit_metadata(sess, trans, &metadata_tmpdir);
330 if let Err(e) = fs::rename(metadata, &out_filename) {
331 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
332 }
333 out_filenames.push(out_filename);
334 }
335
336 let tmpdir = match TempDir::new("rustc") {
337 Ok(tmpdir) => tmpdir,
338 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
339 };
340
341 if outputs.outputs.should_trans() {
342 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
343 match crate_type {
344 config::CrateTypeRlib => {
345 link_rlib(sess,
346 trans,
347 RlibFlavor::Normal,
348 &out_filename,
349 &tmpdir).build();
350 }
351 config::CrateTypeStaticlib => {
352 link_staticlib(sess, trans, &out_filename, &tmpdir);
353 }
354 _ => {
355 link_natively(sess, crate_type, &out_filename, trans, tmpdir.path());
356 }
357 }
358 out_filenames.push(out_filename);
359 }
360
361 if sess.opts.cg.save_temps {
362 let _ = tmpdir.into_path();
363 }
364
365 out_filenames
366 }
367
368 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
369 let mut search = Vec::new();
370 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
371 search.push(path.to_path_buf());
372 });
373 return search;
374 }
375
376 fn archive_config<'a>(sess: &'a Session,
377 output: &Path,
378 input: Option<&Path>) -> ArchiveConfig<'a> {
379 ArchiveConfig {
380 sess,
381 dst: output.to_path_buf(),
382 src: input.map(|p| p.to_path_buf()),
383 lib_search_paths: archive_search_paths(sess),
384 }
385 }
386
387 /// We use a temp directory here to avoid races between concurrent rustc processes,
388 /// such as builds in the same directory using the same filename for metadata while
389 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
390 /// directory being searched for `extern crate` (observing an incomplete file).
391 /// The returned path is the temporary file containing the complete metadata.
392 fn emit_metadata<'a>(sess: &'a Session, trans: &CrateTranslation, tmpdir: &TempDir)
393 -> PathBuf {
394 let out_filename = tmpdir.path().join(METADATA_FILENAME);
395 let result = fs::write(&out_filename, &trans.metadata.raw_data);
396
397 if let Err(e) = result {
398 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
399 }
400
401 out_filename
402 }
403
404 enum RlibFlavor {
405 Normal,
406 StaticlibBase,
407 }
408
409 // Create an 'rlib'
410 //
411 // An rlib in its current incarnation is essentially a renamed .a file. The
412 // rlib primarily contains the object file of the crate, but it also contains
413 // all of the object files from native libraries. This is done by unzipping
414 // native libraries and inserting all of the contents into this archive.
415 fn link_rlib<'a>(sess: &'a Session,
416 trans: &CrateTranslation,
417 flavor: RlibFlavor,
418 out_filename: &Path,
419 tmpdir: &TempDir) -> ArchiveBuilder<'a> {
420 info!("preparing rlib to {:?}", out_filename);
421 let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
422
423 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
424 ab.add_file(obj);
425 }
426
427 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
428 // we may not be configured to actually include a static library if we're
429 // adding it here. That's because later when we consume this rlib we'll
430 // decide whether we actually needed the static library or not.
431 //
432 // To do this "correctly" we'd need to keep track of which libraries added
433 // which object files to the archive. We don't do that here, however. The
434 // #[link(cfg(..))] feature is unstable, though, and only intended to get
435 // liblibc working. In that sense the check below just indicates that if
436 // there are any libraries we want to omit object files for at link time we
437 // just exclude all custom object files.
438 //
439 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
440 // feature then we'll need to figure out how to record what objects were
441 // loaded from the libraries found here and then encode that into the
442 // metadata of the rlib we're generating somehow.
443 for lib in trans.crate_info.used_libraries.iter() {
444 match lib.kind {
445 NativeLibraryKind::NativeStatic => {}
446 NativeLibraryKind::NativeStaticNobundle |
447 NativeLibraryKind::NativeFramework |
448 NativeLibraryKind::NativeUnknown => continue,
449 }
450 ab.add_native_library(&lib.name.as_str());
451 }
452
453 // After adding all files to the archive, we need to update the
454 // symbol table of the archive.
455 ab.update_symbols();
456
457 // Note that it is important that we add all of our non-object "magical
458 // files" *after* all of the object files in the archive. The reason for
459 // this is as follows:
460 //
461 // * When performing LTO, this archive will be modified to remove
462 // objects from above. The reason for this is described below.
463 //
464 // * When the system linker looks at an archive, it will attempt to
465 // determine the architecture of the archive in order to see whether its
466 // linkable.
467 //
468 // The algorithm for this detection is: iterate over the files in the
469 // archive. Skip magical SYMDEF names. Interpret the first file as an
470 // object file. Read architecture from the object file.
471 //
472 // * As one can probably see, if "metadata" and "foo.bc" were placed
473 // before all of the objects, then the architecture of this archive would
474 // not be correctly inferred once 'foo.o' is removed.
475 //
476 // Basically, all this means is that this code should not move above the
477 // code above.
478 match flavor {
479 RlibFlavor::Normal => {
480 // Instead of putting the metadata in an object file section, rlibs
481 // contain the metadata in a separate file.
482 ab.add_file(&emit_metadata(sess, trans, tmpdir));
483
484 // For LTO purposes, the bytecode of this library is also inserted
485 // into the archive.
486 for bytecode in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
487 ab.add_file(bytecode);
488 }
489
490 // After adding all files to the archive, we need to update the
491 // symbol table of the archive. This currently dies on macOS (see
492 // #11162), and isn't necessary there anyway
493 if !sess.target.target.options.is_like_osx {
494 ab.update_symbols();
495 }
496 }
497
498 RlibFlavor::StaticlibBase => {
499 let obj = trans.allocator_module
500 .as_ref()
501 .and_then(|m| m.object.as_ref());
502 if let Some(obj) = obj {
503 ab.add_file(obj);
504 }
505 }
506 }
507
508 ab
509 }
510
511 // Create a static archive
512 //
513 // This is essentially the same thing as an rlib, but it also involves adding
514 // all of the upstream crates' objects into the archive. This will slurp in
515 // all of the native libraries of upstream dependencies as well.
516 //
517 // Additionally, there's no way for us to link dynamic libraries, so we warn
518 // about all dynamic library dependencies that they're not linked in.
519 //
520 // There's no need to include metadata in a static archive, so ensure to not
521 // link in the metadata object file (and also don't prepare the archive with a
522 // metadata file).
523 fn link_staticlib(sess: &Session,
524 trans: &CrateTranslation,
525 out_filename: &Path,
526 tempdir: &TempDir) {
527 let mut ab = link_rlib(sess,
528 trans,
529 RlibFlavor::StaticlibBase,
530 out_filename,
531 tempdir);
532 let mut all_native_libs = vec![];
533
534 let res = each_linked_rlib(sess, &trans.crate_info, &mut |cnum, path| {
535 let name = &trans.crate_info.crate_name[&cnum];
536 let native_libs = &trans.crate_info.native_libraries[&cnum];
537
538 // Here when we include the rlib into our staticlib we need to make a
539 // decision whether to include the extra object files along the way.
540 // These extra object files come from statically included native
541 // libraries, but they may be cfg'd away with #[link(cfg(..))].
542 //
543 // This unstable feature, though, only needs liblibc to work. The only
544 // use case there is where musl is statically included in liblibc.rlib,
545 // so if we don't want the included version we just need to skip it. As
546 // a result the logic here is that if *any* linked library is cfg'd away
547 // we just skip all object files.
548 //
549 // Clearly this is not sufficient for a general purpose feature, and
550 // we'd want to read from the library's metadata to determine which
551 // object files come from where and selectively skip them.
552 let skip_object_files = native_libs.iter().any(|lib| {
553 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
554 });
555 ab.add_rlib(path,
556 &name.as_str(),
557 is_full_lto_enabled(sess) &&
558 !ignored_for_lto(sess, &trans.crate_info, cnum),
559 skip_object_files).unwrap();
560
561 all_native_libs.extend(trans.crate_info.native_libraries[&cnum].iter().cloned());
562 });
563 if let Err(e) = res {
564 sess.fatal(&e);
565 }
566
567 ab.update_symbols();
568 ab.build();
569
570 if !all_native_libs.is_empty() {
571 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
572 print_native_static_libs(sess, &all_native_libs);
573 }
574 }
575 }
576
577 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
578 let lib_args: Vec<_> = all_native_libs.iter()
579 .filter(|l| relevant_lib(sess, l))
580 .filter_map(|lib| match lib.kind {
581 NativeLibraryKind::NativeStaticNobundle |
582 NativeLibraryKind::NativeUnknown => {
583 if sess.target.target.options.is_like_msvc {
584 Some(format!("{}.lib", lib.name))
585 } else {
586 Some(format!("-l{}", lib.name))
587 }
588 },
589 NativeLibraryKind::NativeFramework => {
590 // ld-only syntax, since there are no frameworks in MSVC
591 Some(format!("-framework {}", lib.name))
592 },
593 // These are included, no need to print them
594 NativeLibraryKind::NativeStatic => None,
595 })
596 .collect();
597 if !lib_args.is_empty() {
598 sess.note_without_error("Link against the following native artifacts when linking \
599 against this static library. The order and any duplication \
600 can be significant on some platforms.");
601 // Prefix for greppability
602 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
603 }
604 }
605
606 // Create a dynamic library or executable
607 //
608 // This will invoke the system linker/cc to create the resulting file. This
609 // links to all upstream files as well.
610 fn link_natively(sess: &Session,
611 crate_type: config::CrateType,
612 out_filename: &Path,
613 trans: &CrateTranslation,
614 tmpdir: &Path) {
615 info!("preparing {:?} to {:?}", crate_type, out_filename);
616 let flavor = sess.linker_flavor();
617
618 // The invocations of cc share some flags across platforms
619 let (pname, mut cmd) = get_linker(sess);
620
621 let root = sess.target_filesearch(PathKind::Native).get_lib_path();
622 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
623 cmd.args(args);
624 }
625 if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
626 cmd.args(args);
627 }
628 cmd.args(&sess.opts.debugging_opts.pre_link_arg);
629
630 let pre_link_objects = if crate_type == config::CrateTypeExecutable {
631 &sess.target.target.options.pre_link_objects_exe
632 } else {
633 &sess.target.target.options.pre_link_objects_dll
634 };
635 for obj in pre_link_objects {
636 cmd.arg(root.join(obj));
637 }
638
639 if sess.target.target.options.is_like_emscripten {
640 cmd.arg("-s");
641 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
642 "DISABLE_EXCEPTION_CATCHING=1"
643 } else {
644 "DISABLE_EXCEPTION_CATCHING=0"
645 });
646 }
647
648 {
649 let mut linker = trans.linker_info.to_linker(cmd, &sess);
650 link_args(&mut *linker, sess, crate_type, tmpdir,
651 out_filename, trans);
652 cmd = linker.finalize();
653 }
654 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
655 cmd.args(args);
656 }
657 for obj in &sess.target.target.options.post_link_objects {
658 cmd.arg(root.join(obj));
659 }
660 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
661 cmd.args(args);
662 }
663 for &(ref k, ref v) in &sess.target.target.options.link_env {
664 cmd.env(k, v);
665 }
666
667 if sess.opts.debugging_opts.print_link_args {
668 println!("{:?}", &cmd);
669 }
670
671 // May have not found libraries in the right formats.
672 sess.abort_if_errors();
673
674 // Invoke the system linker
675 //
676 // Note that there's a terribly awful hack that really shouldn't be present
677 // in any compiler. Here an environment variable is supported to
678 // automatically retry the linker invocation if the linker looks like it
679 // segfaulted.
680 //
681 // Gee that seems odd, normally segfaults are things we want to know about!
682 // Unfortunately though in rust-lang/rust#38878 we're experiencing the
683 // linker segfaulting on Travis quite a bit which is causing quite a bit of
684 // pain to land PRs when they spuriously fail due to a segfault.
685 //
686 // The issue #38878 has some more debugging information on it as well, but
687 // this unfortunately looks like it's just a race condition in macOS's linker
688 // with some thread pool working in the background. It seems that no one
689 // currently knows a fix for this so in the meantime we're left with this...
690 info!("{:?}", &cmd);
691 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
692 let mut prog;
693 let mut i = 0;
694 loop {
695 i += 1;
696 prog = time(sess, "running linker", || {
697 exec_linker(sess, &mut cmd, tmpdir)
698 });
699 let output = match prog {
700 Ok(ref output) => output,
701 Err(_) => break,
702 };
703 if output.status.success() {
704 break
705 }
706 let mut out = output.stderr.clone();
707 out.extend(&output.stdout);
708 let out = String::from_utf8_lossy(&out);
709
710 // Check to see if the link failed with "unrecognized command line option:
711 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
712 // reperform the link step without the -no-pie option. This is safe because
713 // if the linker doesn't support -no-pie then it should not default to
714 // linking executables as pie. Different versions of gcc seem to use
715 // different quotes in the error message so don't check for them.
716 if sess.target.target.options.linker_is_gnu &&
717 sess.linker_flavor() != LinkerFlavor::Ld &&
718 (out.contains("unrecognized command line option") ||
719 out.contains("unknown argument")) &&
720 out.contains("-no-pie") &&
721 cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
722 info!("linker output: {:?}", out);
723 warn!("Linker does not support -no-pie command line option. Retrying without.");
724 for arg in cmd.take_args() {
725 if arg.to_string_lossy() != "-no-pie" {
726 cmd.arg(arg);
727 }
728 }
729 info!("{:?}", &cmd);
730 continue;
731 }
732 if !retry_on_segfault || i > 3 {
733 break
734 }
735 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
736 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
737 if !(out.contains(msg_segv) || out.contains(msg_bus)) {
738 break
739 }
740
741 warn!(
742 "looks like the linker segfaulted when we tried to call it, \
743 automatically retrying again. cmd = {:?}, out = {}.",
744 cmd,
745 out,
746 );
747 }
748
749 match prog {
750 Ok(prog) => {
751 fn escape_string(s: &[u8]) -> String {
752 str::from_utf8(s).map(|s| s.to_owned())
753 .unwrap_or_else(|_| {
754 let mut x = "Non-UTF-8 output: ".to_string();
755 x.extend(s.iter()
756 .flat_map(|&b| ascii::escape_default(b))
757 .map(|b| char::from_u32(b as u32).unwrap()));
758 x
759 })
760 }
761 if !prog.status.success() {
762 let mut output = prog.stderr.clone();
763 output.extend_from_slice(&prog.stdout);
764 sess.struct_err(&format!("linking with `{}` failed: {}",
765 pname.display(),
766 prog.status))
767 .note(&format!("{:?}", &cmd))
768 .note(&escape_string(&output))
769 .emit();
770 sess.abort_if_errors();
771 }
772 info!("linker stderr:\n{}", escape_string(&prog.stderr));
773 info!("linker stdout:\n{}", escape_string(&prog.stdout));
774 },
775 Err(e) => {
776 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
777
778 let mut linker_error = {
779 if linker_not_found {
780 sess.struct_err(&format!("linker `{}` not found", pname.display()))
781 } else {
782 sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
783 }
784 };
785
786 linker_error.note(&format!("{}", e));
787
788 if !linker_not_found {
789 linker_error.note(&format!("{:?}", &cmd));
790 }
791
792 linker_error.emit();
793
794 if sess.target.target.options.is_like_msvc && linker_not_found {
795 sess.note_without_error("the msvc targets depend on the msvc linker \
796 but `link.exe` was not found");
797 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
798 with the Visual C++ option");
799 }
800 sess.abort_if_errors();
801 }
802 }
803
804
805 // On macOS, debuggers need this utility to get run to do some munging of
806 // the symbols. Note, though, that if the object files are being preserved
807 // for their debug information there's no need for us to run dsymutil.
808 if sess.target.target.options.is_like_osx &&
809 sess.opts.debuginfo != NoDebugInfo &&
810 !preserve_objects_for_their_debuginfo(sess)
811 {
812 match Command::new("dsymutil").arg(out_filename).output() {
813 Ok(..) => {}
814 Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
815 }
816 }
817
818 if sess.opts.target_triple == TargetTriple::from_triple("wasm32-unknown-unknown") {
819 wasm::rewrite_imports(&out_filename, &trans.crate_info.wasm_imports);
820 wasm::add_custom_sections(&out_filename,
821 &trans.crate_info.wasm_custom_sections);
822 }
823 }
824
825 fn exec_linker(sess: &Session, cmd: &mut Command, tmpdir: &Path)
826 -> io::Result<Output>
827 {
828 // When attempting to spawn the linker we run a risk of blowing out the
829 // size limits for spawning a new process with respect to the arguments
830 // we pass on the command line.
831 //
832 // Here we attempt to handle errors from the OS saying "your list of
833 // arguments is too big" by reinvoking the linker again with an `@`-file
834 // that contains all the arguments. The theory is that this is then
835 // accepted on all linkers and the linker will read all its options out of
836 // there instead of looking at the command line.
837 if !cmd.very_likely_to_exceed_some_spawn_limit() {
838 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
839 Ok(child) => return child.wait_with_output(),
840 Err(ref e) if command_line_too_big(e) => {
841 info!("command line to linker was too big: {}", e);
842 }
843 Err(e) => return Err(e)
844 }
845 }
846
847 info!("falling back to passing arguments to linker via an @-file");
848 let mut cmd2 = cmd.clone();
849 let mut args = String::new();
850 for arg in cmd2.take_args() {
851 args.push_str(&Escape {
852 arg: arg.to_str().unwrap(),
853 is_like_msvc: sess.target.target.options.is_like_msvc,
854 }.to_string());
855 args.push_str("\n");
856 }
857 let file = tmpdir.join("linker-arguments");
858 let bytes = if sess.target.target.options.is_like_msvc {
859 let mut out = vec![];
860 // start the stream with a UTF-16 BOM
861 for c in vec![0xFEFF].into_iter().chain(args.encode_utf16()) {
862 // encode in little endian
863 out.push(c as u8);
864 out.push((c >> 8) as u8);
865 }
866 out
867 } else {
868 args.into_bytes()
869 };
870 fs::write(&file, &bytes)?;
871 cmd2.arg(format!("@{}", file.display()));
872 info!("invoking linker {:?}", cmd2);
873 return cmd2.output();
874
875 #[cfg(unix)]
876 fn command_line_too_big(err: &io::Error) -> bool {
877 err.raw_os_error() == Some(::libc::E2BIG)
878 }
879
880 #[cfg(windows)]
881 fn command_line_too_big(err: &io::Error) -> bool {
882 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
883 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
884 }
885
886 struct Escape<'a> {
887 arg: &'a str,
888 is_like_msvc: bool,
889 }
890
891 impl<'a> fmt::Display for Escape<'a> {
892 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
893 if self.is_like_msvc {
894 // This is "documented" at
895 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
896 //
897 // Unfortunately there's not a great specification of the
898 // syntax I could find online (at least) but some local
899 // testing showed that this seemed sufficient-ish to catch
900 // at least a few edge cases.
901 write!(f, "\"")?;
902 for c in self.arg.chars() {
903 match c {
904 '"' => write!(f, "\\{}", c)?,
905 c => write!(f, "{}", c)?,
906 }
907 }
908 write!(f, "\"")?;
909 } else {
910 // This is documented at https://linux.die.net/man/1/ld, namely:
911 //
912 // > Options in file are separated by whitespace. A whitespace
913 // > character may be included in an option by surrounding the
914 // > entire option in either single or double quotes. Any
915 // > character (including a backslash) may be included by
916 // > prefixing the character to be included with a backslash.
917 //
918 // We put an argument on each line, so all we need to do is
919 // ensure the line is interpreted as one whole argument.
920 for c in self.arg.chars() {
921 match c {
922 '\\' |
923 ' ' => write!(f, "\\{}", c)?,
924 c => write!(f, "{}", c)?,
925 }
926 }
927 }
928 Ok(())
929 }
930 }
931 }
932
933 fn link_args(cmd: &mut Linker,
934 sess: &Session,
935 crate_type: config::CrateType,
936 tmpdir: &Path,
937 out_filename: &Path,
938 trans: &CrateTranslation) {
939
940 // The default library location, we need this to find the runtime.
941 // The location of crates will be determined as needed.
942 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
943
944 // target descriptor
945 let t = &sess.target.target;
946
947 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
948 for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
949 cmd.add_object(obj);
950 }
951 cmd.output_filename(out_filename);
952
953 if crate_type == config::CrateTypeExecutable &&
954 sess.target.target.options.is_like_windows {
955 if let Some(ref s) = trans.windows_subsystem {
956 cmd.subsystem(s);
957 }
958 }
959
960 // If we're building a dynamic library then some platforms need to make sure
961 // that all symbols are exported correctly from the dynamic library.
962 if crate_type != config::CrateTypeExecutable ||
963 sess.target.target.options.is_like_emscripten {
964 cmd.export_symbols(tmpdir, crate_type);
965 }
966
967 // When linking a dynamic library, we put the metadata into a section of the
968 // executable. This metadata is in a separate object file from the main
969 // object file, so we link that in here.
970 if crate_type == config::CrateTypeDylib ||
971 crate_type == config::CrateTypeProcMacro {
972 if let Some(obj) = trans.metadata_module.object.as_ref() {
973 cmd.add_object(obj);
974 }
975 }
976
977 let obj = trans.allocator_module
978 .as_ref()
979 .and_then(|m| m.object.as_ref());
980 if let Some(obj) = obj {
981 cmd.add_object(obj);
982 }
983
984 // Try to strip as much out of the generated object by removing unused
985 // sections if possible. See more comments in linker.rs
986 if !sess.opts.cg.link_dead_code {
987 let keep_metadata = crate_type == config::CrateTypeDylib;
988 cmd.gc_sections(keep_metadata);
989 }
990
991 let used_link_args = &trans.crate_info.link_args;
992
993 if crate_type == config::CrateTypeExecutable {
994 let mut position_independent_executable = false;
995
996 if t.options.position_independent_executables {
997 let empty_vec = Vec::new();
998 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
999 let more_args = &sess.opts.cg.link_arg;
1000 let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1001
1002 if get_reloc_model(sess) == llvm::RelocMode::PIC
1003 && !sess.crt_static() && !args.any(|x| *x == "-static") {
1004 position_independent_executable = true;
1005 }
1006 }
1007
1008 if position_independent_executable {
1009 cmd.position_independent_executable();
1010 } else {
1011 // recent versions of gcc can be configured to generate position
1012 // independent executables by default. We have to pass -no-pie to
1013 // explicitly turn that off. Not applicable to ld.
1014 if sess.target.target.options.linker_is_gnu
1015 && sess.linker_flavor() != LinkerFlavor::Ld {
1016 cmd.no_position_independent_executable();
1017 }
1018 }
1019 }
1020
1021 let relro_level = match sess.opts.debugging_opts.relro_level {
1022 Some(level) => level,
1023 None => t.options.relro_level,
1024 };
1025 match relro_level {
1026 RelroLevel::Full => {
1027 cmd.full_relro();
1028 },
1029 RelroLevel::Partial => {
1030 cmd.partial_relro();
1031 },
1032 RelroLevel::Off => {
1033 cmd.no_relro();
1034 },
1035 RelroLevel::None => {
1036 },
1037 }
1038
1039 // Pass optimization flags down to the linker.
1040 cmd.optimize();
1041
1042 // Pass debuginfo flags down to the linker.
1043 cmd.debuginfo();
1044
1045 // We want to prevent the compiler from accidentally leaking in any system
1046 // libraries, so we explicitly ask gcc to not link to any libraries by
1047 // default. Note that this does not happen for windows because windows pulls
1048 // in some large number of libraries and I couldn't quite figure out which
1049 // subset we wanted.
1050 if t.options.no_default_libraries {
1051 cmd.no_default_libraries();
1052 }
1053
1054 // Take careful note of the ordering of the arguments we pass to the linker
1055 // here. Linkers will assume that things on the left depend on things to the
1056 // right. Things on the right cannot depend on things on the left. This is
1057 // all formally implemented in terms of resolving symbols (libs on the right
1058 // resolve unknown symbols of libs on the left, but not vice versa).
1059 //
1060 // For this reason, we have organized the arguments we pass to the linker as
1061 // such:
1062 //
1063 // 1. The local object that LLVM just generated
1064 // 2. Local native libraries
1065 // 3. Upstream rust libraries
1066 // 4. Upstream native libraries
1067 //
1068 // The rationale behind this ordering is that those items lower down in the
1069 // list can't depend on items higher up in the list. For example nothing can
1070 // depend on what we just generated (e.g. that'd be a circular dependency).
1071 // Upstream rust libraries are not allowed to depend on our local native
1072 // libraries as that would violate the structure of the DAG, in that
1073 // scenario they are required to link to them as well in a shared fashion.
1074 //
1075 // Note that upstream rust libraries may contain native dependencies as
1076 // well, but they also can't depend on what we just started to add to the
1077 // link line. And finally upstream native libraries can't depend on anything
1078 // in this DAG so far because they're only dylibs and dylibs can only depend
1079 // on other dylibs (e.g. other native deps).
1080 add_local_native_libraries(cmd, sess, trans);
1081 add_upstream_rust_crates(cmd, sess, trans, crate_type, tmpdir);
1082 add_upstream_native_libraries(cmd, sess, trans, crate_type);
1083
1084 // Tell the linker what we're doing.
1085 if crate_type != config::CrateTypeExecutable {
1086 cmd.build_dylib(out_filename);
1087 }
1088 if crate_type == config::CrateTypeExecutable && sess.crt_static() {
1089 cmd.build_static_executable();
1090 }
1091
1092 if sess.opts.debugging_opts.pgo_gen.is_some() {
1093 cmd.pgo_gen();
1094 }
1095
1096 // FIXME (#2397): At some point we want to rpath our guesses as to
1097 // where extern libraries might live, based on the
1098 // addl_lib_search_paths
1099 if sess.opts.cg.rpath {
1100 let sysroot = sess.sysroot();
1101 let target_triple = sess.opts.target_triple.triple();
1102 let mut get_install_prefix_lib_path = || {
1103 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1104 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1105 let mut path = PathBuf::from(install_prefix);
1106 path.push(&tlib);
1107
1108 path
1109 };
1110 let mut rpath_config = RPathConfig {
1111 used_crates: &trans.crate_info.used_crates_dynamic,
1112 out_filename: out_filename.to_path_buf(),
1113 has_rpath: sess.target.target.options.has_rpath,
1114 is_like_osx: sess.target.target.options.is_like_osx,
1115 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1116 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1117 };
1118 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1119 }
1120
1121 // Finally add all the linker arguments provided on the command line along
1122 // with any #[link_args] attributes found inside the crate
1123 if let Some(ref args) = sess.opts.cg.link_args {
1124 cmd.args(args);
1125 }
1126 cmd.args(&sess.opts.cg.link_arg);
1127 cmd.args(&used_link_args);
1128 }
1129
1130 // # Native library linking
1131 //
1132 // User-supplied library search paths (-L on the command line). These are
1133 // the same paths used to find Rust crates, so some of them may have been
1134 // added already by the previous crate linking code. This only allows them
1135 // to be found at compile time so it is still entirely up to outside
1136 // forces to make sure that library can be found at runtime.
1137 //
1138 // Also note that the native libraries linked here are only the ones located
1139 // in the current crate. Upstream crates with native library dependencies
1140 // may have their native library pulled in above.
1141 fn add_local_native_libraries(cmd: &mut Linker,
1142 sess: &Session,
1143 trans: &CrateTranslation) {
1144 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1145 match k {
1146 PathKind::Framework => { cmd.framework_path(path); }
1147 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1148 }
1149 });
1150
1151 let relevant_libs = trans.crate_info.used_libraries.iter().filter(|l| {
1152 relevant_lib(sess, l)
1153 });
1154
1155 let search_path = archive_search_paths(sess);
1156 for lib in relevant_libs {
1157 match lib.kind {
1158 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1159 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1160 NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1161 NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1162 &search_path)
1163 }
1164 }
1165 }
1166
1167 // # Rust Crate linking
1168 //
1169 // Rust crates are not considered at all when creating an rlib output. All
1170 // dependencies will be linked when producing the final output (instead of
1171 // the intermediate rlib version)
1172 fn add_upstream_rust_crates(cmd: &mut Linker,
1173 sess: &Session,
1174 trans: &CrateTranslation,
1175 crate_type: config::CrateType,
1176 tmpdir: &Path) {
1177 // All of the heavy lifting has previously been accomplished by the
1178 // dependency_format module of the compiler. This is just crawling the
1179 // output of that module, adding crates as necessary.
1180 //
1181 // Linking to a rlib involves just passing it to the linker (the linker
1182 // will slurp up the object files inside), and linking to a dynamic library
1183 // involves just passing the right -l flag.
1184
1185 let formats = sess.dependency_formats.borrow();
1186 let data = formats.get(&crate_type).unwrap();
1187
1188 // Invoke get_used_crates to ensure that we get a topological sorting of
1189 // crates.
1190 let deps = &trans.crate_info.used_crates_dynamic;
1191
1192 // There's a few internal crates in the standard library (aka libcore and
1193 // libstd) which actually have a circular dependence upon one another. This
1194 // currently arises through "weak lang items" where libcore requires things
1195 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1196 // circular dependence to work correctly in all situations we'll need to be
1197 // sure to correctly apply the `--start-group` and `--end-group` options to
1198 // GNU linkers, otherwise if we don't use any other symbol from the standard
1199 // library it'll get discarded and the whole application won't link.
1200 //
1201 // In this loop we're calculating the `group_end`, after which crate to
1202 // pass `--end-group` and `group_start`, before which crate to pass
1203 // `--start-group`. We currently do this by passing `--end-group` after
1204 // the first crate (when iterating backwards) that requires a lang item
1205 // defined somewhere else. Once that's set then when we've defined all the
1206 // necessary lang items we'll pass `--start-group`.
1207 //
1208 // Note that this isn't amazing logic for now but it should do the trick
1209 // for the current implementation of the standard library.
1210 let mut group_end = None;
1211 let mut group_start = None;
1212 let mut end_with = FxHashSet();
1213 let info = &trans.crate_info;
1214 for &(cnum, _) in deps.iter().rev() {
1215 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1216 end_with.extend(missing.iter().cloned());
1217 if end_with.len() > 0 && group_end.is_none() {
1218 group_end = Some(cnum);
1219 }
1220 }
1221 end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1222 if end_with.len() == 0 && group_end.is_some() {
1223 group_start = Some(cnum);
1224 break
1225 }
1226 }
1227
1228 // If we didn't end up filling in all lang items from upstream crates then
1229 // we'll be filling it in with our crate. This probably means we're the
1230 // standard library itself, so skip this for now.
1231 if group_end.is_some() && group_start.is_none() {
1232 group_end = None;
1233 }
1234
1235 let mut compiler_builtins = None;
1236
1237 for &(cnum, _) in deps.iter() {
1238 if group_start == Some(cnum) {
1239 cmd.group_start();
1240 }
1241
1242 // We may not pass all crates through to the linker. Some crates may
1243 // appear statically in an existing dylib, meaning we'll pick up all the
1244 // symbols from the dylib.
1245 let src = &trans.crate_info.used_crate_source[&cnum];
1246 match data[cnum.as_usize() - 1] {
1247 _ if trans.crate_info.profiler_runtime == Some(cnum) => {
1248 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1249 }
1250 _ if trans.crate_info.sanitizer_runtime == Some(cnum) => {
1251 link_sanitizer_runtime(cmd, sess, trans, tmpdir, cnum);
1252 }
1253 // compiler-builtins are always placed last to ensure that they're
1254 // linked correctly.
1255 _ if trans.crate_info.compiler_builtins == Some(cnum) => {
1256 assert!(compiler_builtins.is_none());
1257 compiler_builtins = Some(cnum);
1258 }
1259 Linkage::NotLinked |
1260 Linkage::IncludedFromDylib => {}
1261 Linkage::Static => {
1262 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1263 }
1264 Linkage::Dynamic => {
1265 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1266 }
1267 }
1268
1269 if group_end == Some(cnum) {
1270 cmd.group_end();
1271 }
1272 }
1273
1274 // compiler-builtins are always placed last to ensure that they're
1275 // linked correctly.
1276 // We must always link the `compiler_builtins` crate statically. Even if it
1277 // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1278 // is used)
1279 if let Some(cnum) = compiler_builtins {
1280 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1281 }
1282
1283 // Converts a library file-stem into a cc -l argument
1284 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1285 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1286 &stem[3..]
1287 } else {
1288 stem
1289 }
1290 }
1291
1292 // We must link the sanitizer runtime using -Wl,--whole-archive but since
1293 // it's packed in a .rlib, it contains stuff that are not objects that will
1294 // make the linker error. So we must remove those bits from the .rlib before
1295 // linking it.
1296 fn link_sanitizer_runtime(cmd: &mut Linker,
1297 sess: &Session,
1298 trans: &CrateTranslation,
1299 tmpdir: &Path,
1300 cnum: CrateNum) {
1301 let src = &trans.crate_info.used_crate_source[&cnum];
1302 let cratepath = &src.rlib.as_ref().unwrap().0;
1303
1304 if sess.target.target.options.is_like_osx {
1305 // On Apple platforms, the sanitizer is always built as a dylib, and
1306 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1307 // rpath to the library as well (the rpath should be absolute, see
1308 // PR #41352 for details).
1309 //
1310 // FIXME: Remove this logic into librustc_*san once Cargo supports it
1311 let rpath = cratepath.parent().unwrap();
1312 let rpath = rpath.to_str().expect("non-utf8 component in path");
1313 cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1314 }
1315
1316 let dst = tmpdir.join(cratepath.file_name().unwrap());
1317 let cfg = archive_config(sess, &dst, Some(cratepath));
1318 let mut archive = ArchiveBuilder::new(cfg);
1319 archive.update_symbols();
1320
1321 for f in archive.src_files() {
1322 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1323 archive.remove_file(&f);
1324 continue
1325 }
1326 }
1327
1328 archive.build();
1329
1330 cmd.link_whole_rlib(&dst);
1331 }
1332
1333 // Adds the static "rlib" versions of all crates to the command line.
1334 // There's a bit of magic which happens here specifically related to LTO and
1335 // dynamic libraries. Specifically:
1336 //
1337 // * For LTO, we remove upstream object files.
1338 // * For dylibs we remove metadata and bytecode from upstream rlibs
1339 //
1340 // When performing LTO, almost(*) all of the bytecode from the upstream
1341 // libraries has already been included in our object file output. As a
1342 // result we need to remove the object files in the upstream libraries so
1343 // the linker doesn't try to include them twice (or whine about duplicate
1344 // symbols). We must continue to include the rest of the rlib, however, as
1345 // it may contain static native libraries which must be linked in.
1346 //
1347 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1348 // their bytecode wasn't included. The object files in those libraries must
1349 // still be passed to the linker.
1350 //
1351 // When making a dynamic library, linkers by default don't include any
1352 // object files in an archive if they're not necessary to resolve the link.
1353 // We basically want to convert the archive (rlib) to a dylib, though, so we
1354 // *do* want everything included in the output, regardless of whether the
1355 // linker thinks it's needed or not. As a result we must use the
1356 // --whole-archive option (or the platform equivalent). When using this
1357 // option the linker will fail if there are non-objects in the archive (such
1358 // as our own metadata and/or bytecode). All in all, for rlibs to be
1359 // entirely included in dylibs, we need to remove all non-object files.
1360 //
1361 // Note, however, that if we're not doing LTO or we're not producing a dylib
1362 // (aka we're making an executable), we can just pass the rlib blindly to
1363 // the linker (fast) because it's fine if it's not actually included as
1364 // we're at the end of the dependency chain.
1365 fn add_static_crate(cmd: &mut Linker,
1366 sess: &Session,
1367 trans: &CrateTranslation,
1368 tmpdir: &Path,
1369 crate_type: config::CrateType,
1370 cnum: CrateNum) {
1371 let src = &trans.crate_info.used_crate_source[&cnum];
1372 let cratepath = &src.rlib.as_ref().unwrap().0;
1373
1374 // See the comment above in `link_staticlib` and `link_rlib` for why if
1375 // there's a static library that's not relevant we skip all object
1376 // files.
1377 let native_libs = &trans.crate_info.native_libraries[&cnum];
1378 let skip_native = native_libs.iter().any(|lib| {
1379 lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1380 });
1381
1382 if (!is_full_lto_enabled(sess) ||
1383 ignored_for_lto(sess, &trans.crate_info, cnum)) &&
1384 crate_type != config::CrateTypeDylib &&
1385 !skip_native {
1386 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1387 return
1388 }
1389
1390 let dst = tmpdir.join(cratepath.file_name().unwrap());
1391 let name = cratepath.file_name().unwrap().to_str().unwrap();
1392 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1393
1394 time(sess, &format!("altering {}.rlib", name), || {
1395 let cfg = archive_config(sess, &dst, Some(cratepath));
1396 let mut archive = ArchiveBuilder::new(cfg);
1397 archive.update_symbols();
1398
1399 let mut any_objects = false;
1400 for f in archive.src_files() {
1401 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1402 archive.remove_file(&f);
1403 continue
1404 }
1405
1406 let canonical = f.replace("-", "_");
1407 let canonical_name = name.replace("-", "_");
1408
1409 // Look for `.rcgu.o` at the end of the filename to conclude
1410 // that this is a Rust-related object file.
1411 fn looks_like_rust(s: &str) -> bool {
1412 let path = Path::new(s);
1413 let ext = path.extension().and_then(|s| s.to_str());
1414 if ext != Some(OutputType::Object.extension()) {
1415 return false
1416 }
1417 let ext2 = path.file_stem()
1418 .and_then(|s| Path::new(s).extension())
1419 .and_then(|s| s.to_str());
1420 ext2 == Some(RUST_CGU_EXT)
1421 }
1422
1423 let is_rust_object =
1424 canonical.starts_with(&canonical_name) &&
1425 looks_like_rust(&f);
1426
1427 // If we've been requested to skip all native object files
1428 // (those not generated by the rust compiler) then we can skip
1429 // this file. See above for why we may want to do this.
1430 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1431
1432 // If we're performing LTO and this is a rust-generated object
1433 // file, then we don't need the object file as it's part of the
1434 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1435 // though, so we let that object file slide.
1436 let skip_because_lto = is_full_lto_enabled(sess) &&
1437 is_rust_object &&
1438 (sess.target.target.options.no_builtins ||
1439 !trans.crate_info.is_no_builtins.contains(&cnum));
1440
1441 if skip_because_cfg_say_so || skip_because_lto {
1442 archive.remove_file(&f);
1443 } else {
1444 any_objects = true;
1445 }
1446 }
1447
1448 if !any_objects {
1449 return
1450 }
1451 archive.build();
1452
1453 // If we're creating a dylib, then we need to include the
1454 // whole of each object in our archive into that artifact. This is
1455 // because a `dylib` can be reused as an intermediate artifact.
1456 //
1457 // Note, though, that we don't want to include the whole of a
1458 // compiler-builtins crate (e.g. compiler-rt) because it'll get
1459 // repeatedly linked anyway.
1460 if crate_type == config::CrateTypeDylib &&
1461 trans.crate_info.compiler_builtins != Some(cnum) {
1462 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1463 } else {
1464 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1465 }
1466 });
1467 }
1468
1469 // Same thing as above, but for dynamic crates instead of static crates.
1470 fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1471 // If we're performing LTO, then it should have been previously required
1472 // that all upstream rust dependencies were available in an rlib format.
1473 assert!(!is_full_lto_enabled(sess));
1474
1475 // Just need to tell the linker about where the library lives and
1476 // what its name is
1477 let parent = cratepath.parent();
1478 if let Some(dir) = parent {
1479 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1480 }
1481 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1482 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1483 parent.unwrap_or(Path::new("")));
1484 }
1485 }
1486
1487 // Link in all of our upstream crates' native dependencies. Remember that
1488 // all of these upstream native dependencies are all non-static
1489 // dependencies. We've got two cases then:
1490 //
1491 // 1. The upstream crate is an rlib. In this case we *must* link in the
1492 // native dependency because the rlib is just an archive.
1493 //
1494 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1495 // have the dependency present on the system somewhere. Thus, we don't
1496 // gain a whole lot from not linking in the dynamic dependency to this
1497 // crate as well.
1498 //
1499 // The use case for this is a little subtle. In theory the native
1500 // dependencies of a crate are purely an implementation detail of the crate
1501 // itself, but the problem arises with generic and inlined functions. If a
1502 // generic function calls a native function, then the generic function must
1503 // be instantiated in the target crate, meaning that the native symbol must
1504 // also be resolved in the target crate.
1505 fn add_upstream_native_libraries(cmd: &mut Linker,
1506 sess: &Session,
1507 trans: &CrateTranslation,
1508 crate_type: config::CrateType) {
1509 // Be sure to use a topological sorting of crates because there may be
1510 // interdependencies between native libraries. When passing -nodefaultlibs,
1511 // for example, almost all native libraries depend on libc, so we have to
1512 // make sure that's all the way at the right (liblibc is near the base of
1513 // the dependency chain).
1514 //
1515 // This passes RequireStatic, but the actual requirement doesn't matter,
1516 // we're just getting an ordering of crate numbers, we're not worried about
1517 // the paths.
1518 let formats = sess.dependency_formats.borrow();
1519 let data = formats.get(&crate_type).unwrap();
1520
1521 let crates = &trans.crate_info.used_crates_static;
1522 for &(cnum, _) in crates {
1523 for lib in trans.crate_info.native_libraries[&cnum].iter() {
1524 if !relevant_lib(sess, &lib) {
1525 continue
1526 }
1527 match lib.kind {
1528 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1529 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1530 NativeLibraryKind::NativeStaticNobundle => {
1531 // Link "static-nobundle" native libs only if the crate they originate from
1532 // is being linked statically to the current crate. If it's linked dynamically
1533 // or is an rlib already included via some other dylib crate, the symbols from
1534 // native libs will have already been included in that dylib.
1535 if data[cnum.as_usize() - 1] == Linkage::Static {
1536 cmd.link_staticlib(&lib.name.as_str())
1537 }
1538 },
1539 // ignore statically included native libraries here as we've
1540 // already included them when we included the rust library
1541 // previously
1542 NativeLibraryKind::NativeStatic => {}
1543 }
1544 }
1545 }
1546 }
1547
1548 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1549 match lib.cfg {
1550 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1551 None => true,
1552 }
1553 }
1554
1555 fn is_full_lto_enabled(sess: &Session) -> bool {
1556 match sess.lto() {
1557 Lto::Yes |
1558 Lto::Thin |
1559 Lto::Fat => true,
1560 Lto::No |
1561 Lto::ThinLocal => false,
1562 }
1563 }