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