1mod raw_dylib;
2
3use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{ExitStatus, Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
11
12use cc::windows_registry;
13use itertools::Itertools;
14use regex::Regex;
15use rustc_arena::TypedArena;
16use rustc_ast::CRATE_NODE_ID;
17use rustc_data_structures::fx::FxIndexSet;
18use rustc_data_structures::memmap::Mmap;
19use rustc_data_structures::temp_dir::MaybeTempDir;
20use rustc_errors::{DiagCtxtHandle, LintDiagnostic};
21use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
22use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
23use rustc_macros::LintDiagnostic;
24use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
25use rustc_metadata::{
26 NativeLibSearchFallback, find_native_static_library, walk_native_lib_search_dirs,
27};
28use rustc_middle::bug;
29use rustc_middle::lint::lint_level;
30use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
31use rustc_middle::middle::dependency_format::Linkage;
32use rustc_middle::middle::exported_symbols::SymbolExportKind;
33use rustc_session::config::{
34 self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
35 OutputType, PrintKind, SplitDwarfKind, Strip,
36};
37use rustc_session::lint::builtin::LINKER_MESSAGES;
38use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
39use rustc_session::search_paths::PathKind;
40use rustc_session::utils::NativeLibKind;
41use rustc_session::{Session, filesearch};
44use rustc_span::Symbol;
45use rustc_target::spec::crt_objects::CrtObjects;
46use rustc_target::spec::{
47 BinaryFormat, Cc, LinkOutputKind, LinkSelfContainedComponents, LinkSelfContainedDefault,
48 LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy, RelocModel, RelroLevel,
49 SanitizerSet, SplitDebuginfo,
50};
51use tempfile::Builder as TempFileBuilder;
52use tracing::{debug, info, warn};
53
54use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
55use super::command::Command;
56use super::linker::{self, Linker};
57use super::metadata::{MetadataPosition, create_wrapper_file};
58use super::rpath::{self, RPathConfig};
59use super::{apple, versioned_llvm_target};
60use crate::{
61 CodegenResults, CompiledModule, CrateInfo, NativeLib, errors, looks_like_rust_object_file,
62};
63
64pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
65 if let Err(e) = fs::remove_file(path) {
66 if e.kind() != io::ErrorKind::NotFound {
67 dcx.err(format!("failed to remove {}: {}", path.display(), e));
68 }
69 }
70}
71
72pub fn link_binary(
75 sess: &Session,
76 archive_builder_builder: &dyn ArchiveBuilderBuilder,
77 codegen_results: CodegenResults,
78 outputs: &OutputFilenames,
79) {
80 let _timer = sess.timer("link_binary");
81 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
82 let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
83 for &crate_type in &codegen_results.crate_info.crate_types {
84 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
86 && !output_metadata
87 && crate_type == CrateType::Executable
88 {
89 continue;
90 }
91
92 if invalid_output_for_target(sess, crate_type) {
93 bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
94 }
95
96 sess.time("link_binary_check_files_are_writeable", || {
97 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
98 check_file_is_writeable(obj, sess);
99 }
100 });
101
102 if outputs.outputs.should_link() {
103 let tmpdir = TempFileBuilder::new()
104 .prefix("rustc")
105 .tempdir()
106 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
107 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
108 let output = out_filename(
109 sess,
110 crate_type,
111 outputs,
112 codegen_results.crate_info.local_crate_name,
113 );
114 let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
115 let out_filename =
116 output.file_for_writing(outputs, OutputType::Exe, Some(crate_name.as_str()));
117 match crate_type {
118 CrateType::Rlib => {
119 let _timer = sess.timer("link_rlib");
120 info!("preparing rlib to {:?}", out_filename);
121 link_rlib(
122 sess,
123 archive_builder_builder,
124 &codegen_results,
125 RlibFlavor::Normal,
126 &path,
127 )
128 .build(&out_filename);
129 }
130 CrateType::Staticlib => {
131 link_staticlib(
132 sess,
133 archive_builder_builder,
134 &codegen_results,
135 &out_filename,
136 &path,
137 );
138 }
139 _ => {
140 link_natively(
141 sess,
142 archive_builder_builder,
143 crate_type,
144 &out_filename,
145 &codegen_results,
146 path.as_ref(),
147 );
148 }
149 }
150 if sess.opts.json_artifact_notifications {
151 sess.dcx().emit_artifact_notification(&out_filename, "link");
152 }
153
154 if sess.prof.enabled()
155 && let Some(artifact_name) = out_filename.file_name()
156 {
157 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
159
160 sess.prof.artifact_size(
161 "linked_artifact",
162 artifact_name.to_string_lossy(),
163 file_size,
164 );
165 }
166
167 if output.is_stdout() {
168 if output.is_tty() {
169 sess.dcx().emit_err(errors::BinaryOutputToTty {
170 shorthand: OutputType::Exe.shorthand(),
171 });
172 } else if let Err(e) = copy_to_stdout(&out_filename) {
173 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
174 }
175 tempfiles_for_stdout_output.push(out_filename);
176 }
177 }
178 }
179
180 sess.time("link_binary_remove_temps", || {
182 if sess.opts.cg.save_temps {
184 return;
185 }
186
187 let maybe_remove_temps_from_module =
188 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
189 if !preserve_objects && let Some(ref obj) = module.object {
190 ensure_removed(sess.dcx(), obj);
191 }
192
193 if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
194 ensure_removed(sess.dcx(), dwo_obj);
195 }
196 };
197
198 let remove_temps_from_module =
199 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
200
201 if let Some(ref metadata_module) = codegen_results.metadata_module {
203 remove_temps_from_module(metadata_module);
204 }
205
206 if let Some(ref allocator_module) = codegen_results.allocator_module {
207 remove_temps_from_module(allocator_module);
208 }
209
210 for temp in tempfiles_for_stdout_output {
212 ensure_removed(sess.dcx(), &temp);
213 }
214
215 if !sess.opts.output_types.should_link() {
218 return;
219 }
220
221 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
223 debug!(?preserve_objects, ?preserve_dwarf_objects);
224
225 for module in &codegen_results.modules {
226 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
227 }
228 });
229}
230
231pub fn each_linked_rlib(
234 info: &CrateInfo,
235 crate_type: Option<CrateType>,
236 f: &mut dyn FnMut(CrateNum, &Path),
237) -> Result<(), errors::LinkRlibError> {
238 let fmts = if let Some(crate_type) = crate_type {
239 let Some(fmts) = info.dependency_formats.get(&crate_type) else {
240 return Err(errors::LinkRlibError::MissingFormat);
241 };
242
243 fmts
244 } else {
245 let mut dep_formats = info.dependency_formats.iter();
246 let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
247 if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
248 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
249 ty1: format!("{ty1:?}"),
250 ty2: format!("{ty2:?}"),
251 list1: format!("{list1:?}"),
252 list2: format!("{list2:?}"),
253 });
254 }
255 list1
256 };
257
258 let used_dep_crates = info.used_crates.iter();
259 for &cnum in used_dep_crates {
260 match fmts.get(cnum) {
261 Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
262 Some(_) => {}
263 None => return Err(errors::LinkRlibError::MissingFormat),
264 }
265 let crate_name = info.crate_name[&cnum];
266 let used_crate_source = &info.used_crate_source[&cnum];
267 if let Some((path, _)) = &used_crate_source.rlib {
268 f(cnum, path);
269 } else if used_crate_source.rmeta.is_some() {
270 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
271 } else {
272 return Err(errors::LinkRlibError::NotFound { crate_name });
273 }
274 }
275 Ok(())
276}
277
278fn link_rlib<'a>(
284 sess: &'a Session,
285 archive_builder_builder: &dyn ArchiveBuilderBuilder,
286 codegen_results: &CodegenResults,
287 flavor: RlibFlavor,
288 tmpdir: &MaybeTempDir,
289) -> Box<dyn ArchiveBuilder + 'a> {
290 let mut ab = archive_builder_builder.new_archive_builder(sess);
291
292 let trailing_metadata = match flavor {
293 RlibFlavor::Normal => {
294 let (metadata, metadata_position) = create_wrapper_file(
295 sess,
296 ".rmeta".to_string(),
297 codegen_results.metadata.raw_data(),
298 );
299 let metadata = emit_wrapper_file(sess, &metadata, tmpdir, METADATA_FILENAME);
300 match metadata_position {
301 MetadataPosition::First => {
302 ab.add_file(&metadata);
308 None
309 }
310 MetadataPosition::Last => Some(metadata),
311 }
312 }
313
314 RlibFlavor::StaticlibBase => None,
315 };
316
317 for m in &codegen_results.modules {
318 if let Some(obj) = m.object.as_ref() {
319 ab.add_file(obj);
320 }
321
322 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
323 ab.add_file(dwarf_obj);
324 }
325 }
326
327 match flavor {
328 RlibFlavor::Normal => {}
329 RlibFlavor::StaticlibBase => {
330 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
331 if let Some(obj) = obj {
332 ab.add_file(obj);
333 }
334 }
335 }
336
337 let mut packed_bundled_libs = Vec::new();
339
340 for lib in codegen_results.crate_info.used_libraries.iter() {
357 let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
358 continue;
359 };
360 if flavor == RlibFlavor::Normal
361 && let Some(filename) = lib.filename
362 {
363 let path = find_native_static_library(filename.as_str(), true, sess);
364 let src = read(path)
365 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
366 let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
367 let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
368 packed_bundled_libs.push(wrapper_file);
369 } else {
370 let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
371 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
372 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
373 });
374 }
375 }
376
377 if sess.target.is_like_windows {
381 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
382 sess,
383 archive_builder_builder,
384 codegen_results.crate_info.used_libraries.iter(),
385 tmpdir.as_ref(),
386 true,
387 ) {
388 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
389 sess.dcx()
390 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
391 });
392 }
393 }
394
395 if let Some(trailing_metadata) = trailing_metadata {
396 ab.add_file(&trailing_metadata);
422 }
423
424 for lib in packed_bundled_libs {
427 ab.add_file(&lib)
428 }
429
430 ab
431}
432
433fn link_staticlib(
445 sess: &Session,
446 archive_builder_builder: &dyn ArchiveBuilderBuilder,
447 codegen_results: &CodegenResults,
448 out_filename: &Path,
449 tempdir: &MaybeTempDir,
450) {
451 info!("preparing staticlib to {:?}", out_filename);
452 let mut ab = link_rlib(
453 sess,
454 archive_builder_builder,
455 codegen_results,
456 RlibFlavor::StaticlibBase,
457 tempdir,
458 );
459 let mut all_native_libs = vec![];
460
461 let res = each_linked_rlib(
462 &codegen_results.crate_info,
463 Some(CrateType::Staticlib),
464 &mut |cnum, path| {
465 let lto = are_upstream_rust_objects_already_included(sess)
466 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
467
468 let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
469 let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
470 let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
471
472 let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
473 ab.add_archive(
474 path,
475 Box::new(move |fname: &str| {
476 if fname == METADATA_FILENAME {
478 return true;
479 }
480
481 if lto && looks_like_rust_object_file(fname) {
483 return true;
484 }
485
486 if bundled_libs.contains(&Symbol::intern(fname)) {
488 return true;
489 }
490
491 false
492 }),
493 )
494 .unwrap();
495
496 archive_builder_builder
497 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
498 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
499
500 for filename in relevant_libs.iter() {
501 let joined = tempdir.as_ref().join(filename.as_str());
502 let path = joined.as_path();
503 ab.add_archive(path, Box::new(|_| false)).unwrap();
504 }
505
506 all_native_libs
507 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
508 },
509 );
510 if let Err(e) = res {
511 sess.dcx().emit_fatal(e);
512 }
513
514 ab.build(out_filename);
515
516 let crates = codegen_results.crate_info.used_crates.iter();
517
518 let fmts = codegen_results
519 .crate_info
520 .dependency_formats
521 .get(&CrateType::Staticlib)
522 .expect("no dependency formats for staticlib");
523
524 let mut all_rust_dylibs = vec![];
525 for &cnum in crates {
526 let Some(Linkage::Dynamic) = fmts.get(cnum) else {
527 continue;
528 };
529 let crate_name = codegen_results.crate_info.crate_name[&cnum];
530 let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
531 if let Some((path, _)) = &used_crate_source.dylib {
532 all_rust_dylibs.push(&**path);
533 } else if used_crate_source.rmeta.is_some() {
534 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
535 } else {
536 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
537 }
538 }
539
540 all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
541
542 for print in &sess.opts.prints {
543 if print.kind == PrintKind::NativeStaticLibs {
544 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
545 }
546 }
547}
548
549fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
552 let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
553 dwp_out_filename.push(".dwp");
554 debug!(?dwp_out_filename, ?executable_out_filename);
555
556 #[derive(Default)]
557 struct ThorinSession<Relocations> {
558 arena_data: TypedArena<Vec<u8>>,
559 arena_mmap: TypedArena<Mmap>,
560 arena_relocations: TypedArena<Relocations>,
561 }
562
563 impl<Relocations> ThorinSession<Relocations> {
564 fn alloc_mmap(&self, data: Mmap) -> &Mmap {
565 &*self.arena_mmap.alloc(data)
566 }
567 }
568
569 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
570 fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
571 &*self.arena_data.alloc(data)
572 }
573
574 fn alloc_relocation(&self, data: Relocations) -> &Relocations {
575 &*self.arena_relocations.alloc(data)
576 }
577
578 fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
579 let file = File::open(&path)?;
580 let mmap = (unsafe { Mmap::map(file) })?;
581 Ok(self.alloc_mmap(mmap))
582 }
583 }
584
585 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
586 let thorin_sess = ThorinSession::default();
587 let mut package = thorin::DwarfPackage::new(&thorin_sess);
588
589 match sess.opts.unstable_opts.split_dwarf_kind {
591 SplitDwarfKind::Single => {
592 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
593 package.add_input_object(input_obj)?;
594 }
595 }
596 SplitDwarfKind::Split => {
597 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
598 package.add_input_object(input_obj)?;
599 }
600 }
601 }
602
603 let input_rlibs = cg_results
605 .crate_info
606 .used_crate_source
607 .items()
608 .filter_map(|(_, csource)| csource.rlib.as_ref())
609 .map(|(path, _)| path)
610 .into_sorted_stable_ord();
611
612 for input_rlib in input_rlibs {
613 debug!(?input_rlib);
614 package.add_input_object(input_rlib)?;
615 }
616
617 package.add_executable(
627 executable_out_filename,
628 thorin::MissingReferencedObjectBehaviour::Skip,
629 )?;
630
631 let output_stream = BufWriter::new(
632 OpenOptions::new()
633 .read(true)
634 .write(true)
635 .create(true)
636 .truncate(true)
637 .open(dwp_out_filename)?,
638 );
639 let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
640 package.finish()?.emit(&mut output_stream)?;
641 output_stream.result()?;
642 output_stream.into_inner().flush()?;
643
644 Ok(())
645 }) {
646 Ok(()) => {}
647 Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
648 }
649}
650
651#[derive(LintDiagnostic)]
652#[diag(codegen_ssa_linker_output)]
653struct LinkerOutput {
656 inner: String,
657}
658
659fn link_natively(
664 sess: &Session,
665 archive_builder_builder: &dyn ArchiveBuilderBuilder,
666 crate_type: CrateType,
667 out_filename: &Path,
668 codegen_results: &CodegenResults,
669 tmpdir: &Path,
670) {
671 info!("preparing {:?} to {:?}", crate_type, out_filename);
672 let (linker_path, flavor) = linker_and_flavor(sess);
673 let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
674
675 let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
680 let archive_member =
681 should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
682 let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
683
684 let mut cmd = linker_with_args(
685 &linker_path,
686 flavor,
687 sess,
688 archive_builder_builder,
689 crate_type,
690 tmpdir,
691 temp_filename,
692 codegen_results,
693 self_contained_components,
694 );
695
696 linker::disable_localization(&mut cmd);
697
698 for (k, v) in sess.target.link_env.as_ref() {
699 cmd.env(k.as_ref(), v.as_ref());
700 }
701 for k in sess.target.link_env_remove.as_ref() {
702 cmd.env_remove(k.as_ref());
703 }
704
705 for print in &sess.opts.prints {
706 if print.kind == PrintKind::LinkArgs {
707 let content = format!("{cmd:?}\n");
708 print.out.overwrite(&content, sess);
709 }
710 }
711
712 sess.dcx().abort_if_errors();
714
715 info!("{cmd:?}");
717 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
718 let unknown_arg_regex =
719 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
720 let mut prog;
721 let mut i = 0;
722 loop {
723 i += 1;
724 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
725 let Ok(ref output) = prog else {
726 break;
727 };
728 if output.status.success() {
729 break;
730 }
731 let mut out = output.stderr.clone();
732 out.extend(&output.stdout);
733 let out = String::from_utf8_lossy(&out);
734
735 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
742 && unknown_arg_regex.is_match(&out)
743 && out.contains("-no-pie")
744 && cmd.get_args().iter().any(|e| e == "-no-pie")
745 {
746 info!("linker output: {:?}", out);
747 warn!("Linker does not support -no-pie command line option. Retrying without.");
748 for arg in cmd.take_args() {
749 if arg != "-no-pie" {
750 cmd.arg(arg);
751 }
752 }
753 info!("{cmd:?}");
754 continue;
755 }
756
757 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))
763 && unknown_arg_regex.is_match(&out)
764 && out.contains("-fuse-ld=lld")
765 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
766 {
767 info!("linker output: {:?}", out);
768 warn!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
769 for arg in cmd.take_args() {
770 if arg.to_string_lossy() != "-fuse-ld=lld" {
771 cmd.arg(arg);
772 }
773 }
774 info!("{cmd:?}");
775 continue;
776 }
777
778 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
781 && unknown_arg_regex.is_match(&out)
782 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
783 && cmd.get_args().iter().any(|e| e == "-static-pie")
784 {
785 info!("linker output: {:?}", out);
786 warn!(
787 "Linker does not support -static-pie command line option. Retrying with -static instead."
788 );
789 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
791 let opts = &sess.target;
792 let pre_objects = if self_contained_crt_objects {
793 &opts.pre_link_objects_self_contained
794 } else {
795 &opts.pre_link_objects
796 };
797 let post_objects = if self_contained_crt_objects {
798 &opts.post_link_objects_self_contained
799 } else {
800 &opts.post_link_objects
801 };
802 let get_objects = |objects: &CrtObjects, kind| {
803 objects
804 .get(&kind)
805 .iter()
806 .copied()
807 .flatten()
808 .map(|obj| {
809 get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
810 })
811 .collect::<Vec<_>>()
812 };
813 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
814 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
815 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
816 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
817 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
820 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
821 for arg in cmd.take_args() {
822 if arg == "-static-pie" {
823 cmd.arg("-static");
825 } else if pre_objects_static_pie.contains(&arg) {
826 cmd.args(mem::take(&mut pre_objects_static));
828 } else if post_objects_static_pie.contains(&arg) {
829 cmd.args(mem::take(&mut post_objects_static));
831 } else {
832 cmd.arg(arg);
833 }
834 }
835 info!("{cmd:?}");
836 continue;
837 }
838
839 if !retry_on_segfault || i > 3 {
855 break;
856 }
857 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
858 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
859 if out.contains(msg_segv) || out.contains(msg_bus) {
860 warn!(
861 ?cmd, %out,
862 "looks like the linker segfaulted when we tried to call it, \
863 automatically retrying again",
864 );
865 continue;
866 }
867
868 if is_illegal_instruction(&output.status) {
869 warn!(
870 ?cmd, %out, status = %output.status,
871 "looks like the linker hit an illegal instruction when we \
872 tried to call it, automatically retrying again.",
873 );
874 continue;
875 }
876
877 #[cfg(unix)]
878 fn is_illegal_instruction(status: &ExitStatus) -> bool {
879 use std::os::unix::prelude::*;
880 status.signal() == Some(libc::SIGILL)
881 }
882
883 #[cfg(not(unix))]
884 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
885 false
886 }
887 }
888
889 match prog {
890 Ok(prog) => {
891 let is_msvc_link_exe = sess.target.is_like_msvc
892 && flavor == LinkerFlavor::Msvc(Lld::No)
893 && linker_path.to_str() == Some("link.exe");
895
896 if !prog.status.success() {
897 let mut output = prog.stderr.clone();
898 output.extend_from_slice(&prog.stdout);
899 let escaped_output = escape_linker_output(&output, flavor);
900 let err = errors::LinkingFailed {
901 linker_path: &linker_path,
902 exit_status: prog.status,
903 command: cmd,
904 escaped_output,
905 verbose: sess.opts.verbose,
906 sysroot_dir: sess.sysroot.clone(),
907 };
908 sess.dcx().emit_err(err);
909 if let Some(code) = prog.status.code() {
913 if is_msvc_link_exe && (code < 1000 || code > 9999) {
916 let is_vs_installed = windows_registry::find_vs_version().is_ok();
917 let has_linker =
918 windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
919
920 sess.dcx().emit_note(errors::LinkExeUnexpectedError);
921 if is_vs_installed && has_linker {
922 sess.dcx().emit_note(errors::RepairVSBuildTools);
924 sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
925 } else if is_vs_installed {
926 sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
928 } else {
929 sess.dcx().emit_note(errors::VisualStudioNotInstalled);
931 }
932 }
933 }
934
935 sess.dcx().abort_if_errors();
936 }
937
938 let stderr = escape_string(&prog.stderr);
939 let mut stdout = escape_string(&prog.stdout);
940 info!("linker stderr:\n{}", &stderr);
941 info!("linker stdout:\n{}", &stdout);
942
943 if is_msvc_link_exe {
946 if let Ok(str) = str::from_utf8(&prog.stdout) {
947 let mut output = String::with_capacity(str.len());
948 for line in stdout.lines() {
949 if line.starts_with(" Creating library")
950 || line.starts_with("Generating code")
951 || line.starts_with("Finished generating code")
952 {
953 continue;
954 }
955 output += line;
956 output += "\r\n"
957 }
958 stdout = escape_string(output.trim().as_bytes())
959 }
960 }
961
962 let (level, src) = codegen_results.crate_info.lint_levels.linker_messages;
963 let lint = |msg| {
964 lint_level(sess, LINKER_MESSAGES, level, src, None, |diag| {
965 LinkerOutput { inner: msg }.decorate_lint(diag)
966 })
967 };
968
969 if !prog.stderr.is_empty() {
970 let stderr = stderr
972 .strip_prefix("warning: ")
973 .unwrap_or(&stderr)
974 .replace(": warning: ", ": ");
975 lint(format!("linker stderr: {stderr}"));
976 }
977 if !stdout.is_empty() {
978 lint(format!("linker stdout: {}", stdout))
979 }
980 }
981 Err(e) => {
982 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
983
984 let err = if linker_not_found {
985 sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
986 } else {
987 sess.dcx().emit_err(errors::UnableToExeLinker {
988 linker_path,
989 error: e,
990 command_formatted: format!("{cmd:?}"),
991 })
992 };
993
994 if sess.target.is_like_msvc && linker_not_found {
995 sess.dcx().emit_note(errors::MsvcMissingLinker);
996 sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
997 sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
998 }
999 err.raise_fatal();
1000 }
1001 }
1002
1003 match sess.split_debuginfo() {
1004 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
1007
1008 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
1011
1012 SplitDebuginfo::Packed if sess.target.is_like_osx => {
1016 let prog = Command::new("dsymutil").arg(out_filename).output();
1017 match prog {
1018 Ok(prog) => {
1019 if !prog.status.success() {
1020 let mut output = prog.stderr.clone();
1021 output.extend_from_slice(&prog.stdout);
1022 sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1023 status: prog.status,
1024 output: escape_string(&output),
1025 });
1026 }
1027 }
1028 Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1029 }
1030 }
1031
1032 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1035
1036 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1042 }
1043
1044 let strip = sess.opts.cg.strip;
1045
1046 if sess.target.is_like_osx {
1047 let stripcmd = "rust-objcopy";
1048 match (strip, crate_type) {
1049 (Strip::Debuginfo, _) => {
1050 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1051 }
1052 (Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro) => {
1054 strip_with_external_utility(sess, stripcmd, out_filename, &["-x"])
1055 }
1056 (Strip::Symbols, _) => {
1057 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1058 }
1059 (Strip::None, _) => {}
1060 }
1061 }
1062
1063 if sess.target.is_like_solaris {
1064 let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1071 match strip {
1072 Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1074 Strip::Symbols => {}
1076 Strip::None => {}
1077 }
1078 }
1079
1080 if sess.target.is_like_aix {
1081 if !sess.host.is_like_aix {
1083 sess.dcx().emit_warn(errors::AixStripNotUsed);
1084 }
1085 let stripcmd = "/usr/bin/strip";
1086 match strip {
1087 Strip::Debuginfo => {
1088 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-l"])
1090 }
1091 Strip::Symbols => {
1092 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-r"])
1094 }
1095 Strip::None => {}
1096 }
1097 }
1098
1099 if should_archive {
1100 let mut ab = archive_builder_builder.new_archive_builder(sess);
1101 ab.add_file(temp_filename);
1102 ab.build(out_filename);
1103 }
1104}
1105
1106fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1107 let mut cmd = Command::new(util);
1108 cmd.args(options);
1109
1110 let mut new_path = sess.get_tools_search_paths(false);
1111 if let Some(path) = env::var_os("PATH") {
1112 new_path.extend(env::split_paths(&path));
1113 }
1114 cmd.env("PATH", env::join_paths(new_path).unwrap());
1115
1116 let prog = cmd.arg(out_filename).output();
1117 match prog {
1118 Ok(prog) => {
1119 if !prog.status.success() {
1120 let mut output = prog.stderr.clone();
1121 output.extend_from_slice(&prog.stdout);
1122 sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1123 util,
1124 status: prog.status,
1125 output: escape_string(&output),
1126 });
1127 }
1128 }
1129 Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1130 }
1131}
1132
1133fn escape_string(s: &[u8]) -> String {
1134 match str::from_utf8(s) {
1135 Ok(s) => s.to_owned(),
1136 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1137 }
1138}
1139
1140#[cfg(not(windows))]
1141fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1142 escape_string(s)
1143}
1144
1145#[cfg(windows)]
1148fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1149 if flavour != LinkerFlavor::Msvc(Lld::No) {
1151 return escape_string(s);
1152 }
1153 match str::from_utf8(s) {
1154 Ok(s) => return s.to_owned(),
1155 Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1156 Some(s) => s,
1157 None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1159 },
1160 }
1161}
1162
1163#[cfg(windows)]
1165mod win {
1166 use windows::Win32::Globalization::{
1167 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1168 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1169 };
1170
1171 pub(super) fn oem_code_page() -> u32 {
1174 unsafe {
1175 let mut cp: u32 = 0;
1176 let len = size_of::<u32>() / size_of::<u16>();
1179 let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1180 let len_written = GetLocaleInfoEx(
1181 LOCALE_NAME_SYSTEM_DEFAULT,
1182 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1183 Some(data),
1184 );
1185 if len_written as usize == len { cp } else { CP_OEMCP }
1186 }
1187 }
1188 pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1197 if s.len() > isize::MAX as usize {
1199 return None;
1200 }
1201 let flags = MB_ERR_INVALID_CHARS;
1203 let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1206 if len > 0 {
1207 let mut utf16 = vec![0; len as usize];
1208 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1209 if len > 0 {
1210 return utf16.get(..len as usize).map(String::from_utf16_lossy);
1211 }
1212 }
1213 None
1214 }
1215}
1216
1217fn add_sanitizer_libraries(
1218 sess: &Session,
1219 flavor: LinkerFlavor,
1220 crate_type: CrateType,
1221 linker: &mut dyn Linker,
1222) {
1223 if sess.target.is_like_android {
1224 return;
1227 }
1228
1229 if sess.opts.unstable_opts.external_clangrt {
1230 return;
1233 }
1234
1235 if matches!(crate_type, CrateType::Rlib | CrateType::Staticlib) {
1236 return;
1237 }
1238
1239 if matches!(crate_type, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro)
1244 && !(sess.target.is_like_osx || sess.target.is_like_msvc)
1245 {
1246 return;
1247 }
1248
1249 let sanitizer = sess.opts.unstable_opts.sanitizer;
1250 if sanitizer.contains(SanitizerSet::ADDRESS) {
1251 link_sanitizer_runtime(sess, flavor, linker, "asan");
1252 }
1253 if sanitizer.contains(SanitizerSet::DATAFLOW) {
1254 link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1255 }
1256 if sanitizer.contains(SanitizerSet::LEAK)
1257 && !sanitizer.contains(SanitizerSet::ADDRESS)
1258 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1259 {
1260 link_sanitizer_runtime(sess, flavor, linker, "lsan");
1261 }
1262 if sanitizer.contains(SanitizerSet::MEMORY) {
1263 link_sanitizer_runtime(sess, flavor, linker, "msan");
1264 }
1265 if sanitizer.contains(SanitizerSet::THREAD) {
1266 link_sanitizer_runtime(sess, flavor, linker, "tsan");
1267 }
1268 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1269 link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1270 }
1271 if sanitizer.contains(SanitizerSet::SAFESTACK) {
1272 link_sanitizer_runtime(sess, flavor, linker, "safestack");
1273 }
1274}
1275
1276fn link_sanitizer_runtime(
1277 sess: &Session,
1278 flavor: LinkerFlavor,
1279 linker: &mut dyn Linker,
1280 name: &str,
1281) {
1282 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1283 let path = sess.target_tlib_path.dir.join(filename);
1284 if path.exists() {
1285 sess.target_tlib_path.dir.clone()
1286 } else {
1287 let default_sysroot = filesearch::get_or_default_sysroot();
1288 let default_tlib =
1289 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.tuple());
1290 default_tlib
1291 }
1292 }
1293
1294 let channel =
1295 option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
1296
1297 if sess.target.is_like_osx {
1298 let filename = format!("rustc{channel}_rt.{name}");
1303 let path = find_sanitizer_runtime(sess, &filename);
1304 let rpath = path.to_str().expect("non-utf8 component in path");
1305 linker.link_args(&["-rpath", rpath]);
1306 linker.link_dylib_by_name(&filename, false, true);
1307 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1308 linker.link_arg("/INFERASANLIBS");
1311 } else {
1312 let filename = format!("librustc{channel}_rt.{name}.a");
1313 let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1314 linker.link_staticlib_by_path(&path, true);
1315 }
1316}
1317
1318pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1329 !sess.target.no_builtins
1333 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1334}
1335
1336pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1338 fn infer_from(
1339 sess: &Session,
1340 linker: Option<PathBuf>,
1341 flavor: Option<LinkerFlavor>,
1342 features: LinkerFeaturesCli,
1343 ) -> Option<(PathBuf, LinkerFlavor)> {
1344 let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1345 match (linker, flavor) {
1346 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1347 (None, Some(flavor)) => Some((
1349 PathBuf::from(match flavor {
1350 LinkerFlavor::Gnu(Cc::Yes, _)
1351 | LinkerFlavor::Darwin(Cc::Yes, _)
1352 | LinkerFlavor::WasmLld(Cc::Yes)
1353 | LinkerFlavor::Unix(Cc::Yes) => {
1354 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1355 "gcc"
1362 } else {
1363 "cc"
1364 }
1365 }
1366 LinkerFlavor::Gnu(_, Lld::Yes)
1367 | LinkerFlavor::Darwin(_, Lld::Yes)
1368 | LinkerFlavor::WasmLld(..)
1369 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1370 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1371 "ld"
1372 }
1373 LinkerFlavor::Msvc(..) => "link.exe",
1374 LinkerFlavor::EmCc => {
1375 if cfg!(windows) {
1376 "emcc.bat"
1377 } else {
1378 "emcc"
1379 }
1380 }
1381 LinkerFlavor::Bpf => "bpf-linker",
1382 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1383 LinkerFlavor::Ptx => "rust-ptx-linker",
1384 }),
1385 flavor,
1386 )),
1387 (Some(linker), None) => {
1388 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1389 sess.dcx().emit_fatal(errors::LinkerFileStem);
1390 });
1391 let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1392 let flavor = adjust_flavor_to_features(flavor, features);
1393 Some((linker, flavor))
1394 }
1395 (None, None) => None,
1396 }
1397 }
1398
1399 fn adjust_flavor_to_features(
1404 flavor: LinkerFlavor,
1405 features: LinkerFeaturesCli,
1406 ) -> LinkerFlavor {
1407 if features.enabled.contains(LinkerFeatures::LLD) {
1409 flavor.with_lld_enabled()
1410 } else if features.disabled.contains(LinkerFeatures::LLD) {
1411 flavor.with_lld_disabled()
1412 } else {
1413 flavor
1414 }
1415 }
1416
1417 let features = sess.opts.unstable_opts.linker_features;
1418
1419 let linker_flavor = match sess.opts.cg.linker_flavor {
1422 Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1424 Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1425 _ => sess
1427 .opts
1428 .cg
1429 .linker_flavor
1430 .map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
1431 };
1432 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1433 return ret;
1434 }
1435
1436 if let Some(ret) = infer_from(
1437 sess,
1438 sess.target.linker.as_deref().map(PathBuf::from),
1439 Some(sess.target.linker_flavor),
1440 features,
1441 ) {
1442 return ret;
1443 }
1444
1445 bug!("Not enough information provided to determine how to invoke the linker");
1446}
1447
1448fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1452 if sess.opts.debuginfo == config::DebugInfo::None {
1454 return (false, false);
1455 }
1456
1457 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1458 (SplitDebuginfo::Off, _) => (false, false),
1460 (SplitDebuginfo::Packed, _) => (false, false),
1463 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1466 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1470 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1471 }
1472}
1473
1474#[derive(PartialEq)]
1475enum RlibFlavor {
1476 Normal,
1477 StaticlibBase,
1478}
1479
1480fn print_native_static_libs(
1481 sess: &Session,
1482 out: &OutFileName,
1483 all_native_libs: &[NativeLib],
1484 all_rust_dylibs: &[&Path],
1485) {
1486 let mut lib_args: Vec<_> = all_native_libs
1487 .iter()
1488 .filter(|l| relevant_lib(sess, l))
1489 .filter_map(|lib| {
1490 let name = lib.name;
1491 match lib.kind {
1492 NativeLibKind::Static { bundle: Some(false), .. }
1493 | NativeLibKind::Dylib { .. }
1494 | NativeLibKind::Unspecified => {
1495 let verbatim = lib.verbatim;
1496 if sess.target.is_like_msvc {
1497 let (prefix, suffix) = sess.staticlib_components(verbatim);
1498 Some(format!("{prefix}{name}{suffix}"))
1499 } else if sess.target.linker_flavor.is_gnu() {
1500 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1501 } else {
1502 Some(format!("-l{name}"))
1503 }
1504 }
1505 NativeLibKind::Framework { .. } => {
1506 Some(format!("-framework {name}"))
1508 }
1509 NativeLibKind::Static { bundle: None | Some(true), .. }
1511 | NativeLibKind::LinkArg
1512 | NativeLibKind::WasmImportModule
1513 | NativeLibKind::RawDylib => None,
1514 }
1515 })
1516 .dedup()
1518 .collect();
1519 for path in all_rust_dylibs {
1520 let parent = path.parent();
1525 if let Some(dir) = parent {
1526 let dir = fix_windows_verbatim_for_gcc(dir);
1527 if sess.target.is_like_msvc {
1528 let mut arg = String::from("/LIBPATH:");
1529 arg.push_str(&dir.display().to_string());
1530 lib_args.push(arg);
1531 } else {
1532 lib_args.push("-L".to_owned());
1533 lib_args.push(dir.display().to_string());
1534 }
1535 }
1536 let stem = path.file_stem().unwrap().to_str().unwrap();
1537 let lib = if let Some(lib) = stem.strip_prefix("lib")
1539 && !sess.target.is_like_windows
1540 {
1541 lib
1542 } else {
1543 stem
1544 };
1545 let path = parent.unwrap_or_else(|| Path::new(""));
1546 if sess.target.is_like_msvc {
1547 let name = format!("{lib}.dll.lib");
1552 if path.join(&name).exists() {
1553 lib_args.push(name);
1554 }
1555 } else {
1556 lib_args.push(format!("-l{lib}"));
1557 }
1558 }
1559
1560 match out {
1561 OutFileName::Real(path) => {
1562 out.overwrite(&lib_args.join(" "), sess);
1563 sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1564 }
1565 OutFileName::Stdout => {
1566 sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1567 sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
1570 }
1571 }
1572}
1573
1574fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1575 let file_path = sess.target_tlib_path.dir.join(name);
1576 if file_path.exists() {
1577 return file_path;
1578 }
1579 if self_contained {
1581 let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1582 if file_path.exists() {
1583 return file_path;
1584 }
1585 }
1586 for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1587 let file_path = search_path.dir.join(name);
1588 if file_path.exists() {
1589 return file_path;
1590 }
1591 }
1592 PathBuf::from(name)
1593}
1594
1595fn exec_linker(
1596 sess: &Session,
1597 cmd: &Command,
1598 out_filename: &Path,
1599 flavor: LinkerFlavor,
1600 tmpdir: &Path,
1601) -> io::Result<Output> {
1602 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1612 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1613 Ok(child) => {
1614 let output = child.wait_with_output();
1615 flush_linked_file(&output, out_filename)?;
1616 return output;
1617 }
1618 Err(ref e) if command_line_too_big(e) => {
1619 info!("command line to linker was too big: {}", e);
1620 }
1621 Err(e) => return Err(e),
1622 }
1623 }
1624
1625 info!("falling back to passing arguments to linker via an @-file");
1626 let mut cmd2 = cmd.clone();
1627 let mut args = String::new();
1628 for arg in cmd2.take_args() {
1629 args.push_str(
1630 &Escape {
1631 arg: arg.to_str().unwrap(),
1632 is_like_msvc: sess.target.is_like_msvc
1637 || (cfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1638 }
1639 .to_string(),
1640 );
1641 args.push('\n');
1642 }
1643 let file = tmpdir.join("linker-arguments");
1644 let bytes = if sess.target.is_like_msvc {
1645 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1646 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1648 out.push(c as u8);
1650 out.push((c >> 8) as u8);
1651 }
1652 out
1653 } else {
1654 args.into_bytes()
1655 };
1656 fs::write(&file, &bytes)?;
1657 cmd2.arg(format!("@{}", file.display()));
1658 info!("invoking linker {:?}", cmd2);
1659 let output = cmd2.output();
1660 flush_linked_file(&output, out_filename)?;
1661 return output;
1662
1663 #[cfg(not(windows))]
1664 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1665 Ok(())
1666 }
1667
1668 #[cfg(windows)]
1669 fn flush_linked_file(
1670 command_output: &io::Result<Output>,
1671 out_filename: &Path,
1672 ) -> io::Result<()> {
1673 if let &Ok(ref out) = command_output {
1682 if out.status.success() {
1683 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1684 of.sync_all()?;
1685 }
1686 }
1687 }
1688
1689 Ok(())
1690 }
1691
1692 #[cfg(unix)]
1693 fn command_line_too_big(err: &io::Error) -> bool {
1694 err.raw_os_error() == Some(::libc::E2BIG)
1695 }
1696
1697 #[cfg(windows)]
1698 fn command_line_too_big(err: &io::Error) -> bool {
1699 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1700 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1701 }
1702
1703 #[cfg(not(any(unix, windows)))]
1704 fn command_line_too_big(_: &io::Error) -> bool {
1705 false
1706 }
1707
1708 struct Escape<'a> {
1709 arg: &'a str,
1710 is_like_msvc: bool,
1711 }
1712
1713 impl<'a> fmt::Display for Escape<'a> {
1714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1715 if self.is_like_msvc {
1716 write!(f, "\"")?;
1724 for c in self.arg.chars() {
1725 match c {
1726 '"' => write!(f, "\\{c}")?,
1727 c => write!(f, "{c}")?,
1728 }
1729 }
1730 write!(f, "\"")?;
1731 } else {
1732 for c in self.arg.chars() {
1743 match c {
1744 '\\' | ' ' => write!(f, "\\{c}")?,
1745 c => write!(f, "{c}")?,
1746 }
1747 }
1748 }
1749 Ok(())
1750 }
1751 }
1752}
1753
1754fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1755 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1756 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1757 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1758 LinkOutputKind::DynamicPicExe
1759 }
1760 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1761 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1762 LinkOutputKind::StaticPicExe
1763 }
1764 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1765 (_, true, _) => LinkOutputKind::StaticDylib,
1766 (_, false, _) => LinkOutputKind::DynamicDylib,
1767 };
1768
1769 let opts = &sess.target;
1771 let pic_exe_supported = opts.position_independent_executables;
1772 let static_pic_exe_supported = opts.static_position_independent_executables;
1773 let static_dylib_supported = opts.crt_static_allows_dylibs;
1774 match kind {
1775 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1776 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1777 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1778 _ => kind,
1779 }
1780}
1781
1782fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1784 if linker == Path::new("rust-lld") {
1786 return true;
1787 }
1788 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1789 linker.with_extension("exe")
1790 } else {
1791 linker.to_path_buf()
1792 };
1793 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1794 let full_path = dir.join(&linker_with_extension);
1795 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1797 return false;
1798 }
1799 }
1800 true
1801}
1802
1803fn self_contained_components(
1807 sess: &Session,
1808 crate_type: CrateType,
1809 linker: &Path,
1810) -> LinkSelfContainedComponents {
1811 let self_contained =
1814 if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1815 if sess.target.link_self_contained.is_disabled() {
1818 sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1819 }
1820 self_contained
1821 } else {
1822 match sess.target.link_self_contained {
1823 LinkSelfContainedDefault::False => false,
1824 LinkSelfContainedDefault::True => true,
1825
1826 LinkSelfContainedDefault::WithComponents(components) => {
1827 return components;
1830 }
1831
1832 LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1836 LinkSelfContainedDefault::InferredForMingw => {
1837 sess.host == sess.target
1838 && sess.target.vendor != "uwp"
1839 && detect_self_contained_mingw(sess, linker)
1840 }
1841 }
1842 };
1843 if self_contained {
1844 LinkSelfContainedComponents::all()
1845 } else {
1846 LinkSelfContainedComponents::empty()
1847 }
1848}
1849
1850fn add_pre_link_objects(
1852 cmd: &mut dyn Linker,
1853 sess: &Session,
1854 flavor: LinkerFlavor,
1855 link_output_kind: LinkOutputKind,
1856 self_contained: bool,
1857) {
1858 let opts = &sess.target;
1861 let empty = Default::default();
1862 let objects = if self_contained {
1863 &opts.pre_link_objects_self_contained
1864 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1865 &opts.pre_link_objects
1866 } else {
1867 &empty
1868 };
1869 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1870 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1871 }
1872}
1873
1874fn add_post_link_objects(
1876 cmd: &mut dyn Linker,
1877 sess: &Session,
1878 link_output_kind: LinkOutputKind,
1879 self_contained: bool,
1880) {
1881 let objects = if self_contained {
1882 &sess.target.post_link_objects_self_contained
1883 } else {
1884 &sess.target.post_link_objects
1885 };
1886 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1887 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1888 }
1889}
1890
1891fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1894 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1895 cmd.verbatim_args(args.iter().map(Deref::deref));
1896 }
1897
1898 cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1899}
1900
1901fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1903 match (crate_type, &sess.target.link_script) {
1904 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1905 if !sess.target.linker_flavor.is_gnu() {
1906 sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1907 }
1908
1909 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1910
1911 let path = tmpdir.join(file_name);
1912 if let Err(error) = fs::write(&path, script.as_ref()) {
1913 sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1914 }
1915
1916 cmd.link_arg("--script").link_arg(path);
1917 }
1918 _ => {}
1919 }
1920}
1921
1922fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1925 cmd.verbatim_args(&sess.opts.cg.link_args);
1926}
1927
1928fn add_late_link_args(
1931 cmd: &mut dyn Linker,
1932 sess: &Session,
1933 flavor: LinkerFlavor,
1934 crate_type: CrateType,
1935 codegen_results: &CodegenResults,
1936) {
1937 let any_dynamic_crate = crate_type == CrateType::Dylib
1938 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1939 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1940 });
1941 if any_dynamic_crate {
1942 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1943 cmd.verbatim_args(args.iter().map(Deref::deref));
1944 }
1945 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1946 cmd.verbatim_args(args.iter().map(Deref::deref));
1947 }
1948 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1949 cmd.verbatim_args(args.iter().map(Deref::deref));
1950 }
1951}
1952
1953fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1956 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1957 cmd.verbatim_args(args.iter().map(Deref::deref));
1958 }
1959}
1960
1961fn add_linked_symbol_object(
1991 cmd: &mut dyn Linker,
1992 sess: &Session,
1993 tmpdir: &Path,
1994 symbols: &[(String, SymbolExportKind)],
1995) {
1996 if symbols.is_empty() {
1997 return;
1998 }
1999
2000 let Some(mut file) = super::metadata::create_object_file(sess) else {
2001 return;
2002 };
2003
2004 if file.format() == object::BinaryFormat::Coff {
2005 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
2008
2009 file.set_mangling(object::write::Mangling::None);
2012 }
2013
2014 if file.format() == object::BinaryFormat::MachO {
2015 file.set_subsections_via_symbols();
2018 }
2019
2020 let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2023 Some(file.add_section(
2024 file.segment_name(object::write::StandardSegment::Data).to_vec(),
2025 "__data".into(),
2026 object::SectionKind::Data,
2027 ))
2028 } else {
2029 None
2030 };
2031
2032 for (sym, kind) in symbols.iter() {
2033 let symbol = file.add_symbol(object::write::Symbol {
2034 name: sym.clone().into(),
2035 value: 0,
2036 size: 0,
2037 kind: match kind {
2038 SymbolExportKind::Text => object::SymbolKind::Text,
2039 SymbolExportKind::Data => object::SymbolKind::Data,
2040 SymbolExportKind::Tls => object::SymbolKind::Tls,
2041 },
2042 scope: object::SymbolScope::Unknown,
2043 weak: false,
2044 section: object::write::SymbolSection::Undefined,
2045 flags: object::SymbolFlags::None,
2046 });
2047
2048 if let Some(section) = ld64_section_helper {
2085 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2086 .expect("failed adding relocation");
2087 }
2088 }
2089
2090 let path = tmpdir.join("symbols.o");
2091 let result = std::fs::write(&path, file.write().unwrap());
2092 if let Err(error) = result {
2093 sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2094 }
2095 cmd.add_object(&path);
2096}
2097
2098fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2100 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2101 cmd.add_object(obj);
2102 }
2103}
2104
2105fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2107 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
2108 cmd.add_object(obj);
2109 }
2110}
2111
2112fn add_local_crate_metadata_objects(
2114 cmd: &mut dyn Linker,
2115 crate_type: CrateType,
2116 codegen_results: &CodegenResults,
2117) {
2118 if matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro)
2122 && let Some(m) = &codegen_results.metadata_module
2123 && let Some(obj) = &m.object
2124 {
2125 cmd.add_object(obj);
2126 }
2127}
2128
2129fn add_library_search_dirs(
2131 cmd: &mut dyn Linker,
2132 sess: &Session,
2133 self_contained_components: LinkSelfContainedComponents,
2134 apple_sdk_root: Option<&Path>,
2135) {
2136 if !sess.opts.unstable_opts.link_native_libraries {
2137 return;
2138 }
2139
2140 let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2141 let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2142 if is_framework {
2143 cmd.framework_path(dir);
2144 } else {
2145 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2146 }
2147 ControlFlow::<()>::Continue(())
2148 });
2149}
2150
2151fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2154 match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2155 RelroLevel::Full => cmd.full_relro(),
2156 RelroLevel::Partial => cmd.partial_relro(),
2157 RelroLevel::Off => cmd.no_relro(),
2158 RelroLevel::None => {}
2159 }
2160}
2161
2162fn add_rpath_args(
2164 cmd: &mut dyn Linker,
2165 sess: &Session,
2166 codegen_results: &CodegenResults,
2167 out_filename: &Path,
2168) {
2169 if !sess.target.has_rpath {
2170 return;
2171 }
2172
2173 if sess.opts.cg.rpath {
2177 let libs = codegen_results
2178 .crate_info
2179 .used_crates
2180 .iter()
2181 .filter_map(|cnum| {
2182 codegen_results.crate_info.used_crate_source[cnum]
2183 .dylib
2184 .as_ref()
2185 .map(|(path, _)| &**path)
2186 })
2187 .collect::<Vec<_>>();
2188 let rpath_config = RPathConfig {
2189 libs: &*libs,
2190 out_filename: out_filename.to_path_buf(),
2191 is_like_osx: sess.target.is_like_osx,
2192 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2193 };
2194 cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2195 }
2196}
2197
2198fn linker_with_args(
2207 path: &Path,
2208 flavor: LinkerFlavor,
2209 sess: &Session,
2210 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2211 crate_type: CrateType,
2212 tmpdir: &Path,
2213 out_filename: &Path,
2214 codegen_results: &CodegenResults,
2215 self_contained_components: LinkSelfContainedComponents,
2216) -> Command {
2217 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2218 let cmd = &mut *super::linker::get_linker(
2219 sess,
2220 path,
2221 flavor,
2222 self_contained_components.are_any_components_enabled(),
2223 &codegen_results.crate_info.target_cpu,
2224 );
2225 let link_output_kind = link_output_kind(sess, crate_type);
2226
2227 cmd.export_symbols(
2235 tmpdir,
2236 crate_type,
2237 &codegen_results.crate_info.exported_symbols[&crate_type],
2238 );
2239
2240 add_pre_link_args(cmd, sess, flavor);
2245
2246 add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
2250
2251 add_linked_symbol_object(
2252 cmd,
2253 sess,
2254 tmpdir,
2255 &codegen_results.crate_info.linked_symbols[&crate_type],
2256 );
2257
2258 add_sanitizer_libraries(sess, flavor, crate_type, cmd);
2260
2261 add_local_crate_regular_objects(cmd, codegen_results);
2289 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
2290 add_local_crate_allocator_objects(cmd, codegen_results);
2291
2292 cmd.add_as_needed();
2301
2302 add_local_native_libraries(
2304 cmd,
2305 sess,
2306 archive_builder_builder,
2307 codegen_results,
2308 tmpdir,
2309 link_output_kind,
2310 );
2311
2312 add_upstream_rust_crates(
2314 cmd,
2315 sess,
2316 archive_builder_builder,
2317 codegen_results,
2318 crate_type,
2319 tmpdir,
2320 link_output_kind,
2321 );
2322
2323 add_upstream_native_libraries(
2325 cmd,
2326 sess,
2327 archive_builder_builder,
2328 codegen_results,
2329 tmpdir,
2330 link_output_kind,
2331 );
2332
2333 let raw_dylib_dir = tmpdir.join("raw-dylibs");
2335 if sess.target.binary_format == BinaryFormat::Elf {
2336 if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2341 sess.dcx().emit_fatal(errors::CreateTempDir { error })
2342 }
2343 cmd.include_path(&raw_dylib_dir);
2344 }
2345
2346 if sess.target.is_like_windows {
2348 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2349 sess,
2350 archive_builder_builder,
2351 codegen_results.crate_info.used_libraries.iter(),
2352 tmpdir,
2353 true,
2354 ) {
2355 cmd.add_object(&output_path);
2356 }
2357 } else {
2358 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2359 sess,
2360 codegen_results.crate_info.used_libraries.iter(),
2361 &raw_dylib_dir,
2362 ) {
2363 cmd.link_dylib_by_name(&link_path, true, false);
2365 }
2366 }
2367 let dependency_linkage = codegen_results
2372 .crate_info
2373 .dependency_formats
2374 .get(&crate_type)
2375 .expect("failed to find crate type in dependency format list");
2376
2377 #[allow(rustc::potential_query_instability)]
2379 let mut native_libraries_from_nonstatics = codegen_results
2380 .crate_info
2381 .native_libraries
2382 .iter()
2383 .filter_map(|(&cnum, libraries)| {
2384 if sess.target.is_like_windows {
2385 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2386 } else {
2387 Some(libraries)
2388 }
2389 })
2390 .flatten()
2391 .collect::<Vec<_>>();
2392 native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
2393
2394 if sess.target.is_like_windows {
2395 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2396 sess,
2397 archive_builder_builder,
2398 native_libraries_from_nonstatics,
2399 tmpdir,
2400 false,
2401 ) {
2402 cmd.add_object(&output_path);
2403 }
2404 } else {
2405 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2406 sess,
2407 native_libraries_from_nonstatics,
2408 &raw_dylib_dir,
2409 ) {
2410 cmd.link_dylib_by_name(&link_path, true, false);
2412 }
2413 }
2414
2415 cmd.reset_per_library_state();
2418
2419 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2423
2424 add_order_independent_options(
2429 cmd,
2430 sess,
2431 link_output_kind,
2432 self_contained_components,
2433 flavor,
2434 crate_type,
2435 codegen_results,
2436 out_filename,
2437 tmpdir,
2438 );
2439
2440 add_user_defined_link_args(cmd, sess);
2444
2445 add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
2449
2450 add_post_link_args(cmd, sess, flavor);
2457
2458 cmd.take_cmd()
2459}
2460
2461fn add_order_independent_options(
2462 cmd: &mut dyn Linker,
2463 sess: &Session,
2464 link_output_kind: LinkOutputKind,
2465 self_contained_components: LinkSelfContainedComponents,
2466 flavor: LinkerFlavor,
2467 crate_type: CrateType,
2468 codegen_results: &CodegenResults,
2469 out_filename: &Path,
2470 tmpdir: &Path,
2471) {
2472 add_lld_args(cmd, sess, flavor, self_contained_components);
2474
2475 add_apple_link_args(cmd, sess, flavor);
2476
2477 let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
2478
2479 add_link_script(cmd, sess, tmpdir, crate_type);
2480
2481 if sess.target.os == "fuchsia"
2482 && crate_type == CrateType::Executable
2483 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2484 {
2485 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2486 "asan/"
2487 } else {
2488 ""
2489 };
2490 cmd.link_arg(format!("--dynamic-linker={prefix}ld.so.1"));
2491 }
2492
2493 if sess.target.eh_frame_header {
2494 cmd.add_eh_frame_header();
2495 }
2496
2497 cmd.add_no_exec();
2499
2500 if self_contained_components.is_crt_objects_enabled() {
2501 cmd.no_crt_objects();
2502 }
2503
2504 if sess.target.os == "emscripten" {
2505 cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2506 "-fwasm-exceptions"
2507 } else if sess.panic_strategy() == PanicStrategy::Abort {
2508 "-sDISABLE_EXCEPTION_CATCHING=1"
2509 } else {
2510 "-sDISABLE_EXCEPTION_CATCHING=0"
2511 });
2512 }
2513
2514 if flavor == LinkerFlavor::Llbc {
2515 cmd.link_args(&[
2516 "--target",
2517 &versioned_llvm_target(sess),
2518 "--target-cpu",
2519 &codegen_results.crate_info.target_cpu,
2520 ]);
2521 if codegen_results.crate_info.target_features.len() > 0 {
2522 cmd.link_arg(&format!(
2523 "--target-feature={}",
2524 &codegen_results.crate_info.target_features.join(",")
2525 ));
2526 }
2527 } else if flavor == LinkerFlavor::Ptx {
2528 cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2529 } else if flavor == LinkerFlavor::Bpf {
2530 cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2531 if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2532 .into_iter()
2533 .find(|feat| !feat.is_empty())
2534 {
2535 cmd.link_args(&["--cpu-features", feat]);
2536 }
2537 }
2538
2539 cmd.linker_plugin_lto();
2540
2541 add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
2542
2543 cmd.output_filename(out_filename);
2544
2545 if crate_type == CrateType::Executable
2546 && sess.target.is_like_windows
2547 && let Some(s) = &codegen_results.crate_info.windows_subsystem
2548 {
2549 cmd.subsystem(s);
2550 }
2551
2552 if !sess.link_dead_code() {
2555 let keep_metadata =
2560 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2561 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2562 {
2563 cmd.gc_sections(keep_metadata);
2564 } else {
2565 cmd.no_gc_sections();
2566 }
2567 }
2568
2569 cmd.set_output_kind(link_output_kind, crate_type, out_filename);
2570
2571 add_relro_args(cmd, sess);
2572
2573 cmd.optimize();
2575
2576 let natvis_visualizers = collect_natvis_visualizers(
2578 tmpdir,
2579 sess,
2580 &codegen_results.crate_info.local_crate_name,
2581 &codegen_results.crate_info.natvis_debugger_visualizers,
2582 );
2583
2584 cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
2586
2587 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2590 cmd.no_default_libraries();
2591 }
2592
2593 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2594 cmd.pgo_gen();
2595 }
2596
2597 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2598 cmd.control_flow_guard();
2599 }
2600
2601 if sess.opts.unstable_opts.ehcont_guard {
2603 cmd.ehcont_guard();
2604 }
2605
2606 add_rpath_args(cmd, sess, codegen_results, out_filename);
2607}
2608
2609fn collect_natvis_visualizers(
2611 tmpdir: &Path,
2612 sess: &Session,
2613 crate_name: &Symbol,
2614 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2615) -> Vec<PathBuf> {
2616 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2617
2618 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2619 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2620
2621 match fs::write(&visualizer_out_file, &visualizer.src) {
2622 Ok(()) => {
2623 visualizer_paths.push(visualizer_out_file);
2624 }
2625 Err(error) => {
2626 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2627 path: visualizer_out_file,
2628 error,
2629 });
2630 }
2631 };
2632 }
2633 visualizer_paths
2634}
2635
2636fn add_native_libs_from_crate(
2637 cmd: &mut dyn Linker,
2638 sess: &Session,
2639 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2640 codegen_results: &CodegenResults,
2641 tmpdir: &Path,
2642 bundled_libs: &FxIndexSet<Symbol>,
2643 cnum: CrateNum,
2644 link_static: bool,
2645 link_dynamic: bool,
2646 link_output_kind: LinkOutputKind,
2647) {
2648 if !sess.opts.unstable_opts.link_native_libraries {
2649 return;
2653 }
2654
2655 if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2656 let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2658 archive_builder_builder
2659 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2660 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2661 }
2662
2663 let native_libs = match cnum {
2664 LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2665 _ => &codegen_results.crate_info.native_libraries[&cnum],
2666 };
2667
2668 let mut last = (None, NativeLibKind::Unspecified, false);
2669 for lib in native_libs {
2670 if !relevant_lib(sess, lib) {
2671 continue;
2672 }
2673
2674 last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2676 continue;
2677 } else {
2678 (Some(lib.name), lib.kind, lib.verbatim)
2679 };
2680
2681 let name = lib.name.as_str();
2682 let verbatim = lib.verbatim;
2683 match lib.kind {
2684 NativeLibKind::Static { bundle, whole_archive } => {
2685 if link_static {
2686 let bundle = bundle.unwrap_or(true);
2687 let whole_archive = whole_archive == Some(true);
2688 if bundle && cnum != LOCAL_CRATE {
2689 if let Some(filename) = lib.filename {
2690 let path = tmpdir.join(filename.as_str());
2692 cmd.link_staticlib_by_path(&path, whole_archive);
2693 }
2694 } else {
2695 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2696 }
2697 }
2698 }
2699 NativeLibKind::Dylib { as_needed } => {
2700 if link_dynamic {
2701 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2702 }
2703 }
2704 NativeLibKind::Unspecified => {
2705 if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2708 if link_static {
2709 cmd.link_staticlib_by_name(name, verbatim, false);
2710 }
2711 } else if link_dynamic {
2712 cmd.link_dylib_by_name(name, verbatim, true);
2713 }
2714 }
2715 NativeLibKind::Framework { as_needed } => {
2716 if link_dynamic {
2717 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2718 }
2719 }
2720 NativeLibKind::RawDylib => {
2721 }
2723 NativeLibKind::WasmImportModule => {}
2724 NativeLibKind::LinkArg => {
2725 if link_static {
2726 if verbatim {
2727 cmd.verbatim_arg(name);
2728 } else {
2729 cmd.link_arg(name);
2730 }
2731 }
2732 }
2733 }
2734 }
2735}
2736
2737fn add_local_native_libraries(
2738 cmd: &mut dyn Linker,
2739 sess: &Session,
2740 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2741 codegen_results: &CodegenResults,
2742 tmpdir: &Path,
2743 link_output_kind: LinkOutputKind,
2744) {
2745 let link_static = true;
2747 let link_dynamic = true;
2748 add_native_libs_from_crate(
2749 cmd,
2750 sess,
2751 archive_builder_builder,
2752 codegen_results,
2753 tmpdir,
2754 &Default::default(),
2755 LOCAL_CRATE,
2756 link_static,
2757 link_dynamic,
2758 link_output_kind,
2759 );
2760}
2761
2762fn add_upstream_rust_crates(
2763 cmd: &mut dyn Linker,
2764 sess: &Session,
2765 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2766 codegen_results: &CodegenResults,
2767 crate_type: CrateType,
2768 tmpdir: &Path,
2769 link_output_kind: LinkOutputKind,
2770) {
2771 let data = codegen_results
2779 .crate_info
2780 .dependency_formats
2781 .get(&crate_type)
2782 .expect("failed to find crate type in dependency format list");
2783
2784 if sess.target.is_like_aix {
2785 cmd.link_or_cc_arg("-bnoipath");
2791 }
2792
2793 for &cnum in &codegen_results.crate_info.used_crates {
2794 let linkage = data[cnum];
2802 let link_static_crate = linkage == Linkage::Static
2803 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2804 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2805 || codegen_results.crate_info.profiler_runtime == Some(cnum));
2806
2807 let mut bundled_libs = Default::default();
2808 match linkage {
2809 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2810 if link_static_crate {
2811 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2812 .iter()
2813 .filter_map(|lib| lib.filename)
2814 .collect();
2815 add_static_crate(
2816 cmd,
2817 sess,
2818 archive_builder_builder,
2819 codegen_results,
2820 tmpdir,
2821 cnum,
2822 &bundled_libs,
2823 );
2824 }
2825 }
2826 Linkage::Dynamic => {
2827 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2828 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2829 }
2830 }
2831
2832 let link_static = link_static_crate;
2841 let link_dynamic = false;
2843 add_native_libs_from_crate(
2844 cmd,
2845 sess,
2846 archive_builder_builder,
2847 codegen_results,
2848 tmpdir,
2849 &bundled_libs,
2850 cnum,
2851 link_static,
2852 link_dynamic,
2853 link_output_kind,
2854 );
2855 }
2856}
2857
2858fn add_upstream_native_libraries(
2859 cmd: &mut dyn Linker,
2860 sess: &Session,
2861 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2862 codegen_results: &CodegenResults,
2863 tmpdir: &Path,
2864 link_output_kind: LinkOutputKind,
2865) {
2866 for &cnum in &codegen_results.crate_info.used_crates {
2867 let link_static = false;
2873 let link_dynamic = true;
2881 add_native_libs_from_crate(
2882 cmd,
2883 sess,
2884 archive_builder_builder,
2885 codegen_results,
2886 tmpdir,
2887 &Default::default(),
2888 cnum,
2889 link_static,
2890 link_dynamic,
2891 link_output_kind,
2892 );
2893 }
2894}
2895
2896fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2906 let sysroot_lib_path = &sess.target_tlib_path.dir;
2907 let canonical_sysroot_lib_path =
2908 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2909
2910 let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2911 if canonical_lib_dir == canonical_sysroot_lib_path {
2912 sysroot_lib_path.clone()
2914 } else {
2915 fix_windows_verbatim_for_gcc(lib_dir)
2916 }
2917}
2918
2919fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2920 if let Some(dir) = path.parent() {
2921 let file_name = path.file_name().expect("library path has no file name component");
2922 rehome_sysroot_lib_dir(sess, dir).join(file_name)
2923 } else {
2924 fix_windows_verbatim_for_gcc(path)
2925 }
2926}
2927
2928fn add_static_crate(
2947 cmd: &mut dyn Linker,
2948 sess: &Session,
2949 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2950 codegen_results: &CodegenResults,
2951 tmpdir: &Path,
2952 cnum: CrateNum,
2953 bundled_lib_file_names: &FxIndexSet<Symbol>,
2954) {
2955 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2956 let cratepath = &src.rlib.as_ref().unwrap().0;
2957
2958 let mut link_upstream =
2959 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
2960
2961 if !are_upstream_rust_objects_already_included(sess)
2962 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2963 {
2964 link_upstream(cratepath);
2965 return;
2966 }
2967
2968 let dst = tmpdir.join(cratepath.file_name().unwrap());
2969 let name = cratepath.file_name().unwrap().to_str().unwrap();
2970 let name = &name[3..name.len() - 5]; let bundled_lib_file_names = bundled_lib_file_names.clone();
2972
2973 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2974 let canonical_name = name.replace('-', "_");
2975 let upstream_rust_objects_already_included =
2976 are_upstream_rust_objects_already_included(sess);
2977 let is_builtins =
2978 sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2979
2980 let mut archive = archive_builder_builder.new_archive_builder(sess);
2981 if let Err(error) = archive.add_archive(
2982 cratepath,
2983 Box::new(move |f| {
2984 if f == METADATA_FILENAME {
2985 return true;
2986 }
2987
2988 let canonical = f.replace('-', "_");
2989
2990 let is_rust_object =
2991 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
2992
2993 if upstream_rust_objects_already_included && is_rust_object && is_builtins {
2998 return true;
2999 }
3000
3001 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3007 return true;
3008 }
3009
3010 false
3011 }),
3012 ) {
3013 sess.dcx()
3014 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3015 }
3016 if archive.build(&dst) {
3017 link_upstream(&dst);
3018 }
3019 });
3020}
3021
3022fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3024 cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3025}
3026
3027fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3028 match lib.cfg {
3029 Some(ref cfg) => rustc_attr_parsing::cfg_matches(cfg, sess, CRATE_NODE_ID, None),
3030 None => true,
3031 }
3032}
3033
3034pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3035 match sess.lto() {
3036 config::Lto::Fat => true,
3037 config::Lto::Thin => {
3038 !sess.opts.cg.linker_plugin_lto.enabled()
3041 }
3042 config::Lto::No | config::Lto::ThinLocal => false,
3043 }
3044}
3045
3046fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3053 if !sess.target.is_like_osx {
3054 return;
3055 }
3056 let LinkerFlavor::Darwin(cc, _) = flavor else {
3057 return;
3058 };
3059
3060 let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3062 let target_os = &*sess.target.os;
3063 let target_abi = &*sess.target.abi;
3064
3065 let ld64_arch = match llvm_arch {
3073 "armv7k" => "armv7k",
3074 "armv7s" => "armv7s",
3075 "arm64" => "arm64",
3076 "arm64e" => "arm64e",
3077 "arm64_32" => "arm64_32",
3078 "i386" | "i686" => "i386",
3082 "x86_64" => "x86_64",
3083 "x86_64h" => "x86_64h",
3084 _ => bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3085 };
3086
3087 if cc == Cc::No {
3088 cmd.link_args(&["-arch", ld64_arch]);
3098
3099 let platform_name = match (target_os, target_abi) {
3115 (os, "") => os,
3116 ("ios", "macabi") => "mac-catalyst",
3117 ("ios", "sim") => "ios-simulator",
3118 ("tvos", "sim") => "tvos-simulator",
3119 ("watchos", "sim") => "watchos-simulator",
3120 ("visionos", "sim") => "visionos-simulator",
3121 _ => bug!("invalid OS/ABI combination for Apple target: {target_os}, {target_abi}"),
3122 };
3123
3124 let (major, minor, patch) = apple::deployment_target(sess);
3125 let min_version = format!("{major}.{minor}.{patch}");
3126
3127 let sdk_version = &*min_version;
3160
3161 cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3170 } else {
3171 if target_os == "macos" {
3186 cmd.cc_args(&["-arch", ld64_arch]);
3191
3192 let (major, minor, patch) = apple::deployment_target(sess);
3195 cmd.cc_arg(&format!("-mmacosx-version-min={major}.{minor}.{patch}"));
3198
3199 } else {
3204 cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3205 }
3206 }
3207}
3208
3209fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3210 let os = &sess.target.os;
3211 if sess.target.vendor != "apple"
3212 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "visionos" | "macos")
3213 || !matches!(flavor, LinkerFlavor::Darwin(..))
3214 {
3215 return None;
3216 }
3217
3218 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
3219 return None;
3220 }
3221
3222 let sdk_root = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
3223
3224 match flavor {
3225 LinkerFlavor::Darwin(Cc::Yes, _) => {
3226 cmd.cc_arg("-isysroot");
3233 cmd.cc_arg(&sdk_root);
3234 }
3235 LinkerFlavor::Darwin(Cc::No, _) => {
3236 cmd.link_arg("-syslibroot");
3237 cmd.link_arg(&sdk_root);
3238 }
3239 _ => unreachable!(),
3240 }
3241
3242 Some(sdk_root)
3243}
3244
3245fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3246 if let Ok(sdkroot) = env::var("SDKROOT") {
3247 let p = PathBuf::from(&sdkroot);
3248
3249 match &*apple::sdk_name(&sess.target).to_lowercase() {
3258 "appletvos"
3259 if sdkroot.contains("TVSimulator.platform")
3260 || sdkroot.contains("MacOSX.platform") => {}
3261 "appletvsimulator"
3262 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3263 "iphoneos"
3264 if sdkroot.contains("iPhoneSimulator.platform")
3265 || sdkroot.contains("MacOSX.platform") => {}
3266 "iphonesimulator"
3267 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3268 }
3269 "macosx"
3270 if sdkroot.contains("iPhoneOS.platform")
3271 || sdkroot.contains("iPhoneSimulator.platform") => {}
3272 "watchos"
3273 if sdkroot.contains("WatchSimulator.platform")
3274 || sdkroot.contains("MacOSX.platform") => {}
3275 "watchsimulator"
3276 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3277 "xros"
3278 if sdkroot.contains("XRSimulator.platform")
3279 || sdkroot.contains("MacOSX.platform") => {}
3280 "xrsimulator"
3281 if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3282 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3284 _ => return Some(p),
3285 }
3286 }
3287
3288 apple::get_sdk_root(sess)
3289}
3290
3291fn add_lld_args(
3296 cmd: &mut dyn Linker,
3297 sess: &Session,
3298 flavor: LinkerFlavor,
3299 self_contained_components: LinkSelfContainedComponents,
3300) {
3301 debug!(
3302 "add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3303 flavor, self_contained_components,
3304 );
3305
3306 if !(flavor.uses_cc() && flavor.uses_lld()) {
3309 return;
3310 }
3311
3312 let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3318 let self_contained_target = self_contained_components.is_linker_enabled();
3319
3320 let self_contained_linker = self_contained_cli || self_contained_target;
3321 if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3322 let mut linker_path_exists = false;
3323 for path in sess.get_tools_search_paths(false) {
3324 let linker_path = path.join("gcc-ld");
3325 linker_path_exists |= linker_path.exists();
3326 cmd.cc_arg({
3327 let mut arg = OsString::from("-B");
3328 arg.push(linker_path);
3329 arg
3330 });
3331 }
3332 if !linker_path_exists {
3333 sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3336 }
3337 }
3338
3339 if !sess.target.is_like_wasm {
3346 cmd.cc_arg("-fuse-ld=lld");
3347
3348 if sess.target.llvm_target == "x86_64-unknown-linux-gnu" {
3374 cmd.link_arg("-znostart-stop-gc");
3375 }
3376 }
3377
3378 if !flavor.is_gnu() {
3379 if sess.target.linker_flavor != sess.host.linker_flavor {
3399 cmd.cc_arg(format!("--target={}", versioned_llvm_target(sess)));
3400 }
3401 }
3402}