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