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