]> git.proxmox.com Git - rustc.git/blob - src/librustc_codegen_ssa/back/link.rs
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_codegen_ssa / back / link.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::temp_dir::MaybeTempDir;
3 use rustc_fs_util::fix_windows_verbatim_for_gcc;
4 use rustc_hir::def_id::CrateNum;
5 use rustc_middle::middle::cstore::{EncodedMetadata, LibSource, NativeLib};
6 use rustc_middle::middle::dependency_format::Linkage;
7 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo};
8 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SanitizerSet};
9 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
10 use rustc_session::search_paths::PathKind;
11 use rustc_session::utils::NativeLibKind;
12 /// For all the linkers we support, and information they might
13 /// need out of the shared crate context before we get rid of it.
14 use rustc_session::{filesearch, Session};
15 use rustc_span::symbol::Symbol;
16 use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
17 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
18 use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel};
19
20 use super::archive::ArchiveBuilder;
21 use super::command::Command;
22 use super::linker::{self, Linker};
23 use super::rpath::{self, RPathConfig};
24 use crate::{looks_like_rust_object_file, CodegenResults, CrateInfo, METADATA_FILENAME};
25
26 use cc::windows_registry;
27 use tempfile::Builder as TempFileBuilder;
28
29 use std::ffi::OsString;
30 use std::path::{Path, PathBuf};
31 use std::process::{ExitStatus, Output, Stdio};
32 use std::{ascii, char, env, fmt, fs, io, mem, str};
33
34 pub fn remove(sess: &Session, path: &Path) {
35 if let Err(e) = fs::remove_file(path) {
36 sess.err(&format!("failed to remove {}: {}", path.display(), e));
37 }
38 }
39
40 /// Performs the linkage portion of the compilation phase. This will generate all
41 /// of the requested outputs for this compilation session.
42 pub fn link_binary<'a, B: ArchiveBuilder<'a>>(
43 sess: &'a Session,
44 codegen_results: &CodegenResults,
45 outputs: &OutputFilenames,
46 crate_name: &str,
47 target_cpu: &str,
48 ) {
49 let _timer = sess.timer("link_binary");
50 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
51 for &crate_type in sess.crate_types().iter() {
52 // Ignore executable crates if we have -Z no-codegen, as they will error.
53 if (sess.opts.debugging_opts.no_codegen || !sess.opts.output_types.should_codegen())
54 && !output_metadata
55 && crate_type == CrateType::Executable
56 {
57 continue;
58 }
59
60 if invalid_output_for_target(sess, crate_type) {
61 bug!(
62 "invalid output type `{:?}` for target os `{}`",
63 crate_type,
64 sess.opts.target_triple
65 );
66 }
67
68 sess.time("link_binary_check_files_are_writeable", || {
69 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
70 check_file_is_writeable(obj, sess);
71 }
72 });
73
74 if outputs.outputs.should_codegen() {
75 let tmpdir = TempFileBuilder::new()
76 .prefix("rustc")
77 .tempdir()
78 .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err)));
79 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
80 let out_filename = out_filename(sess, crate_type, outputs, crate_name);
81 match crate_type {
82 CrateType::Rlib => {
83 let _timer = sess.timer("link_rlib");
84 link_rlib::<B>(sess, codegen_results, RlibFlavor::Normal, &out_filename, &path)
85 .build();
86 }
87 CrateType::Staticlib => {
88 link_staticlib::<B>(sess, codegen_results, &out_filename, &path);
89 }
90 _ => {
91 link_natively::<B>(
92 sess,
93 crate_type,
94 &out_filename,
95 codegen_results,
96 path.as_ref(),
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
107 // Remove the temporary object file and metadata if we aren't saving temps
108 sess.time("link_binary_remove_temps", || {
109 if !sess.opts.cg.save_temps {
110 if sess.opts.output_types.should_codegen()
111 && !preserve_objects_for_their_debuginfo(sess)
112 {
113 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
114 remove(sess, obj);
115 }
116 }
117 if let Some(ref metadata_module) = codegen_results.metadata_module {
118 if let Some(ref obj) = metadata_module.object {
119 remove(sess, obj);
120 }
121 }
122 if let Some(ref allocator_module) = codegen_results.allocator_module {
123 if let Some(ref obj) = allocator_module.object {
124 remove(sess, obj);
125 }
126 }
127 }
128 });
129 }
130
131 // The third parameter is for env vars, used on windows to set up the
132 // path for MSVC to find its DLLs, and gcc to find its bundled
133 // toolchain
134 fn get_linker(
135 sess: &Session,
136 linker: &Path,
137 flavor: LinkerFlavor,
138 self_contained: bool,
139 ) -> Command {
140 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
141
142 // If our linker looks like a batch script on Windows then to execute this
143 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
144 // emscripten where the linker is `emcc.bat` and needs to be spawned as
145 // `cmd /c emcc.bat ...`.
146 //
147 // This worked historically but is needed manually since #42436 (regression
148 // was tagged as #42791) and some more info can be found on #44443 for
149 // emscripten itself.
150 let mut cmd = match linker.to_str() {
151 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
152 _ => match flavor {
153 LinkerFlavor::Lld(f) => Command::lld(linker, f),
154 LinkerFlavor::Msvc
155 if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
156 {
157 Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
158 }
159 _ => Command::new(linker),
160 },
161 };
162
163 // UWP apps have API restrictions enforced during Store submissions.
164 // To comply with the Windows App Certification Kit,
165 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
166 let t = &sess.target.target;
167 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
168 && t.target_vendor == "uwp"
169 {
170 if let Some(ref tool) = msvc_tool {
171 let original_path = tool.path();
172 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
173 let arch = match t.arch.as_str() {
174 "x86_64" => Some("x64".to_string()),
175 "x86" => Some("x86".to_string()),
176 "aarch64" => Some("arm64".to_string()),
177 "arm" => Some("arm".to_string()),
178 _ => None,
179 };
180 if let Some(ref a) = arch {
181 // FIXME: Move this to `fn linker_with_args`.
182 let mut arg = OsString::from("/LIBPATH:");
183 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a.to_string()));
184 cmd.arg(&arg);
185 } else {
186 warn!("arch is not supported");
187 }
188 } else {
189 warn!("MSVC root path lib location not found");
190 }
191 } else {
192 warn!("link.exe not found");
193 }
194 }
195
196 // The compiler's sysroot often has some bundled tools, so add it to the
197 // PATH for the child.
198 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(self_contained);
199 let mut msvc_changed_path = false;
200 if sess.target.target.options.is_like_msvc {
201 if let Some(ref tool) = msvc_tool {
202 cmd.args(tool.args());
203 for &(ref k, ref v) in tool.env() {
204 if k == "PATH" {
205 new_path.extend(env::split_paths(v));
206 msvc_changed_path = true;
207 } else {
208 cmd.env(k, v);
209 }
210 }
211 }
212 }
213
214 if !msvc_changed_path {
215 if let Some(path) = env::var_os("PATH") {
216 new_path.extend(env::split_paths(&path));
217 }
218 }
219 cmd.env("PATH", env::join_paths(new_path).unwrap());
220
221 cmd
222 }
223
224 pub fn each_linked_rlib(
225 info: &CrateInfo,
226 f: &mut dyn FnMut(CrateNum, &Path),
227 ) -> Result<(), String> {
228 let crates = info.used_crates_static.iter();
229 let mut fmts = None;
230 for (ty, list) in info.dependency_formats.iter() {
231 match ty {
232 CrateType::Executable
233 | CrateType::Staticlib
234 | CrateType::Cdylib
235 | CrateType::ProcMacro => {
236 fmts = Some(list);
237 break;
238 }
239 _ => {}
240 }
241 }
242 let fmts = match fmts {
243 Some(f) => f,
244 None => return Err("could not find formats for rlibs".to_string()),
245 };
246 for &(cnum, ref path) in crates {
247 match fmts.get(cnum.as_usize() - 1) {
248 Some(&Linkage::NotLinked | &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!(
257 "could not find rlib for: `{}`, found rmeta (metadata) file",
258 name
259 ));
260 }
261 LibSource::None => return Err(format!("could not find rlib for: `{}`", name)),
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(sess: &Session, metadata: &EncodedMetadata, tmpdir: &MaybeTempDir) -> PathBuf {
274 let out_filename = tmpdir.as_ref().join(METADATA_FILENAME);
275 let result = fs::write(&out_filename, &metadata.raw_data);
276
277 if let Err(e) = result {
278 sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
279 }
280
281 out_filename
282 }
283
284 // Create an 'rlib'
285 //
286 // An rlib in its current incarnation is essentially a renamed .a file. The
287 // rlib primarily contains the object file of the crate, but it also contains
288 // all of the object files from native libraries. This is done by unzipping
289 // native libraries and inserting all of the contents into this archive.
290 fn link_rlib<'a, B: ArchiveBuilder<'a>>(
291 sess: &'a Session,
292 codegen_results: &CodegenResults,
293 flavor: RlibFlavor,
294 out_filename: &Path,
295 tmpdir: &MaybeTempDir,
296 ) -> B {
297 info!("preparing rlib to {:?}", out_filename);
298 let mut ab = <B as ArchiveBuilder>::new(sess, out_filename, None);
299
300 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
301 ab.add_file(obj);
302 }
303
304 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
305 // we may not be configured to actually include a static library if we're
306 // adding it here. That's because later when we consume this rlib we'll
307 // decide whether we actually needed the static library or not.
308 //
309 // To do this "correctly" we'd need to keep track of which libraries added
310 // which object files to the archive. We don't do that here, however. The
311 // #[link(cfg(..))] feature is unstable, though, and only intended to get
312 // liblibc working. In that sense the check below just indicates that if
313 // there are any libraries we want to omit object files for at link time we
314 // just exclude all custom object files.
315 //
316 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
317 // feature then we'll need to figure out how to record what objects were
318 // loaded from the libraries found here and then encode that into the
319 // metadata of the rlib we're generating somehow.
320 for lib in codegen_results.crate_info.used_libraries.iter() {
321 match lib.kind {
322 NativeLibKind::StaticBundle => {}
323 NativeLibKind::StaticNoBundle
324 | NativeLibKind::Dylib
325 | NativeLibKind::Framework
326 | NativeLibKind::RawDylib
327 | NativeLibKind::Unspecified => continue,
328 }
329 if let Some(name) = lib.name {
330 ab.add_native_library(name);
331 }
332 }
333
334 // After adding all files to the archive, we need to update the
335 // symbol table of the archive.
336 ab.update_symbols();
337
338 // Note that it is important that we add all of our non-object "magical
339 // files" *after* all of the object files in the archive. The reason for
340 // this is as follows:
341 //
342 // * When performing LTO, this archive will be modified to remove
343 // objects from above. The reason for this is described below.
344 //
345 // * When the system linker looks at an archive, it will attempt to
346 // determine the architecture of the archive in order to see whether its
347 // linkable.
348 //
349 // The algorithm for this detection is: iterate over the files in the
350 // archive. Skip magical SYMDEF names. Interpret the first file as an
351 // object file. Read architecture from the object file.
352 //
353 // * As one can probably see, if "metadata" and "foo.bc" were placed
354 // before all of the objects, then the architecture of this archive would
355 // not be correctly inferred once 'foo.o' is removed.
356 //
357 // Basically, all this means is that this code should not move above the
358 // code above.
359 match flavor {
360 RlibFlavor::Normal => {
361 // Instead of putting the metadata in an object file section, rlibs
362 // contain the metadata in a separate file.
363 ab.add_file(&emit_metadata(sess, &codegen_results.metadata, tmpdir));
364
365 // After adding all files to the archive, we need to update the
366 // symbol table of the archive. This currently dies on macOS (see
367 // #11162), and isn't necessary there anyway
368 if !sess.target.target.options.is_like_osx {
369 ab.update_symbols();
370 }
371 }
372
373 RlibFlavor::StaticlibBase => {
374 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
375 if let Some(obj) = obj {
376 ab.add_file(obj);
377 }
378 }
379 }
380
381 ab
382 }
383
384 // Create a static archive
385 //
386 // This is essentially the same thing as an rlib, but it also involves adding
387 // all of the upstream crates' objects into the archive. This will slurp in
388 // all of the native libraries of upstream dependencies as well.
389 //
390 // Additionally, there's no way for us to link dynamic libraries, so we warn
391 // about all dynamic library dependencies that they're not linked in.
392 //
393 // There's no need to include metadata in a static archive, so ensure to not
394 // link in the metadata object file (and also don't prepare the archive with a
395 // metadata file).
396 fn link_staticlib<'a, B: ArchiveBuilder<'a>>(
397 sess: &'a Session,
398 codegen_results: &CodegenResults,
399 out_filename: &Path,
400 tempdir: &MaybeTempDir,
401 ) {
402 let mut ab =
403 link_rlib::<B>(sess, codegen_results, RlibFlavor::StaticlibBase, out_filename, tempdir);
404 let mut all_native_libs = vec![];
405
406 let res = each_linked_rlib(&codegen_results.crate_info, &mut |cnum, path| {
407 let name = &codegen_results.crate_info.crate_name[&cnum];
408 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
409
410 // Here when we include the rlib into our staticlib we need to make a
411 // decision whether to include the extra object files along the way.
412 // These extra object files come from statically included native
413 // libraries, but they may be cfg'd away with #[link(cfg(..))].
414 //
415 // This unstable feature, though, only needs liblibc to work. The only
416 // use case there is where musl is statically included in liblibc.rlib,
417 // so if we don't want the included version we just need to skip it. As
418 // a result the logic here is that if *any* linked library is cfg'd away
419 // we just skip all object files.
420 //
421 // Clearly this is not sufficient for a general purpose feature, and
422 // we'd want to read from the library's metadata to determine which
423 // object files come from where and selectively skip them.
424 let skip_object_files = native_libs
425 .iter()
426 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
427 ab.add_rlib(
428 path,
429 &name.as_str(),
430 are_upstream_rust_objects_already_included(sess)
431 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum),
432 skip_object_files,
433 )
434 .unwrap();
435
436 all_native_libs.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
437 });
438 if let Err(e) = res {
439 sess.fatal(&e);
440 }
441
442 ab.update_symbols();
443 ab.build();
444
445 if !all_native_libs.is_empty() {
446 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
447 print_native_static_libs(sess, &all_native_libs);
448 }
449 }
450 }
451
452 // Create a dynamic library or executable
453 //
454 // This will invoke the system linker/cc to create the resulting file. This
455 // links to all upstream files as well.
456 fn link_natively<'a, B: ArchiveBuilder<'a>>(
457 sess: &'a Session,
458 crate_type: CrateType,
459 out_filename: &Path,
460 codegen_results: &CodegenResults,
461 tmpdir: &Path,
462 target_cpu: &str,
463 ) {
464 info!("preparing {:?} to {:?}", crate_type, out_filename);
465 let (linker_path, flavor) = linker_and_flavor(sess);
466 let mut cmd = linker_with_args::<B>(
467 &linker_path,
468 flavor,
469 sess,
470 crate_type,
471 tmpdir,
472 out_filename,
473 codegen_results,
474 target_cpu,
475 );
476
477 linker::disable_localization(&mut cmd);
478
479 for &(ref k, ref v) in &sess.target.target.options.link_env {
480 cmd.env(k, v);
481 }
482 for k in &sess.target.target.options.link_env_remove {
483 cmd.env_remove(k);
484 }
485
486 if sess.opts.debugging_opts.print_link_args {
487 println!("{:?}", &cmd);
488 }
489
490 // May have not found libraries in the right formats.
491 sess.abort_if_errors();
492
493 // Invoke the system linker
494 info!("{:?}", &cmd);
495 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
496 let mut prog;
497 let mut i = 0;
498 loop {
499 i += 1;
500 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
501 let output = match prog {
502 Ok(ref output) => output,
503 Err(_) => break,
504 };
505 if output.status.success() {
506 break;
507 }
508 let mut out = output.stderr.clone();
509 out.extend(&output.stdout);
510 let out = String::from_utf8_lossy(&out);
511
512 // Check to see if the link failed with "unrecognized command line option:
513 // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
514 // reperform the link step without the -no-pie option. This is safe because
515 // if the linker doesn't support -no-pie then it should not default to
516 // linking executables as pie. Different versions of gcc seem to use
517 // different quotes in the error message so don't check for them.
518 if sess.target.target.options.linker_is_gnu
519 && flavor != LinkerFlavor::Ld
520 && (out.contains("unrecognized command line option")
521 || out.contains("unknown argument"))
522 && out.contains("-no-pie")
523 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
524 {
525 info!("linker output: {:?}", out);
526 warn!("Linker does not support -no-pie command line option. Retrying without.");
527 for arg in cmd.take_args() {
528 if arg.to_string_lossy() != "-no-pie" {
529 cmd.arg(arg);
530 }
531 }
532 info!("{:?}", &cmd);
533 continue;
534 }
535
536 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
537 // Fallback from '-static-pie' to '-static' in that case.
538 if sess.target.target.options.linker_is_gnu
539 && flavor != LinkerFlavor::Ld
540 && (out.contains("unrecognized command line option")
541 || out.contains("unknown argument"))
542 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
543 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
544 {
545 info!("linker output: {:?}", out);
546 warn!(
547 "Linker does not support -static-pie command line option. Retrying with -static instead."
548 );
549 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
550 let self_contained = crt_objects_fallback(sess, crate_type);
551 let opts = &sess.target.target.options;
552 let pre_objects = if self_contained {
553 &opts.pre_link_objects_fallback
554 } else {
555 &opts.pre_link_objects
556 };
557 let post_objects = if self_contained {
558 &opts.post_link_objects_fallback
559 } else {
560 &opts.post_link_objects
561 };
562 let get_objects = |objects: &CrtObjects, kind| {
563 objects
564 .get(&kind)
565 .iter()
566 .copied()
567 .flatten()
568 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
569 .collect::<Vec<_>>()
570 };
571 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
572 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
573 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
574 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
575 // Assume that we know insertion positions for the replacement arguments from replaced
576 // arguments, which is true for all supported targets.
577 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
578 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
579 for arg in cmd.take_args() {
580 if arg.to_string_lossy() == "-static-pie" {
581 // Replace the output kind.
582 cmd.arg("-static");
583 } else if pre_objects_static_pie.contains(&arg) {
584 // Replace the pre-link objects (replace the first and remove the rest).
585 cmd.args(mem::take(&mut pre_objects_static));
586 } else if post_objects_static_pie.contains(&arg) {
587 // Replace the post-link objects (replace the first and remove the rest).
588 cmd.args(mem::take(&mut post_objects_static));
589 } else {
590 cmd.arg(arg);
591 }
592 }
593 info!("{:?}", &cmd);
594 continue;
595 }
596
597 // Here's a terribly awful hack that really shouldn't be present in any
598 // compiler. Here an environment variable is supported to automatically
599 // retry the linker invocation if the linker looks like it segfaulted.
600 //
601 // Gee that seems odd, normally segfaults are things we want to know
602 // about! Unfortunately though in rust-lang/rust#38878 we're
603 // experiencing the linker segfaulting on Travis quite a bit which is
604 // causing quite a bit of pain to land PRs when they spuriously fail
605 // due to a segfault.
606 //
607 // The issue #38878 has some more debugging information on it as well,
608 // but this unfortunately looks like it's just a race condition in
609 // macOS's linker with some thread pool working in the background. It
610 // seems that no one currently knows a fix for this so in the meantime
611 // we're left with this...
612 if !retry_on_segfault || i > 3 {
613 break;
614 }
615 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
616 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
617 if out.contains(msg_segv) || out.contains(msg_bus) {
618 warn!(
619 "looks like the linker segfaulted when we tried to call it, \
620 automatically retrying again. cmd = {:?}, out = {}.",
621 cmd, out,
622 );
623 continue;
624 }
625
626 if is_illegal_instruction(&output.status) {
627 warn!(
628 "looks like the linker hit an illegal instruction when we \
629 tried to call it, automatically retrying again. cmd = {:?}, ]\
630 out = {}, status = {}.",
631 cmd, out, output.status,
632 );
633 continue;
634 }
635
636 #[cfg(unix)]
637 fn is_illegal_instruction(status: &ExitStatus) -> bool {
638 use std::os::unix::prelude::*;
639 status.signal() == Some(libc::SIGILL)
640 }
641
642 #[cfg(windows)]
643 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
644 false
645 }
646 }
647
648 match prog {
649 Ok(prog) => {
650 fn escape_string(s: &[u8]) -> String {
651 str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
652 let mut x = "Non-UTF-8 output: ".to_string();
653 x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
654 x
655 })
656 }
657 if !prog.status.success() {
658 let mut output = prog.stderr.clone();
659 output.extend_from_slice(&prog.stdout);
660 sess.struct_err(&format!(
661 "linking with `{}` failed: {}",
662 linker_path.display(),
663 prog.status
664 ))
665 .note(&format!("{:?}", &cmd))
666 .note(&escape_string(&output))
667 .emit();
668
669 // If MSVC's `link.exe` was expected but the return code
670 // is not a Microsoft LNK error then suggest a way to fix or
671 // install the Visual Studio build tools.
672 if let Some(code) = prog.status.code() {
673 if sess.target.target.options.is_like_msvc
674 && flavor == LinkerFlavor::Msvc
675 // Respect the command line override
676 && sess.opts.cg.linker.is_none()
677 // Match exactly "link.exe"
678 && linker_path.to_str() == Some("link.exe")
679 // All Microsoft `link.exe` linking error codes are
680 // four digit numbers in the range 1000 to 9999 inclusive
681 && (code < 1000 || code > 9999)
682 {
683 let is_vs_installed = windows_registry::find_vs_version().is_ok();
684 let has_linker = windows_registry::find_tool(
685 &sess.opts.target_triple.triple(),
686 "link.exe",
687 )
688 .is_some();
689
690 sess.note_without_error("`link.exe` returned an unexpected error");
691 if is_vs_installed && has_linker {
692 // the linker is broken
693 sess.note_without_error(
694 "the Visual Studio build tools may need to be repaired \
695 using the Visual Studio installer",
696 );
697 sess.note_without_error(
698 "or a necessary component may be missing from the \
699 \"C++ build tools\" workload",
700 );
701 } else if is_vs_installed {
702 // the linker is not installed
703 sess.note_without_error(
704 "in the Visual Studio installer, ensure the \
705 \"C++ build tools\" workload is selected",
706 );
707 } else {
708 // visual studio is not installed
709 sess.note_without_error(
710 "you may need to install Visual Studio build tools with the \
711 \"C++ build tools\" workload",
712 );
713 }
714 }
715 }
716
717 sess.abort_if_errors();
718 }
719 info!("linker stderr:\n{}", escape_string(&prog.stderr));
720 info!("linker stdout:\n{}", escape_string(&prog.stdout));
721 }
722 Err(e) => {
723 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
724
725 let mut linker_error = {
726 if linker_not_found {
727 sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
728 } else {
729 sess.struct_err(&format!(
730 "could not exec the linker `{}`",
731 linker_path.display()
732 ))
733 }
734 };
735
736 linker_error.note(&e.to_string());
737
738 if !linker_not_found {
739 linker_error.note(&format!("{:?}", &cmd));
740 }
741
742 linker_error.emit();
743
744 if sess.target.target.options.is_like_msvc && linker_not_found {
745 sess.note_without_error(
746 "the msvc targets depend on the msvc linker \
747 but `link.exe` was not found",
748 );
749 sess.note_without_error(
750 "please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 \
751 was installed with the Visual C++ option",
752 );
753 }
754 sess.abort_if_errors();
755 }
756 }
757
758 // On macOS, debuggers need this utility to get run to do some munging of
759 // the symbols. Note, though, that if the object files are being preserved
760 // for their debug information there's no need for us to run dsymutil.
761 if sess.target.target.options.is_like_osx
762 && sess.opts.debuginfo != DebugInfo::None
763 && !preserve_objects_for_their_debuginfo(sess)
764 {
765 if let Err(e) = Command::new("dsymutil").arg(out_filename).output() {
766 sess.fatal(&format!("failed to run dsymutil: {}", e))
767 }
768 }
769 }
770
771 fn link_sanitizers(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
772 // On macOS the runtimes are distributed as dylibs which should be linked to
773 // both executables and dynamic shared objects. Everywhere else the runtimes
774 // are currently distributed as static liraries which should be linked to
775 // executables only.
776 let needs_runtime = match crate_type {
777 CrateType::Executable => true,
778 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => {
779 sess.target.target.options.is_like_osx
780 }
781 CrateType::Rlib | CrateType::Staticlib => false,
782 };
783
784 if !needs_runtime {
785 return;
786 }
787
788 let sanitizer = sess.opts.debugging_opts.sanitizer;
789 if sanitizer.contains(SanitizerSet::ADDRESS) {
790 link_sanitizer_runtime(sess, linker, "asan");
791 }
792 if sanitizer.contains(SanitizerSet::LEAK) {
793 link_sanitizer_runtime(sess, linker, "lsan");
794 }
795 if sanitizer.contains(SanitizerSet::MEMORY) {
796 link_sanitizer_runtime(sess, linker, "msan");
797 }
798 if sanitizer.contains(SanitizerSet::THREAD) {
799 link_sanitizer_runtime(sess, linker, "tsan");
800 }
801 }
802
803 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
804 let default_sysroot = filesearch::get_or_default_sysroot();
805 let default_tlib =
806 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.triple());
807 let channel = option_env!("CFG_RELEASE_CHANNEL")
808 .map(|channel| format!("-{}", channel))
809 .unwrap_or_default();
810
811 match sess.opts.target_triple.triple() {
812 "x86_64-apple-darwin" => {
813 // On Apple platforms, the sanitizer is always built as a dylib, and
814 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
815 // rpath to the library as well (the rpath should be absolute, see
816 // PR #41352 for details).
817 let libname = format!("rustc{}_rt.{}", channel, name);
818 let rpath = default_tlib.to_str().expect("non-utf8 component in path");
819 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
820 linker.link_dylib(Symbol::intern(&libname));
821 }
822 "aarch64-fuchsia"
823 | "aarch64-unknown-linux-gnu"
824 | "x86_64-fuchsia"
825 | "x86_64-unknown-freebsd"
826 | "x86_64-unknown-linux-gnu" => {
827 let filename = format!("librustc{}_rt.{}.a", channel, name);
828 let path = default_tlib.join(&filename);
829 linker.link_whole_rlib(&path);
830 }
831 _ => {}
832 }
833 }
834
835 /// Returns a boolean indicating whether the specified crate should be ignored
836 /// during LTO.
837 ///
838 /// Crates ignored during LTO are not lumped together in the "massive object
839 /// file" that we create and are linked in their normal rlib states. See
840 /// comments below for what crates do not participate in LTO.
841 ///
842 /// It's unusual for a crate to not participate in LTO. Typically only
843 /// compiler-specific and unstable crates have a reason to not participate in
844 /// LTO.
845 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
846 // If our target enables builtin function lowering in LLVM then the
847 // crates providing these functions don't participate in LTO (e.g.
848 // no_builtins or compiler builtins crates).
849 !sess.target.target.options.no_builtins
850 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
851 }
852
853 fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
854 fn infer_from(
855 sess: &Session,
856 linker: Option<PathBuf>,
857 flavor: Option<LinkerFlavor>,
858 ) -> Option<(PathBuf, LinkerFlavor)> {
859 match (linker, flavor) {
860 (Some(linker), Some(flavor)) => Some((linker, flavor)),
861 // only the linker flavor is known; use the default linker for the selected flavor
862 (None, Some(flavor)) => Some((
863 PathBuf::from(match flavor {
864 LinkerFlavor::Em => {
865 if cfg!(windows) {
866 "emcc.bat"
867 } else {
868 "emcc"
869 }
870 }
871 LinkerFlavor::Gcc => {
872 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
873 // On historical Solaris systems, "cc" may have
874 // been Sun Studio, which is not flag-compatible
875 // with "gcc". This history casts a long shadow,
876 // and many modern illumos distributions today
877 // ship GCC as "gcc" without also making it
878 // available as "cc".
879 "gcc"
880 } else {
881 "cc"
882 }
883 }
884 LinkerFlavor::Ld => "ld",
885 LinkerFlavor::Msvc => "link.exe",
886 LinkerFlavor::Lld(_) => "lld",
887 LinkerFlavor::PtxLinker => "rust-ptx-linker",
888 }),
889 flavor,
890 )),
891 (Some(linker), None) => {
892 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
893 sess.fatal("couldn't extract file stem from specified linker")
894 });
895
896 let flavor = if stem == "emcc" {
897 LinkerFlavor::Em
898 } else if stem == "gcc"
899 || stem.ends_with("-gcc")
900 || stem == "clang"
901 || stem.ends_with("-clang")
902 {
903 LinkerFlavor::Gcc
904 } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
905 LinkerFlavor::Ld
906 } else if stem == "link" || stem == "lld-link" {
907 LinkerFlavor::Msvc
908 } else if stem == "lld" || stem == "rust-lld" {
909 LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
910 } else {
911 // fall back to the value in the target spec
912 sess.target.target.linker_flavor
913 };
914
915 Some((linker, flavor))
916 }
917 (None, None) => None,
918 }
919 }
920
921 // linker and linker flavor specified via command line have precedence over what the target
922 // specification specifies
923 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), sess.opts.cg.linker_flavor) {
924 return ret;
925 }
926
927 if let Some(ret) = infer_from(
928 sess,
929 sess.target.target.options.linker.clone().map(PathBuf::from),
930 Some(sess.target.target.linker_flavor),
931 ) {
932 return ret;
933 }
934
935 bug!("Not enough information provided to determine how to invoke the linker");
936 }
937
938 /// Returns a boolean indicating whether we should preserve the object files on
939 /// the filesystem for their debug information. This is often useful with
940 /// split-dwarf like schemes.
941 fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool {
942 // If the objects don't have debuginfo there's nothing to preserve.
943 if sess.opts.debuginfo == config::DebugInfo::None {
944 return false;
945 }
946
947 // If we're only producing artifacts that are archives, no need to preserve
948 // the objects as they're losslessly contained inside the archives.
949 let output_linked =
950 sess.crate_types().iter().any(|&x| x != CrateType::Rlib && x != CrateType::Staticlib);
951 if !output_linked {
952 return false;
953 }
954
955 // If we're on OSX then the equivalent of split dwarf is turned on by
956 // default. The final executable won't actually have any debug information
957 // except it'll have pointers to elsewhere. Historically we've always run
958 // `dsymutil` to "link all the dwarf together" but this is actually sort of
959 // a bummer for incremental compilation! (the whole point of split dwarf is
960 // that you don't do this sort of dwarf link).
961 //
962 // Basically as a result this just means that if we're on OSX and we're
963 // *not* running dsymutil then the object files are the only source of truth
964 // for debug information, so we must preserve them.
965 if sess.target.target.options.is_like_osx {
966 return !sess.opts.debugging_opts.run_dsymutil;
967 }
968
969 false
970 }
971
972 pub fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
973 sess.target_filesearch(PathKind::Native).search_path_dirs()
974 }
975
976 enum RlibFlavor {
977 Normal,
978 StaticlibBase,
979 }
980
981 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
982 let lib_args: Vec<_> = all_native_libs
983 .iter()
984 .filter(|l| relevant_lib(sess, l))
985 .filter_map(|lib| {
986 let name = lib.name?;
987 match lib.kind {
988 NativeLibKind::StaticNoBundle
989 | NativeLibKind::Dylib
990 | NativeLibKind::Unspecified => {
991 if sess.target.target.options.is_like_msvc {
992 Some(format!("{}.lib", name))
993 } else {
994 Some(format!("-l{}", name))
995 }
996 }
997 NativeLibKind::Framework => {
998 // ld-only syntax, since there are no frameworks in MSVC
999 Some(format!("-framework {}", name))
1000 }
1001 // These are included, no need to print them
1002 NativeLibKind::StaticBundle | NativeLibKind::RawDylib => None,
1003 }
1004 })
1005 .collect();
1006 if !lib_args.is_empty() {
1007 sess.note_without_error(
1008 "Link against the following native artifacts when linking \
1009 against this static library. The order and any duplication \
1010 can be significant on some platforms.",
1011 );
1012 // Prefix for greppability
1013 sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1014 }
1015 }
1016
1017 // Because windows-gnu target is meant to be self-contained for pure Rust code it bundles
1018 // own mingw-w64 libraries. These libraries are usually not compatible with mingw-w64
1019 // installed in the system. This breaks many cases where Rust is mixed with other languages
1020 // (e.g. *-sys crates).
1021 // We prefer system mingw-w64 libraries if they are available to avoid this issue.
1022 fn get_crt_libs_path(sess: &Session) -> Option<PathBuf> {
1023 fn find_exe_in_path<P>(exe_name: P) -> Option<PathBuf>
1024 where
1025 P: AsRef<Path>,
1026 {
1027 for dir in env::split_paths(&env::var_os("PATH")?) {
1028 let full_path = dir.join(&exe_name);
1029 if full_path.is_file() {
1030 return Some(fix_windows_verbatim_for_gcc(&full_path));
1031 }
1032 }
1033 None
1034 }
1035
1036 fn probe(sess: &Session) -> Option<PathBuf> {
1037 if let (linker, LinkerFlavor::Gcc) = linker_and_flavor(&sess) {
1038 let linker_path = if cfg!(windows) && linker.extension().is_none() {
1039 linker.with_extension("exe")
1040 } else {
1041 linker
1042 };
1043 if let Some(linker_path) = find_exe_in_path(linker_path) {
1044 let mingw_arch = match &sess.target.target.arch {
1045 x if x == "x86" => "i686",
1046 x => x,
1047 };
1048 let mingw_bits = &sess.target.target.target_pointer_width;
1049 let mingw_dir = format!("{}-w64-mingw32", mingw_arch);
1050 // Here we have path/bin/gcc but we need path/
1051 let mut path = linker_path;
1052 path.pop();
1053 path.pop();
1054 // Loosely based on Clang MinGW driver
1055 let probe_paths = vec![
1056 path.join(&mingw_dir).join("lib"), // Typical path
1057 path.join(&mingw_dir).join("sys-root/mingw/lib"), // Rare path
1058 path.join(format!(
1059 "lib/mingw/tools/install/mingw{}/{}/lib",
1060 &mingw_bits, &mingw_dir
1061 )), // Chocolatey is creative
1062 ];
1063 for probe_path in probe_paths {
1064 if probe_path.join("crt2.o").exists() {
1065 return Some(probe_path);
1066 };
1067 }
1068 };
1069 };
1070 None
1071 }
1072
1073 let mut system_library_path = sess.system_library_path.borrow_mut();
1074 match &*system_library_path {
1075 Some(Some(compiler_libs_path)) => Some(compiler_libs_path.clone()),
1076 Some(None) => None,
1077 None => {
1078 let path = probe(sess);
1079 *system_library_path = Some(path.clone());
1080 path
1081 }
1082 }
1083 }
1084
1085 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1086 // prefer system {,dll}crt2.o libs, see get_crt_libs_path comment for more details
1087 if sess.opts.debugging_opts.link_self_contained.is_none()
1088 && sess.target.target.llvm_target.contains("windows-gnu")
1089 {
1090 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1091 let file_path = compiler_libs_path.join(name);
1092 if file_path.exists() {
1093 return file_path;
1094 }
1095 }
1096 }
1097 let fs = sess.target_filesearch(PathKind::Native);
1098 let file_path = fs.get_lib_path().join(name);
1099 if file_path.exists() {
1100 return file_path;
1101 }
1102 // Special directory with objects used only in self-contained linkage mode
1103 if self_contained {
1104 let file_path = fs.get_self_contained_lib_path().join(name);
1105 if file_path.exists() {
1106 return file_path;
1107 }
1108 }
1109 for search_path in fs.search_paths() {
1110 let file_path = search_path.dir.join(name);
1111 if file_path.exists() {
1112 return file_path;
1113 }
1114 }
1115 PathBuf::from(name)
1116 }
1117
1118 fn exec_linker(
1119 sess: &Session,
1120 cmd: &Command,
1121 out_filename: &Path,
1122 tmpdir: &Path,
1123 ) -> io::Result<Output> {
1124 // When attempting to spawn the linker we run a risk of blowing out the
1125 // size limits for spawning a new process with respect to the arguments
1126 // we pass on the command line.
1127 //
1128 // Here we attempt to handle errors from the OS saying "your list of
1129 // arguments is too big" by reinvoking the linker again with an `@`-file
1130 // that contains all the arguments. The theory is that this is then
1131 // accepted on all linkers and the linker will read all its options out of
1132 // there instead of looking at the command line.
1133 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1134 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1135 Ok(child) => {
1136 let output = child.wait_with_output();
1137 flush_linked_file(&output, out_filename)?;
1138 return output;
1139 }
1140 Err(ref e) if command_line_too_big(e) => {
1141 info!("command line to linker was too big: {}", e);
1142 }
1143 Err(e) => return Err(e),
1144 }
1145 }
1146
1147 info!("falling back to passing arguments to linker via an @-file");
1148 let mut cmd2 = cmd.clone();
1149 let mut args = String::new();
1150 for arg in cmd2.take_args() {
1151 args.push_str(
1152 &Escape {
1153 arg: arg.to_str().unwrap(),
1154 is_like_msvc: sess.target.target.options.is_like_msvc,
1155 }
1156 .to_string(),
1157 );
1158 args.push_str("\n");
1159 }
1160 let file = tmpdir.join("linker-arguments");
1161 let bytes = if sess.target.target.options.is_like_msvc {
1162 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1163 // start the stream with a UTF-16 BOM
1164 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1165 // encode in little endian
1166 out.push(c as u8);
1167 out.push((c >> 8) as u8);
1168 }
1169 out
1170 } else {
1171 args.into_bytes()
1172 };
1173 fs::write(&file, &bytes)?;
1174 cmd2.arg(format!("@{}", file.display()));
1175 info!("invoking linker {:?}", cmd2);
1176 let output = cmd2.output();
1177 flush_linked_file(&output, out_filename)?;
1178 return output;
1179
1180 #[cfg(unix)]
1181 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1182 Ok(())
1183 }
1184
1185 #[cfg(windows)]
1186 fn flush_linked_file(
1187 command_output: &io::Result<Output>,
1188 out_filename: &Path,
1189 ) -> io::Result<()> {
1190 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1191 // even long after process exit, causing nasty, non-reproducible output bugs.
1192 //
1193 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1194 //
1195 // А full writeup of the original Chrome bug can be found at
1196 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1197
1198 if let &Ok(ref out) = command_output {
1199 if out.status.success() {
1200 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1201 of.sync_all()?;
1202 }
1203 }
1204 }
1205
1206 Ok(())
1207 }
1208
1209 #[cfg(unix)]
1210 fn command_line_too_big(err: &io::Error) -> bool {
1211 err.raw_os_error() == Some(::libc::E2BIG)
1212 }
1213
1214 #[cfg(windows)]
1215 fn command_line_too_big(err: &io::Error) -> bool {
1216 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1217 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1218 }
1219
1220 struct Escape<'a> {
1221 arg: &'a str,
1222 is_like_msvc: bool,
1223 }
1224
1225 impl<'a> fmt::Display for Escape<'a> {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 if self.is_like_msvc {
1228 // This is "documented" at
1229 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1230 //
1231 // Unfortunately there's not a great specification of the
1232 // syntax I could find online (at least) but some local
1233 // testing showed that this seemed sufficient-ish to catch
1234 // at least a few edge cases.
1235 write!(f, "\"")?;
1236 for c in self.arg.chars() {
1237 match c {
1238 '"' => write!(f, "\\{}", c)?,
1239 c => write!(f, "{}", c)?,
1240 }
1241 }
1242 write!(f, "\"")?;
1243 } else {
1244 // This is documented at https://linux.die.net/man/1/ld, namely:
1245 //
1246 // > Options in file are separated by whitespace. A whitespace
1247 // > character may be included in an option by surrounding the
1248 // > entire option in either single or double quotes. Any
1249 // > character (including a backslash) may be included by
1250 // > prefixing the character to be included with a backslash.
1251 //
1252 // We put an argument on each line, so all we need to do is
1253 // ensure the line is interpreted as one whole argument.
1254 for c in self.arg.chars() {
1255 match c {
1256 '\\' | ' ' => write!(f, "\\{}", c)?,
1257 c => write!(f, "{}", c)?,
1258 }
1259 }
1260 }
1261 Ok(())
1262 }
1263 }
1264 }
1265
1266 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1267 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1268 (CrateType::Executable, false, RelocModel::Pic) => LinkOutputKind::DynamicPicExe,
1269 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1270 (CrateType::Executable, true, RelocModel::Pic) => LinkOutputKind::StaticPicExe,
1271 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1272 (_, true, _) => LinkOutputKind::StaticDylib,
1273 (_, false, _) => LinkOutputKind::DynamicDylib,
1274 };
1275
1276 // Adjust the output kind to target capabilities.
1277 let opts = &sess.target.target.options;
1278 let pic_exe_supported = opts.position_independent_executables;
1279 let static_pic_exe_supported = opts.static_position_independent_executables;
1280 let static_dylib_supported = opts.crt_static_allows_dylibs;
1281 match kind {
1282 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1283 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1284 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1285 _ => kind,
1286 }
1287 }
1288
1289 /// Whether we link to our own CRT objects instead of relying on gcc to pull them.
1290 /// We only provide such support for a very limited number of targets.
1291 fn crt_objects_fallback(sess: &Session, crate_type: CrateType) -> bool {
1292 if let Some(self_contained) = sess.opts.debugging_opts.link_self_contained {
1293 return self_contained;
1294 }
1295
1296 match sess.target.target.options.crt_objects_fallback {
1297 // FIXME: Find a better heuristic for "native musl toolchain is available",
1298 // based on host and linker path, for example.
1299 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1300 Some(CrtObjectsFallback::Musl) => sess.crt_static(Some(crate_type)),
1301 // FIXME: Find some heuristic for "native mingw toolchain is available",
1302 // likely based on `get_crt_libs_path` (https://github.com/rust-lang/rust/pull/67429).
1303 Some(CrtObjectsFallback::Mingw) => {
1304 sess.host == sess.target.target && sess.target.target.target_vendor != "uwp"
1305 }
1306 // FIXME: Figure out cases in which WASM needs to link with a native toolchain.
1307 Some(CrtObjectsFallback::Wasm) => true,
1308 None => false,
1309 }
1310 }
1311
1312 /// Add pre-link object files defined by the target spec.
1313 fn add_pre_link_objects(
1314 cmd: &mut dyn Linker,
1315 sess: &Session,
1316 link_output_kind: LinkOutputKind,
1317 self_contained: bool,
1318 ) {
1319 let opts = &sess.target.target.options;
1320 let objects =
1321 if self_contained { &opts.pre_link_objects_fallback } else { &opts.pre_link_objects };
1322 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1323 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1324 }
1325 }
1326
1327 /// Add post-link object files defined by the target spec.
1328 fn add_post_link_objects(
1329 cmd: &mut dyn Linker,
1330 sess: &Session,
1331 link_output_kind: LinkOutputKind,
1332 self_contained: bool,
1333 ) {
1334 let opts = &sess.target.target.options;
1335 let objects =
1336 if self_contained { &opts.post_link_objects_fallback } else { &opts.post_link_objects };
1337 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1338 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1339 }
1340 }
1341
1342 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1343 /// FIXME: Determine where exactly these args need to be inserted.
1344 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1345 if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
1346 cmd.args(args);
1347 }
1348 cmd.args(&sess.opts.debugging_opts.pre_link_args);
1349 }
1350
1351 /// Add a link script embedded in the target, if applicable.
1352 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1353 match (crate_type, &sess.target.target.options.link_script) {
1354 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1355 if !sess.target.target.options.linker_is_gnu {
1356 sess.fatal("can only use link script when linking with GNU-like linker");
1357 }
1358
1359 let file_name = ["rustc", &sess.target.target.llvm_target, "linkfile.ld"].join("-");
1360
1361 let path = tmpdir.join(file_name);
1362 if let Err(e) = fs::write(&path, script) {
1363 sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1364 }
1365
1366 cmd.arg("--script");
1367 cmd.arg(path);
1368 }
1369 _ => {}
1370 }
1371 }
1372
1373 /// Add arbitrary "user defined" args defined from command line and by `#[link_args]` attributes.
1374 /// FIXME: Determine where exactly these args need to be inserted.
1375 fn add_user_defined_link_args(
1376 cmd: &mut dyn Linker,
1377 sess: &Session,
1378 codegen_results: &CodegenResults,
1379 ) {
1380 cmd.args(&sess.opts.cg.link_args);
1381 cmd.args(&*codegen_results.crate_info.link_args);
1382 }
1383
1384 /// Add arbitrary "late link" args defined by the target spec.
1385 /// FIXME: Determine where exactly these args need to be inserted.
1386 fn add_late_link_args(
1387 cmd: &mut dyn Linker,
1388 sess: &Session,
1389 flavor: LinkerFlavor,
1390 crate_type: CrateType,
1391 codegen_results: &CodegenResults,
1392 ) {
1393 if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
1394 cmd.args(args);
1395 }
1396 let any_dynamic_crate = crate_type == CrateType::Dylib
1397 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1398 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1399 });
1400 if any_dynamic_crate {
1401 if let Some(args) = sess.target.target.options.late_link_args_dynamic.get(&flavor) {
1402 cmd.args(args);
1403 }
1404 } else {
1405 if let Some(args) = sess.target.target.options.late_link_args_static.get(&flavor) {
1406 cmd.args(args);
1407 }
1408 }
1409 }
1410
1411 /// Add arbitrary "post-link" args defined by the target spec.
1412 /// FIXME: Determine where exactly these args need to be inserted.
1413 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1414 if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
1415 cmd.args(args);
1416 }
1417 }
1418
1419 /// Add object files containing code from the current crate.
1420 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1421 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1422 cmd.add_object(obj);
1423 }
1424 }
1425
1426 /// Add object files for allocator code linked once for the whole crate tree.
1427 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1428 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1429 cmd.add_object(obj);
1430 }
1431 }
1432
1433 /// Add object files containing metadata for the current crate.
1434 fn add_local_crate_metadata_objects(
1435 cmd: &mut dyn Linker,
1436 crate_type: CrateType,
1437 codegen_results: &CodegenResults,
1438 ) {
1439 // When linking a dynamic library, we put the metadata into a section of the
1440 // executable. This metadata is in a separate object file from the main
1441 // object file, so we link that in here.
1442 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1443 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1444 {
1445 cmd.add_object(obj);
1446 }
1447 }
1448 }
1449
1450 /// Link native libraries corresponding to the current crate and all libraries corresponding to
1451 /// all its dependency crates.
1452 /// FIXME: Consider combining this with the functions above adding object files for the local crate.
1453 fn link_local_crate_native_libs_and_dependent_crate_libs<'a, B: ArchiveBuilder<'a>>(
1454 cmd: &mut dyn Linker,
1455 sess: &'a Session,
1456 crate_type: CrateType,
1457 codegen_results: &CodegenResults,
1458 tmpdir: &Path,
1459 ) {
1460 // Take careful note of the ordering of the arguments we pass to the linker
1461 // here. Linkers will assume that things on the left depend on things to the
1462 // right. Things on the right cannot depend on things on the left. This is
1463 // all formally implemented in terms of resolving symbols (libs on the right
1464 // resolve unknown symbols of libs on the left, but not vice versa).
1465 //
1466 // For this reason, we have organized the arguments we pass to the linker as
1467 // such:
1468 //
1469 // 1. The local object that LLVM just generated
1470 // 2. Local native libraries
1471 // 3. Upstream rust libraries
1472 // 4. Upstream native libraries
1473 //
1474 // The rationale behind this ordering is that those items lower down in the
1475 // list can't depend on items higher up in the list. For example nothing can
1476 // depend on what we just generated (e.g., that'd be a circular dependency).
1477 // Upstream rust libraries are not allowed to depend on our local native
1478 // libraries as that would violate the structure of the DAG, in that
1479 // scenario they are required to link to them as well in a shared fashion.
1480 //
1481 // Note that upstream rust libraries may contain native dependencies as
1482 // well, but they also can't depend on what we just started to add to the
1483 // link line. And finally upstream native libraries can't depend on anything
1484 // in this DAG so far because they're only dylibs and dylibs can only depend
1485 // on other dylibs (e.g., other native deps).
1486 //
1487 // If -Zlink-native-libraries=false is set, then the assumption is that an
1488 // external build system already has the native dependencies defined, and it
1489 // will provide them to the linker itself.
1490 if sess.opts.debugging_opts.link_native_libraries {
1491 add_local_native_libraries(cmd, sess, codegen_results);
1492 }
1493 add_upstream_rust_crates::<B>(cmd, sess, codegen_results, crate_type, tmpdir);
1494 if sess.opts.debugging_opts.link_native_libraries {
1495 add_upstream_native_libraries(cmd, sess, codegen_results, crate_type);
1496 }
1497 }
1498
1499 /// Add sysroot and other globally set directories to the directory search list.
1500 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1501 // Prefer system mingw-w64 libs, see get_crt_libs_path comment for more details.
1502 if sess.opts.debugging_opts.link_self_contained.is_none()
1503 && cfg!(windows)
1504 && sess.target.target.llvm_target.contains("windows-gnu")
1505 {
1506 if let Some(compiler_libs_path) = get_crt_libs_path(sess) {
1507 cmd.include_path(&compiler_libs_path);
1508 }
1509 }
1510
1511 // The default library location, we need this to find the runtime.
1512 // The location of crates will be determined as needed.
1513 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1514 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1515
1516 // Special directory with libraries used only in self-contained linkage mode
1517 if self_contained {
1518 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1519 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1520 }
1521 }
1522
1523 /// Add options making relocation sections in the produced ELF files read-only
1524 /// and suppressing lazy binding.
1525 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1526 match sess.opts.debugging_opts.relro_level.unwrap_or(sess.target.target.options.relro_level) {
1527 RelroLevel::Full => cmd.full_relro(),
1528 RelroLevel::Partial => cmd.partial_relro(),
1529 RelroLevel::Off => cmd.no_relro(),
1530 RelroLevel::None => {}
1531 }
1532 }
1533
1534 /// Add library search paths used at runtime by dynamic linkers.
1535 fn add_rpath_args(
1536 cmd: &mut dyn Linker,
1537 sess: &Session,
1538 codegen_results: &CodegenResults,
1539 out_filename: &Path,
1540 ) {
1541 // FIXME (#2397): At some point we want to rpath our guesses as to
1542 // where extern libraries might live, based on the
1543 // addl_lib_search_paths
1544 if sess.opts.cg.rpath {
1545 let target_triple = sess.opts.target_triple.triple();
1546 let mut get_install_prefix_lib_path = || {
1547 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1548 let tlib = filesearch::relative_target_lib_path(&sess.sysroot, target_triple);
1549 let mut path = PathBuf::from(install_prefix);
1550 path.push(&tlib);
1551
1552 path
1553 };
1554 let mut rpath_config = RPathConfig {
1555 used_crates: &codegen_results.crate_info.used_crates_dynamic,
1556 out_filename: out_filename.to_path_buf(),
1557 has_rpath: sess.target.target.options.has_rpath,
1558 is_like_osx: sess.target.target.options.is_like_osx,
1559 linker_is_gnu: sess.target.target.options.linker_is_gnu,
1560 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1561 };
1562 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1563 }
1564 }
1565
1566 /// Produce the linker command line containing linker path and arguments.
1567 /// `NO-OPT-OUT` marks the arguments that cannot be removed from the command line
1568 /// by the user without creating a custom target specification.
1569 /// `OBJECT-FILES` specify whether the arguments can add object files.
1570 /// `CUSTOMIZATION-POINT` means that arbitrary arguments defined by the user
1571 /// or by the target spec can be inserted here.
1572 /// `AUDIT-ORDER` - need to figure out whether the option is order-dependent or not.
1573 fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
1574 path: &Path,
1575 flavor: LinkerFlavor,
1576 sess: &'a Session,
1577 crate_type: CrateType,
1578 tmpdir: &Path,
1579 out_filename: &Path,
1580 codegen_results: &CodegenResults,
1581 target_cpu: &str,
1582 ) -> Command {
1583 let crt_objects_fallback = crt_objects_fallback(sess, crate_type);
1584 let base_cmd = get_linker(sess, path, flavor, crt_objects_fallback);
1585 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
1586 // to the linker args construction.
1587 assert!(base_cmd.get_args().is_empty() || sess.target.target.target_vendor == "uwp");
1588 let cmd = &mut *codegen_results.linker_info.to_linker(base_cmd, &sess, flavor, target_cpu);
1589 let link_output_kind = link_output_kind(sess, crate_type);
1590
1591 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1592 add_pre_link_args(cmd, sess, flavor);
1593
1594 // NO-OPT-OUT
1595 add_link_script(cmd, sess, tmpdir, crate_type);
1596
1597 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1598 if sess.target.target.options.is_like_fuchsia && crate_type == CrateType::Executable {
1599 let prefix = if sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
1600 "asan/"
1601 } else {
1602 ""
1603 };
1604 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
1605 }
1606
1607 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1608 if sess.target.target.options.eh_frame_header {
1609 cmd.add_eh_frame_header();
1610 }
1611
1612 // NO-OPT-OUT, OBJECT-FILES-NO
1613 if crt_objects_fallback {
1614 cmd.no_crt_objects();
1615 }
1616
1617 // NO-OPT-OUT, OBJECT-FILES-YES
1618 add_pre_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1619
1620 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1621 if sess.target.target.options.is_like_emscripten {
1622 cmd.arg("-s");
1623 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
1624 "DISABLE_EXCEPTION_CATCHING=1"
1625 } else {
1626 "DISABLE_EXCEPTION_CATCHING=0"
1627 });
1628 }
1629
1630 // OBJECT-FILES-YES, AUDIT-ORDER
1631 link_sanitizers(sess, crate_type, cmd);
1632
1633 // OBJECT-FILES-NO, AUDIT-ORDER
1634 // Linker plugins should be specified early in the list of arguments
1635 // FIXME: How "early" exactly?
1636 cmd.linker_plugin_lto();
1637
1638 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1639 // FIXME: Order-dependent, at least relatively to other args adding searh directories.
1640 add_library_search_dirs(cmd, sess, crt_objects_fallback);
1641
1642 // OBJECT-FILES-YES
1643 add_local_crate_regular_objects(cmd, codegen_results);
1644
1645 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1646 cmd.output_filename(out_filename);
1647
1648 // OBJECT-FILES-NO, AUDIT-ORDER
1649 if crate_type == CrateType::Executable && sess.target.target.options.is_like_windows {
1650 if let Some(ref s) = codegen_results.windows_subsystem {
1651 cmd.subsystem(s);
1652 }
1653 }
1654
1655 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1656 // If we're building something like a dynamic library then some platforms
1657 // need to make sure that all symbols are exported correctly from the
1658 // dynamic library.
1659 cmd.export_symbols(tmpdir, crate_type);
1660
1661 // OBJECT-FILES-YES
1662 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
1663
1664 // OBJECT-FILES-YES
1665 add_local_crate_allocator_objects(cmd, codegen_results);
1666
1667 // OBJECT-FILES-NO, AUDIT-ORDER
1668 // FIXME: Order dependent, applies to the following objects. Where should it be placed?
1669 // Try to strip as much out of the generated object by removing unused
1670 // sections if possible. See more comments in linker.rs
1671 if sess.opts.cg.link_dead_code != Some(true) {
1672 let keep_metadata = crate_type == CrateType::Dylib;
1673 cmd.gc_sections(keep_metadata);
1674 }
1675
1676 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1677 cmd.set_output_kind(link_output_kind, out_filename);
1678
1679 // OBJECT-FILES-NO, AUDIT-ORDER
1680 add_relro_args(cmd, sess);
1681
1682 // OBJECT-FILES-NO, AUDIT-ORDER
1683 // Pass optimization flags down to the linker.
1684 cmd.optimize();
1685
1686 // OBJECT-FILES-NO, AUDIT-ORDER
1687 // Pass debuginfo and strip flags down to the linker.
1688 cmd.debuginfo(sess.opts.debugging_opts.strip);
1689
1690 // OBJECT-FILES-NO, AUDIT-ORDER
1691 // We want to prevent the compiler from accidentally leaking in any system libraries,
1692 // so by default we tell linkers not to link to any default libraries.
1693 if !sess.opts.cg.default_linker_libraries && sess.target.target.options.no_default_libraries {
1694 cmd.no_default_libraries();
1695 }
1696
1697 // OBJECT-FILES-YES
1698 link_local_crate_native_libs_and_dependent_crate_libs::<B>(
1699 cmd,
1700 sess,
1701 crate_type,
1702 codegen_results,
1703 tmpdir,
1704 );
1705
1706 // OBJECT-FILES-NO, AUDIT-ORDER
1707 if sess.opts.cg.profile_generate.enabled() || sess.opts.debugging_opts.instrument_coverage {
1708 cmd.pgo_gen();
1709 }
1710
1711 // OBJECT-FILES-NO, AUDIT-ORDER
1712 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
1713 cmd.control_flow_guard();
1714 }
1715
1716 // OBJECT-FILES-NO, AUDIT-ORDER
1717 add_rpath_args(cmd, sess, codegen_results, out_filename);
1718
1719 // OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1720 add_user_defined_link_args(cmd, sess, codegen_results);
1721
1722 // NO-OPT-OUT, OBJECT-FILES-NO, AUDIT-ORDER
1723 cmd.finalize();
1724
1725 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1726 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
1727
1728 // NO-OPT-OUT, OBJECT-FILES-YES
1729 add_post_link_objects(cmd, sess, link_output_kind, crt_objects_fallback);
1730
1731 // NO-OPT-OUT, OBJECT-FILES-MAYBE, CUSTOMIZATION-POINT
1732 add_post_link_args(cmd, sess, flavor);
1733
1734 cmd.take_cmd()
1735 }
1736
1737 // # Native library linking
1738 //
1739 // User-supplied library search paths (-L on the command line). These are
1740 // the same paths used to find Rust crates, so some of them may have been
1741 // added already by the previous crate linking code. This only allows them
1742 // to be found at compile time so it is still entirely up to outside
1743 // forces to make sure that library can be found at runtime.
1744 //
1745 // Also note that the native libraries linked here are only the ones located
1746 // in the current crate. Upstream crates with native library dependencies
1747 // may have their native library pulled in above.
1748 fn add_local_native_libraries(
1749 cmd: &mut dyn Linker,
1750 sess: &Session,
1751 codegen_results: &CodegenResults,
1752 ) {
1753 let filesearch = sess.target_filesearch(PathKind::All);
1754 for search_path in filesearch.search_paths() {
1755 match search_path.kind {
1756 PathKind::Framework => {
1757 cmd.framework_path(&search_path.dir);
1758 }
1759 _ => {
1760 cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir));
1761 }
1762 }
1763 }
1764
1765 let relevant_libs =
1766 codegen_results.crate_info.used_libraries.iter().filter(|l| relevant_lib(sess, l));
1767
1768 let search_path = archive_search_paths(sess);
1769 for lib in relevant_libs {
1770 let name = match lib.name {
1771 Some(l) => l,
1772 None => continue,
1773 };
1774 match lib.kind {
1775 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
1776 NativeLibKind::Framework => cmd.link_framework(name),
1777 NativeLibKind::StaticNoBundle => cmd.link_staticlib(name),
1778 NativeLibKind::StaticBundle => cmd.link_whole_staticlib(name, &search_path),
1779 NativeLibKind::RawDylib => {
1780 // FIXME(#58713): Proper handling for raw dylibs.
1781 bug!("raw_dylib feature not yet implemented");
1782 }
1783 }
1784 }
1785 }
1786
1787 // # Rust Crate linking
1788 //
1789 // Rust crates are not considered at all when creating an rlib output. All
1790 // dependencies will be linked when producing the final output (instead of
1791 // the intermediate rlib version)
1792 fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
1793 cmd: &mut dyn Linker,
1794 sess: &'a Session,
1795 codegen_results: &CodegenResults,
1796 crate_type: CrateType,
1797 tmpdir: &Path,
1798 ) {
1799 // All of the heavy lifting has previously been accomplished by the
1800 // dependency_format module of the compiler. This is just crawling the
1801 // output of that module, adding crates as necessary.
1802 //
1803 // Linking to a rlib involves just passing it to the linker (the linker
1804 // will slurp up the object files inside), and linking to a dynamic library
1805 // involves just passing the right -l flag.
1806
1807 let (_, data) = codegen_results
1808 .crate_info
1809 .dependency_formats
1810 .iter()
1811 .find(|(ty, _)| *ty == crate_type)
1812 .expect("failed to find crate type in dependency format list");
1813
1814 // Invoke get_used_crates to ensure that we get a topological sorting of
1815 // crates.
1816 let deps = &codegen_results.crate_info.used_crates_dynamic;
1817
1818 // There's a few internal crates in the standard library (aka libcore and
1819 // libstd) which actually have a circular dependence upon one another. This
1820 // currently arises through "weak lang items" where libcore requires things
1821 // like `rust_begin_unwind` but libstd ends up defining it. To get this
1822 // circular dependence to work correctly in all situations we'll need to be
1823 // sure to correctly apply the `--start-group` and `--end-group` options to
1824 // GNU linkers, otherwise if we don't use any other symbol from the standard
1825 // library it'll get discarded and the whole application won't link.
1826 //
1827 // In this loop we're calculating the `group_end`, after which crate to
1828 // pass `--end-group` and `group_start`, before which crate to pass
1829 // `--start-group`. We currently do this by passing `--end-group` after
1830 // the first crate (when iterating backwards) that requires a lang item
1831 // defined somewhere else. Once that's set then when we've defined all the
1832 // necessary lang items we'll pass `--start-group`.
1833 //
1834 // Note that this isn't amazing logic for now but it should do the trick
1835 // for the current implementation of the standard library.
1836 let mut group_end = None;
1837 let mut group_start = None;
1838 // Crates available for linking thus far.
1839 let mut available = FxHashSet::default();
1840 // Crates required to satisfy dependencies discovered so far.
1841 let mut required = FxHashSet::default();
1842
1843 let info = &codegen_results.crate_info;
1844 for &(cnum, _) in deps.iter().rev() {
1845 if let Some(missing) = info.missing_lang_items.get(&cnum) {
1846 let missing_crates = missing.iter().map(|i| info.lang_item_to_crate.get(i).copied());
1847 required.extend(missing_crates);
1848 }
1849
1850 required.insert(Some(cnum));
1851 available.insert(Some(cnum));
1852
1853 if required.len() > available.len() && group_end.is_none() {
1854 group_end = Some(cnum);
1855 }
1856 if required.len() == available.len() && group_end.is_some() {
1857 group_start = Some(cnum);
1858 break;
1859 }
1860 }
1861
1862 // If we didn't end up filling in all lang items from upstream crates then
1863 // we'll be filling it in with our crate. This probably means we're the
1864 // standard library itself, so skip this for now.
1865 if group_end.is_some() && group_start.is_none() {
1866 group_end = None;
1867 }
1868
1869 let mut compiler_builtins = None;
1870
1871 for &(cnum, _) in deps.iter() {
1872 if group_start == Some(cnum) {
1873 cmd.group_start();
1874 }
1875
1876 // We may not pass all crates through to the linker. Some crates may
1877 // appear statically in an existing dylib, meaning we'll pick up all the
1878 // symbols from the dylib.
1879 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1880 match data[cnum.as_usize() - 1] {
1881 _ if codegen_results.crate_info.profiler_runtime == Some(cnum) => {
1882 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1883 }
1884 // compiler-builtins are always placed last to ensure that they're
1885 // linked correctly.
1886 _ if codegen_results.crate_info.compiler_builtins == Some(cnum) => {
1887 assert!(compiler_builtins.is_none());
1888 compiler_builtins = Some(cnum);
1889 }
1890 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
1891 Linkage::Static => {
1892 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1893 }
1894 Linkage::Dynamic => add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0),
1895 }
1896
1897 if group_end == Some(cnum) {
1898 cmd.group_end();
1899 }
1900 }
1901
1902 // compiler-builtins are always placed last to ensure that they're
1903 // linked correctly.
1904 // We must always link the `compiler_builtins` crate statically. Even if it
1905 // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic`
1906 // is used)
1907 if let Some(cnum) = compiler_builtins {
1908 add_static_crate::<B>(cmd, sess, codegen_results, tmpdir, crate_type, cnum);
1909 }
1910
1911 // Converts a library file-stem into a cc -l argument
1912 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1913 if stem.starts_with("lib") && !config.target.options.is_like_windows {
1914 &stem[3..]
1915 } else {
1916 stem
1917 }
1918 }
1919
1920 // Adds the static "rlib" versions of all crates to the command line.
1921 // There's a bit of magic which happens here specifically related to LTO and
1922 // dynamic libraries. Specifically:
1923 //
1924 // * For LTO, we remove upstream object files.
1925 // * For dylibs we remove metadata and bytecode from upstream rlibs
1926 //
1927 // When performing LTO, almost(*) all of the bytecode from the upstream
1928 // libraries has already been included in our object file output. As a
1929 // result we need to remove the object files in the upstream libraries so
1930 // the linker doesn't try to include them twice (or whine about duplicate
1931 // symbols). We must continue to include the rest of the rlib, however, as
1932 // it may contain static native libraries which must be linked in.
1933 //
1934 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1935 // their bytecode wasn't included. The object files in those libraries must
1936 // still be passed to the linker.
1937 //
1938 // When making a dynamic library, linkers by default don't include any
1939 // object files in an archive if they're not necessary to resolve the link.
1940 // We basically want to convert the archive (rlib) to a dylib, though, so we
1941 // *do* want everything included in the output, regardless of whether the
1942 // linker thinks it's needed or not. As a result we must use the
1943 // --whole-archive option (or the platform equivalent). When using this
1944 // option the linker will fail if there are non-objects in the archive (such
1945 // as our own metadata and/or bytecode). All in all, for rlibs to be
1946 // entirely included in dylibs, we need to remove all non-object files.
1947 //
1948 // Note, however, that if we're not doing LTO or we're not producing a dylib
1949 // (aka we're making an executable), we can just pass the rlib blindly to
1950 // the linker (fast) because it's fine if it's not actually included as
1951 // we're at the end of the dependency chain.
1952 fn add_static_crate<'a, B: ArchiveBuilder<'a>>(
1953 cmd: &mut dyn Linker,
1954 sess: &'a Session,
1955 codegen_results: &CodegenResults,
1956 tmpdir: &Path,
1957 crate_type: CrateType,
1958 cnum: CrateNum,
1959 ) {
1960 let src = &codegen_results.crate_info.used_crate_source[&cnum];
1961 let cratepath = &src.rlib.as_ref().unwrap().0;
1962
1963 // See the comment above in `link_staticlib` and `link_rlib` for why if
1964 // there's a static library that's not relevant we skip all object
1965 // files.
1966 let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
1967 let skip_native = native_libs
1968 .iter()
1969 .any(|lib| lib.kind == NativeLibKind::StaticBundle && !relevant_lib(sess, lib));
1970
1971 if (!are_upstream_rust_objects_already_included(sess)
1972 || ignored_for_lto(sess, &codegen_results.crate_info, cnum))
1973 && crate_type != CrateType::Dylib
1974 && !skip_native
1975 {
1976 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1977 return;
1978 }
1979
1980 let dst = tmpdir.join(cratepath.file_name().unwrap());
1981 let name = cratepath.file_name().unwrap().to_str().unwrap();
1982 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1983
1984 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
1985 let mut archive = <B as ArchiveBuilder>::new(sess, &dst, Some(cratepath));
1986 archive.update_symbols();
1987
1988 let mut any_objects = false;
1989 for f in archive.src_files() {
1990 if f == METADATA_FILENAME {
1991 archive.remove_file(&f);
1992 continue;
1993 }
1994
1995 let canonical = f.replace("-", "_");
1996 let canonical_name = name.replace("-", "_");
1997
1998 let is_rust_object =
1999 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2000
2001 // If we've been requested to skip all native object files
2002 // (those not generated by the rust compiler) then we can skip
2003 // this file. See above for why we may want to do this.
2004 let skip_because_cfg_say_so = skip_native && !is_rust_object;
2005
2006 // If we're performing LTO and this is a rust-generated object
2007 // file, then we don't need the object file as it's part of the
2008 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2009 // though, so we let that object file slide.
2010 let skip_because_lto = are_upstream_rust_objects_already_included(sess)
2011 && is_rust_object
2012 && (sess.target.target.options.no_builtins
2013 || !codegen_results.crate_info.is_no_builtins.contains(&cnum));
2014
2015 if skip_because_cfg_say_so || skip_because_lto {
2016 archive.remove_file(&f);
2017 } else {
2018 any_objects = true;
2019 }
2020 }
2021
2022 if !any_objects {
2023 return;
2024 }
2025 archive.build();
2026
2027 // If we're creating a dylib, then we need to include the
2028 // whole of each object in our archive into that artifact. This is
2029 // because a `dylib` can be reused as an intermediate artifact.
2030 //
2031 // Note, though, that we don't want to include the whole of a
2032 // compiler-builtins crate (e.g., compiler-rt) because it'll get
2033 // repeatedly linked anyway.
2034 if crate_type == CrateType::Dylib
2035 && codegen_results.crate_info.compiler_builtins != Some(cnum)
2036 {
2037 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
2038 } else {
2039 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
2040 }
2041 });
2042 }
2043
2044 // Same thing as above, but for dynamic crates instead of static crates.
2045 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2046 // Just need to tell the linker about where the library lives and
2047 // what its name is
2048 let parent = cratepath.parent();
2049 if let Some(dir) = parent {
2050 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2051 }
2052 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
2053 cmd.link_rust_dylib(
2054 Symbol::intern(&unlib(&sess.target, filestem)),
2055 parent.unwrap_or(Path::new("")),
2056 );
2057 }
2058 }
2059
2060 // Link in all of our upstream crates' native dependencies. Remember that
2061 // all of these upstream native dependencies are all non-static
2062 // dependencies. We've got two cases then:
2063 //
2064 // 1. The upstream crate is an rlib. In this case we *must* link in the
2065 // native dependency because the rlib is just an archive.
2066 //
2067 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
2068 // have the dependency present on the system somewhere. Thus, we don't
2069 // gain a whole lot from not linking in the dynamic dependency to this
2070 // crate as well.
2071 //
2072 // The use case for this is a little subtle. In theory the native
2073 // dependencies of a crate are purely an implementation detail of the crate
2074 // itself, but the problem arises with generic and inlined functions. If a
2075 // generic function calls a native function, then the generic function must
2076 // be instantiated in the target crate, meaning that the native symbol must
2077 // also be resolved in the target crate.
2078 fn add_upstream_native_libraries(
2079 cmd: &mut dyn Linker,
2080 sess: &Session,
2081 codegen_results: &CodegenResults,
2082 crate_type: CrateType,
2083 ) {
2084 // Be sure to use a topological sorting of crates because there may be
2085 // interdependencies between native libraries. When passing -nodefaultlibs,
2086 // for example, almost all native libraries depend on libc, so we have to
2087 // make sure that's all the way at the right (liblibc is near the base of
2088 // the dependency chain).
2089 //
2090 // This passes RequireStatic, but the actual requirement doesn't matter,
2091 // we're just getting an ordering of crate numbers, we're not worried about
2092 // the paths.
2093 let (_, data) = codegen_results
2094 .crate_info
2095 .dependency_formats
2096 .iter()
2097 .find(|(ty, _)| *ty == crate_type)
2098 .expect("failed to find crate type in dependency format list");
2099
2100 let crates = &codegen_results.crate_info.used_crates_static;
2101 for &(cnum, _) in crates {
2102 for lib in codegen_results.crate_info.native_libraries[&cnum].iter() {
2103 let name = match lib.name {
2104 Some(l) => l,
2105 None => continue,
2106 };
2107 if !relevant_lib(sess, &lib) {
2108 continue;
2109 }
2110 match lib.kind {
2111 NativeLibKind::Dylib | NativeLibKind::Unspecified => cmd.link_dylib(name),
2112 NativeLibKind::Framework => cmd.link_framework(name),
2113 NativeLibKind::StaticNoBundle => {
2114 // Link "static-nobundle" native libs only if the crate they originate from
2115 // is being linked statically to the current crate. If it's linked dynamically
2116 // or is an rlib already included via some other dylib crate, the symbols from
2117 // native libs will have already been included in that dylib.
2118 if data[cnum.as_usize() - 1] == Linkage::Static {
2119 cmd.link_staticlib(name)
2120 }
2121 }
2122 // ignore statically included native libraries here as we've
2123 // already included them when we included the rust library
2124 // previously
2125 NativeLibKind::StaticBundle => {}
2126 NativeLibKind::RawDylib => {
2127 // FIXME(#58713): Proper handling for raw dylibs.
2128 bug!("raw_dylib feature not yet implemented");
2129 }
2130 }
2131 }
2132 }
2133 }
2134
2135 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2136 match lib.cfg {
2137 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, None),
2138 None => true,
2139 }
2140 }
2141
2142 fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2143 match sess.lto() {
2144 config::Lto::Fat => true,
2145 config::Lto::Thin => {
2146 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2147 // any upstream object files have not been copied yet.
2148 !sess.opts.cg.linker_plugin_lto.enabled()
2149 }
2150 config::Lto::No | config::Lto::ThinLocal => false,
2151 }
2152 }