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