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::{TempDirBuilder, 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 tracing::{debug, info, warn};
52
53use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
54use super::command::Command;
55use super::linker::{self, Linker};
56use super::metadata::{MetadataPosition, create_wrapper_file};
57use super::rpath::{self, RPathConfig};
58use super::{apple, versioned_llvm_target};
59use crate::{
60 CodegenResults, CompiledModule, CrateInfo, NativeLib, errors, looks_like_rust_object_file,
61};
62
63pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
64 if let Err(e) = fs::remove_file(path) {
65 if e.kind() != io::ErrorKind::NotFound {
66 dcx.err(format!("failed to remove {}: {}", path.display(), e));
67 }
68 }
69}
70
71pub fn link_binary(
74 sess: &Session,
75 archive_builder_builder: &dyn ArchiveBuilderBuilder,
76 codegen_results: CodegenResults,
77 outputs: &OutputFilenames,
78) {
79 let _timer = sess.timer("link_binary");
80 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
81 let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
82 for &crate_type in &codegen_results.crate_info.crate_types {
83 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
85 && !output_metadata
86 && crate_type == CrateType::Executable
87 {
88 continue;
89 }
90
91 if invalid_output_for_target(sess, crate_type) {
92 bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
93 }
94
95 sess.time("link_binary_check_files_are_writeable", || {
96 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
97 check_file_is_writeable(obj, sess);
98 }
99 });
100
101 if outputs.outputs.should_link() {
102 let tmpdir = TempDirBuilder::new()
103 .prefix("rustc")
104 .tempdir()
105 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
106 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
107 let output = out_filename(
108 sess,
109 crate_type,
110 outputs,
111 codegen_results.crate_info.local_crate_name,
112 );
113 let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
114 let out_filename = output.file_for_writing(
115 outputs,
116 OutputType::Exe,
117 &crate_name,
118 sess.invocation_temp.as_deref(),
119 );
120 match crate_type {
121 CrateType::Rlib => {
122 let _timer = sess.timer("link_rlib");
123 info!("preparing rlib to {:?}", out_filename);
124 link_rlib(
125 sess,
126 archive_builder_builder,
127 &codegen_results,
128 RlibFlavor::Normal,
129 &path,
130 )
131 .build(&out_filename);
132 }
133 CrateType::Staticlib => {
134 link_staticlib(
135 sess,
136 archive_builder_builder,
137 &codegen_results,
138 &out_filename,
139 &path,
140 );
141 }
142 _ => {
143 link_natively(
144 sess,
145 archive_builder_builder,
146 crate_type,
147 &out_filename,
148 &codegen_results,
149 path.as_ref(),
150 );
151 }
152 }
153 if sess.opts.json_artifact_notifications {
154 sess.dcx().emit_artifact_notification(&out_filename, "link");
155 }
156
157 if sess.prof.enabled()
158 && let Some(artifact_name) = out_filename.file_name()
159 {
160 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
162
163 sess.prof.artifact_size(
164 "linked_artifact",
165 artifact_name.to_string_lossy(),
166 file_size,
167 );
168 }
169
170 if output.is_stdout() {
171 if output.is_tty() {
172 sess.dcx().emit_err(errors::BinaryOutputToTty {
173 shorthand: OutputType::Exe.shorthand(),
174 });
175 } else if let Err(e) = copy_to_stdout(&out_filename) {
176 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
177 }
178 tempfiles_for_stdout_output.push(out_filename);
179 }
180 }
181 }
182
183 sess.time("link_binary_remove_temps", || {
185 if sess.opts.cg.save_temps {
187 return;
188 }
189
190 let maybe_remove_temps_from_module =
191 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
192 if !preserve_objects && let Some(ref obj) = module.object {
193 ensure_removed(sess.dcx(), obj);
194 }
195
196 if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
197 ensure_removed(sess.dcx(), dwo_obj);
198 }
199 };
200
201 let remove_temps_from_module =
202 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
203
204 if let Some(ref metadata_module) = codegen_results.metadata_module {
206 remove_temps_from_module(metadata_module);
207 }
208
209 if let Some(ref allocator_module) = codegen_results.allocator_module {
210 remove_temps_from_module(allocator_module);
211 }
212
213 for temp in tempfiles_for_stdout_output {
215 ensure_removed(sess.dcx(), &temp);
216 }
217
218 if !sess.opts.output_types.should_link() {
221 return;
222 }
223
224 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
226 debug!(?preserve_objects, ?preserve_dwarf_objects);
227
228 for module in &codegen_results.modules {
229 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
230 }
231 });
232}
233
234pub fn each_linked_rlib(
237 info: &CrateInfo,
238 crate_type: Option<CrateType>,
239 f: &mut dyn FnMut(CrateNum, &Path),
240) -> Result<(), errors::LinkRlibError> {
241 let fmts = if let Some(crate_type) = crate_type {
242 let Some(fmts) = info.dependency_formats.get(&crate_type) else {
243 return Err(errors::LinkRlibError::MissingFormat);
244 };
245
246 fmts
247 } else {
248 let mut dep_formats = info.dependency_formats.iter();
249 let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
250 if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
251 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
252 ty1: format!("{ty1:?}"),
253 ty2: format!("{ty2:?}"),
254 list1: format!("{list1:?}"),
255 list2: format!("{list2:?}"),
256 });
257 }
258 list1
259 };
260
261 let used_dep_crates = info.used_crates.iter();
262 for &cnum in used_dep_crates {
263 match fmts.get(cnum) {
264 Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
265 Some(_) => {}
266 None => return Err(errors::LinkRlibError::MissingFormat),
267 }
268 let crate_name = info.crate_name[&cnum];
269 let used_crate_source = &info.used_crate_source[&cnum];
270 if let Some((path, _)) = &used_crate_source.rlib {
271 f(cnum, path);
272 } else if used_crate_source.rmeta.is_some() {
273 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
274 } else {
275 return Err(errors::LinkRlibError::NotFound { crate_name });
276 }
277 }
278 Ok(())
279}
280
281fn link_rlib<'a>(
287 sess: &'a Session,
288 archive_builder_builder: &dyn ArchiveBuilderBuilder,
289 codegen_results: &CodegenResults,
290 flavor: RlibFlavor,
291 tmpdir: &MaybeTempDir,
292) -> Box<dyn ArchiveBuilder + 'a> {
293 let mut ab = archive_builder_builder.new_archive_builder(sess);
294
295 let trailing_metadata = match flavor {
296 RlibFlavor::Normal => {
297 let (metadata, metadata_position) = create_wrapper_file(
298 sess,
299 ".rmeta".to_string(),
300 codegen_results.metadata.stub_or_full(),
301 );
302 let metadata = emit_wrapper_file(sess, &metadata, tmpdir, METADATA_FILENAME);
303 match metadata_position {
304 MetadataPosition::First => {
305 ab.add_file(&metadata);
311 None
312 }
313 MetadataPosition::Last => Some(metadata),
314 }
315 }
316
317 RlibFlavor::StaticlibBase => None,
318 };
319
320 for m in &codegen_results.modules {
321 if let Some(obj) = m.object.as_ref() {
322 ab.add_file(obj);
323 }
324
325 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
326 ab.add_file(dwarf_obj);
327 }
328 }
329
330 match flavor {
331 RlibFlavor::Normal => {}
332 RlibFlavor::StaticlibBase => {
333 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
334 if let Some(obj) = obj {
335 ab.add_file(obj);
336 }
337 }
338 }
339
340 let mut packed_bundled_libs = Vec::new();
342
343 for lib in codegen_results.crate_info.used_libraries.iter() {
360 let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
361 continue;
362 };
363 if flavor == RlibFlavor::Normal
364 && let Some(filename) = lib.filename
365 {
366 let path = find_native_static_library(filename.as_str(), true, sess);
367 let src = read(path)
368 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
369 let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
370 let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
371 packed_bundled_libs.push(wrapper_file);
372 } else {
373 let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
374 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
375 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
376 });
377 }
378 }
379
380 if sess.target.is_like_windows {
384 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
385 sess,
386 archive_builder_builder,
387 codegen_results.crate_info.used_libraries.iter(),
388 tmpdir.as_ref(),
389 true,
390 ) {
391 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
392 sess.dcx()
393 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
394 });
395 }
396 }
397
398 if let Some(trailing_metadata) = trailing_metadata {
399 ab.add_file(&trailing_metadata);
425 }
426
427 for lib in packed_bundled_libs {
430 ab.add_file(&lib)
431 }
432
433 ab
434}
435
436fn link_staticlib(
448 sess: &Session,
449 archive_builder_builder: &dyn ArchiveBuilderBuilder,
450 codegen_results: &CodegenResults,
451 out_filename: &Path,
452 tempdir: &MaybeTempDir,
453) {
454 info!("preparing staticlib to {:?}", out_filename);
455 let mut ab = link_rlib(
456 sess,
457 archive_builder_builder,
458 codegen_results,
459 RlibFlavor::StaticlibBase,
460 tempdir,
461 );
462 let mut all_native_libs = vec![];
463
464 let res = each_linked_rlib(
465 &codegen_results.crate_info,
466 Some(CrateType::Staticlib),
467 &mut |cnum, path| {
468 let lto = are_upstream_rust_objects_already_included(sess)
469 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
470
471 let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
472 let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
473 let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
474
475 let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
476 ab.add_archive(
477 path,
478 Box::new(move |fname: &str| {
479 if fname == METADATA_FILENAME {
481 return true;
482 }
483
484 if lto && looks_like_rust_object_file(fname) {
486 return true;
487 }
488
489 if bundled_libs.contains(&Symbol::intern(fname)) {
491 return true;
492 }
493
494 false
495 }),
496 )
497 .unwrap();
498
499 archive_builder_builder
500 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
501 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
502
503 for filename in relevant_libs.iter() {
504 let joined = tempdir.as_ref().join(filename.as_str());
505 let path = joined.as_path();
506 ab.add_archive(path, Box::new(|_| false)).unwrap();
507 }
508
509 all_native_libs
510 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
511 },
512 );
513 if let Err(e) = res {
514 sess.dcx().emit_fatal(e);
515 }
516
517 ab.build(out_filename);
518
519 let crates = codegen_results.crate_info.used_crates.iter();
520
521 let fmts = codegen_results
522 .crate_info
523 .dependency_formats
524 .get(&CrateType::Staticlib)
525 .expect("no dependency formats for staticlib");
526
527 let mut all_rust_dylibs = vec![];
528 for &cnum in crates {
529 let Some(Linkage::Dynamic) = fmts.get(cnum) else {
530 continue;
531 };
532 let crate_name = codegen_results.crate_info.crate_name[&cnum];
533 let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
534 if let Some((path, _)) = &used_crate_source.dylib {
535 all_rust_dylibs.push(&**path);
536 } else if used_crate_source.rmeta.is_some() {
537 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
538 } else {
539 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
540 }
541 }
542
543 all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
544
545 for print in &sess.opts.prints {
546 if print.kind == PrintKind::NativeStaticLibs {
547 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
548 }
549 }
550}
551
552fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
555 let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
556 dwp_out_filename.push(".dwp");
557 debug!(?dwp_out_filename, ?executable_out_filename);
558
559 #[derive(Default)]
560 struct ThorinSession<Relocations> {
561 arena_data: TypedArena<Vec<u8>>,
562 arena_mmap: TypedArena<Mmap>,
563 arena_relocations: TypedArena<Relocations>,
564 }
565
566 impl<Relocations> ThorinSession<Relocations> {
567 fn alloc_mmap(&self, data: Mmap) -> &Mmap {
568 &*self.arena_mmap.alloc(data)
569 }
570 }
571
572 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
573 fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
574 &*self.arena_data.alloc(data)
575 }
576
577 fn alloc_relocation(&self, data: Relocations) -> &Relocations {
578 &*self.arena_relocations.alloc(data)
579 }
580
581 fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
582 let file = File::open(&path)?;
583 let mmap = (unsafe { Mmap::map(file) })?;
584 Ok(self.alloc_mmap(mmap))
585 }
586 }
587
588 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
589 let thorin_sess = ThorinSession::default();
590 let mut package = thorin::DwarfPackage::new(&thorin_sess);
591
592 match sess.opts.unstable_opts.split_dwarf_kind {
594 SplitDwarfKind::Single => {
595 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
596 package.add_input_object(input_obj)?;
597 }
598 }
599 SplitDwarfKind::Split => {
600 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
601 package.add_input_object(input_obj)?;
602 }
603 }
604 }
605
606 let input_rlibs = cg_results
608 .crate_info
609 .used_crate_source
610 .items()
611 .filter_map(|(_, csource)| csource.rlib.as_ref())
612 .map(|(path, _)| path)
613 .into_sorted_stable_ord();
614
615 for input_rlib in input_rlibs {
616 debug!(?input_rlib);
617 package.add_input_object(input_rlib)?;
618 }
619
620 package.add_executable(
630 executable_out_filename,
631 thorin::MissingReferencedObjectBehaviour::Skip,
632 )?;
633
634 let output_stream = BufWriter::new(
635 OpenOptions::new()
636 .read(true)
637 .write(true)
638 .create(true)
639 .truncate(true)
640 .open(dwp_out_filename)?,
641 );
642 let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
643 package.finish()?.emit(&mut output_stream)?;
644 output_stream.result()?;
645 output_stream.into_inner().flush()?;
646
647 Ok(())
648 }) {
649 Ok(()) => {}
650 Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
651 }
652}
653
654#[derive(LintDiagnostic)]
655#[diag(codegen_ssa_linker_output)]
656struct LinkerOutput {
659 inner: String,
660}
661
662fn link_natively(
667 sess: &Session,
668 archive_builder_builder: &dyn ArchiveBuilderBuilder,
669 crate_type: CrateType,
670 out_filename: &Path,
671 codegen_results: &CodegenResults,
672 tmpdir: &Path,
673) {
674 info!("preparing {:?} to {:?}", crate_type, out_filename);
675 let (linker_path, flavor) = linker_and_flavor(sess);
676 let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
677
678 let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
683 let archive_member =
684 should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
685 let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
686
687 let mut cmd = linker_with_args(
688 &linker_path,
689 flavor,
690 sess,
691 archive_builder_builder,
692 crate_type,
693 tmpdir,
694 temp_filename,
695 codegen_results,
696 self_contained_components,
697 );
698
699 linker::disable_localization(&mut cmd);
700
701 for (k, v) in sess.target.link_env.as_ref() {
702 cmd.env(k.as_ref(), v.as_ref());
703 }
704 for k in sess.target.link_env_remove.as_ref() {
705 cmd.env_remove(k.as_ref());
706 }
707
708 for print in &sess.opts.prints {
709 if print.kind == PrintKind::LinkArgs {
710 let content = format!("{cmd:?}\n");
711 print.out.overwrite(&content, sess);
712 }
713 }
714
715 sess.dcx().abort_if_errors();
717
718 info!("{cmd:?}");
720 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
721 let unknown_arg_regex =
722 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
723 let mut prog;
724 let mut i = 0;
725 loop {
726 i += 1;
727 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
728 let Ok(ref output) = prog else {
729 break;
730 };
731 if output.status.success() {
732 break;
733 }
734 let mut out = output.stderr.clone();
735 out.extend(&output.stdout);
736 let out = String::from_utf8_lossy(&out);
737
738 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
745 && unknown_arg_regex.is_match(&out)
746 && out.contains("-no-pie")
747 && cmd.get_args().iter().any(|e| e == "-no-pie")
748 {
749 info!("linker output: {:?}", out);
750 warn!("Linker does not support -no-pie command line option. Retrying without.");
751 for arg in cmd.take_args() {
752 if arg != "-no-pie" {
753 cmd.arg(arg);
754 }
755 }
756 info!("{cmd:?}");
757 continue;
758 }
759
760 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))
766 && unknown_arg_regex.is_match(&out)
767 && out.contains("-fuse-ld=lld")
768 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
769 {
770 info!("linker output: {:?}", out);
771 info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
772 for arg in cmd.take_args() {
773 if arg.to_string_lossy() != "-fuse-ld=lld" {
774 cmd.arg(arg);
775 }
776 }
777 info!("{cmd:?}");
778 continue;
779 }
780
781 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
784 && unknown_arg_regex.is_match(&out)
785 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
786 && cmd.get_args().iter().any(|e| e == "-static-pie")
787 {
788 info!("linker output: {:?}", out);
789 warn!(
790 "Linker does not support -static-pie command line option. Retrying with -static instead."
791 );
792 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
794 let opts = &sess.target;
795 let pre_objects = if self_contained_crt_objects {
796 &opts.pre_link_objects_self_contained
797 } else {
798 &opts.pre_link_objects
799 };
800 let post_objects = if self_contained_crt_objects {
801 &opts.post_link_objects_self_contained
802 } else {
803 &opts.post_link_objects
804 };
805 let get_objects = |objects: &CrtObjects, kind| {
806 objects
807 .get(&kind)
808 .iter()
809 .copied()
810 .flatten()
811 .map(|obj| {
812 get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
813 })
814 .collect::<Vec<_>>()
815 };
816 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
817 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
818 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
819 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
820 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
823 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
824 for arg in cmd.take_args() {
825 if arg == "-static-pie" {
826 cmd.arg("-static");
828 } else if pre_objects_static_pie.contains(&arg) {
829 cmd.args(mem::take(&mut pre_objects_static));
831 } else if post_objects_static_pie.contains(&arg) {
832 cmd.args(mem::take(&mut post_objects_static));
834 } else {
835 cmd.arg(arg);
836 }
837 }
838 info!("{cmd:?}");
839 continue;
840 }
841
842 if !retry_on_segfault || i > 3 {
858 break;
859 }
860 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
861 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
862 if out.contains(msg_segv) || out.contains(msg_bus) {
863 warn!(
864 ?cmd, %out,
865 "looks like the linker segfaulted when we tried to call it, \
866 automatically retrying again",
867 );
868 continue;
869 }
870
871 if is_illegal_instruction(&output.status) {
872 warn!(
873 ?cmd, %out, status = %output.status,
874 "looks like the linker hit an illegal instruction when we \
875 tried to call it, automatically retrying again.",
876 );
877 continue;
878 }
879
880 #[cfg(unix)]
881 fn is_illegal_instruction(status: &ExitStatus) -> bool {
882 use std::os::unix::prelude::*;
883 status.signal() == Some(libc::SIGILL)
884 }
885
886 #[cfg(not(unix))]
887 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
888 false
889 }
890 }
891
892 match prog {
893 Ok(prog) => {
894 let is_msvc_link_exe = sess.target.is_like_msvc
895 && flavor == LinkerFlavor::Msvc(Lld::No)
896 && linker_path.to_str() == Some("link.exe");
898
899 if !prog.status.success() {
900 let mut output = prog.stderr.clone();
901 output.extend_from_slice(&prog.stdout);
902 let escaped_output = escape_linker_output(&output, flavor);
903 let err = errors::LinkingFailed {
904 linker_path: &linker_path,
905 exit_status: prog.status,
906 command: cmd,
907 escaped_output,
908 verbose: sess.opts.verbose,
909 sysroot_dir: sess.sysroot.clone(),
910 };
911 sess.dcx().emit_err(err);
912 if let Some(code) = prog.status.code() {
916 if is_msvc_link_exe && (code < 1000 || code > 9999) {
919 let is_vs_installed = windows_registry::find_vs_version().is_ok();
920 let has_linker =
921 windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
922
923 sess.dcx().emit_note(errors::LinkExeUnexpectedError);
924 if is_vs_installed && has_linker {
925 sess.dcx().emit_note(errors::RepairVSBuildTools);
927 sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
928 } else if is_vs_installed {
929 sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
931 } else {
932 sess.dcx().emit_note(errors::VisualStudioNotInstalled);
934 }
935 }
936 }
937
938 sess.dcx().abort_if_errors();
939 }
940
941 let stderr = escape_string(&prog.stderr);
942 let mut stdout = escape_string(&prog.stdout);
943 info!("linker stderr:\n{}", &stderr);
944 info!("linker stdout:\n{}", &stdout);
945
946 if is_msvc_link_exe {
949 if let Ok(str) = str::from_utf8(&prog.stdout) {
950 let mut output = String::with_capacity(str.len());
951 for line in stdout.lines() {
952 if line.starts_with(" Creating library")
953 || line.starts_with("Generating code")
954 || line.starts_with("Finished generating code")
955 {
956 continue;
957 }
958 output += line;
959 output += "\r\n"
960 }
961 stdout = escape_string(output.trim().as_bytes())
962 }
963 }
964
965 let level = codegen_results.crate_info.lint_levels.linker_messages;
966 let lint = |msg| {
967 lint_level(sess, LINKER_MESSAGES, level, None, |diag| {
968 LinkerOutput { inner: msg }.decorate_lint(diag)
969 })
970 };
971
972 if !prog.stderr.is_empty() {
973 let stderr = stderr
975 .strip_prefix("warning: ")
976 .unwrap_or(&stderr)
977 .replace(": warning: ", ": ");
978 lint(format!("linker stderr: {stderr}"));
979 }
980 if !stdout.is_empty() {
981 lint(format!("linker stdout: {}", stdout))
982 }
983 }
984 Err(e) => {
985 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
986
987 let err = if linker_not_found {
988 sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
989 } else {
990 sess.dcx().emit_err(errors::UnableToExeLinker {
991 linker_path,
992 error: e,
993 command_formatted: format!("{cmd:?}"),
994 })
995 };
996
997 if sess.target.is_like_msvc && linker_not_found {
998 sess.dcx().emit_note(errors::MsvcMissingLinker);
999 sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
1000 sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
1001 }
1002 err.raise_fatal();
1003 }
1004 }
1005
1006 match sess.split_debuginfo() {
1007 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
1010
1011 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
1014
1015 SplitDebuginfo::Packed if sess.target.is_like_darwin => {
1019 let prog = Command::new("dsymutil").arg(out_filename).output();
1020 match prog {
1021 Ok(prog) => {
1022 if !prog.status.success() {
1023 let mut output = prog.stderr.clone();
1024 output.extend_from_slice(&prog.stdout);
1025 sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
1026 status: prog.status,
1027 output: escape_string(&output),
1028 });
1029 }
1030 }
1031 Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1032 }
1033 }
1034
1035 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1038
1039 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1045 }
1046
1047 let strip = sess.opts.cg.strip;
1048
1049 if sess.target.is_like_darwin {
1050 let stripcmd = "rust-objcopy";
1051 match (strip, crate_type) {
1052 (Strip::Debuginfo, _) => {
1053 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1054 }
1055 (
1057 Strip::Symbols,
1058 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1059 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1060 (Strip::Symbols, _) => {
1061 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1062 }
1063 (Strip::None, _) => {}
1064 }
1065 }
1066
1067 if sess.target.is_like_solaris {
1068 let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1075 match strip {
1076 Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1078 Strip::Symbols => {}
1080 Strip::None => {}
1081 }
1082 }
1083
1084 if sess.target.is_like_aix {
1085 if !sess.host.is_like_aix {
1087 sess.dcx().emit_warn(errors::AixStripNotUsed);
1088 }
1089 let stripcmd = "/usr/bin/strip";
1090 match strip {
1091 Strip::Debuginfo => {
1092 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-l"])
1094 }
1095 Strip::Symbols => {
1096 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-r"])
1098 }
1099 Strip::None => {}
1100 }
1101 }
1102
1103 if should_archive {
1104 let mut ab = archive_builder_builder.new_archive_builder(sess);
1105 ab.add_file(temp_filename);
1106 ab.build(out_filename);
1107 }
1108}
1109
1110fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1111 let mut cmd = Command::new(util);
1112 cmd.args(options);
1113
1114 let mut new_path = sess.get_tools_search_paths(false);
1115 if let Some(path) = env::var_os("PATH") {
1116 new_path.extend(env::split_paths(&path));
1117 }
1118 cmd.env("PATH", env::join_paths(new_path).unwrap());
1119
1120 let prog = cmd.arg(out_filename).output();
1121 match prog {
1122 Ok(prog) => {
1123 if !prog.status.success() {
1124 let mut output = prog.stderr.clone();
1125 output.extend_from_slice(&prog.stdout);
1126 sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1127 util,
1128 status: prog.status,
1129 output: escape_string(&output),
1130 });
1131 }
1132 }
1133 Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1134 }
1135}
1136
1137fn escape_string(s: &[u8]) -> String {
1138 match str::from_utf8(s) {
1139 Ok(s) => s.to_owned(),
1140 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1141 }
1142}
1143
1144#[cfg(not(windows))]
1145fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1146 escape_string(s)
1147}
1148
1149#[cfg(windows)]
1152fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1153 if flavour != LinkerFlavor::Msvc(Lld::No) {
1155 return escape_string(s);
1156 }
1157 match str::from_utf8(s) {
1158 Ok(s) => return s.to_owned(),
1159 Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1160 Some(s) => s,
1161 None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1163 },
1164 }
1165}
1166
1167#[cfg(windows)]
1169mod win {
1170 use windows::Win32::Globalization::{
1171 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1172 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1173 };
1174
1175 pub(super) fn oem_code_page() -> u32 {
1178 unsafe {
1179 let mut cp: u32 = 0;
1180 let len = size_of::<u32>() / size_of::<u16>();
1183 let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1184 let len_written = GetLocaleInfoEx(
1185 LOCALE_NAME_SYSTEM_DEFAULT,
1186 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1187 Some(data),
1188 );
1189 if len_written as usize == len { cp } else { CP_OEMCP }
1190 }
1191 }
1192 pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1201 if s.len() > isize::MAX as usize {
1203 return None;
1204 }
1205 let flags = MB_ERR_INVALID_CHARS;
1207 let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1210 if len > 0 {
1211 let mut utf16 = vec![0; len as usize];
1212 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1213 if len > 0 {
1214 return utf16.get(..len as usize).map(String::from_utf16_lossy);
1215 }
1216 }
1217 None
1218 }
1219}
1220
1221fn add_sanitizer_libraries(
1222 sess: &Session,
1223 flavor: LinkerFlavor,
1224 crate_type: CrateType,
1225 linker: &mut dyn Linker,
1226) {
1227 if sess.target.is_like_android {
1228 return;
1231 }
1232
1233 if sess.opts.unstable_opts.external_clangrt {
1234 return;
1237 }
1238
1239 if matches!(crate_type, CrateType::Rlib | CrateType::Staticlib) {
1240 return;
1241 }
1242
1243 if matches!(
1248 crate_type,
1249 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1250 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1251 {
1252 return;
1253 }
1254
1255 let sanitizer = sess.opts.unstable_opts.sanitizer;
1256 if sanitizer.contains(SanitizerSet::ADDRESS) {
1257 link_sanitizer_runtime(sess, flavor, linker, "asan");
1258 }
1259 if sanitizer.contains(SanitizerSet::DATAFLOW) {
1260 link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1261 }
1262 if sanitizer.contains(SanitizerSet::LEAK)
1263 && !sanitizer.contains(SanitizerSet::ADDRESS)
1264 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1265 {
1266 link_sanitizer_runtime(sess, flavor, linker, "lsan");
1267 }
1268 if sanitizer.contains(SanitizerSet::MEMORY) {
1269 link_sanitizer_runtime(sess, flavor, linker, "msan");
1270 }
1271 if sanitizer.contains(SanitizerSet::THREAD) {
1272 link_sanitizer_runtime(sess, flavor, linker, "tsan");
1273 }
1274 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1275 link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1276 }
1277 if sanitizer.contains(SanitizerSet::SAFESTACK) {
1278 link_sanitizer_runtime(sess, flavor, linker, "safestack");
1279 }
1280}
1281
1282fn link_sanitizer_runtime(
1283 sess: &Session,
1284 flavor: LinkerFlavor,
1285 linker: &mut dyn Linker,
1286 name: &str,
1287) {
1288 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1289 let path = sess.target_tlib_path.dir.join(filename);
1290 if path.exists() {
1291 sess.target_tlib_path.dir.clone()
1292 } else {
1293 let default_sysroot = filesearch::get_or_default_sysroot();
1294 let default_tlib =
1295 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.tuple());
1296 default_tlib
1297 }
1298 }
1299
1300 let channel =
1301 option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
1302
1303 if sess.target.is_like_darwin {
1304 let filename = format!("rustc{channel}_rt.{name}");
1309 let path = find_sanitizer_runtime(sess, &filename);
1310 let rpath = path.to_str().expect("non-utf8 component in path");
1311 linker.link_args(&["-rpath", rpath]);
1312 linker.link_dylib_by_name(&filename, false, true);
1313 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1314 linker.link_arg("/INFERASANLIBS");
1317 } else {
1318 let filename = format!("librustc{channel}_rt.{name}.a");
1319 let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1320 linker.link_staticlib_by_path(&path, true);
1321 }
1322}
1323
1324pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1335 !sess.target.no_builtins
1339 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1340}
1341
1342pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1344 fn infer_from(
1345 sess: &Session,
1346 linker: Option<PathBuf>,
1347 flavor: Option<LinkerFlavor>,
1348 features: LinkerFeaturesCli,
1349 ) -> Option<(PathBuf, LinkerFlavor)> {
1350 let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1351 match (linker, flavor) {
1352 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1353 (None, Some(flavor)) => Some((
1355 PathBuf::from(match flavor {
1356 LinkerFlavor::Gnu(Cc::Yes, _)
1357 | LinkerFlavor::Darwin(Cc::Yes, _)
1358 | LinkerFlavor::WasmLld(Cc::Yes)
1359 | LinkerFlavor::Unix(Cc::Yes) => {
1360 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1361 "gcc"
1368 } else {
1369 "cc"
1370 }
1371 }
1372 LinkerFlavor::Gnu(_, Lld::Yes)
1373 | LinkerFlavor::Darwin(_, Lld::Yes)
1374 | LinkerFlavor::WasmLld(..)
1375 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1376 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1377 "ld"
1378 }
1379 LinkerFlavor::Msvc(..) => "link.exe",
1380 LinkerFlavor::EmCc => {
1381 if cfg!(windows) {
1382 "emcc.bat"
1383 } else {
1384 "emcc"
1385 }
1386 }
1387 LinkerFlavor::Bpf => "bpf-linker",
1388 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1389 LinkerFlavor::Ptx => "rust-ptx-linker",
1390 }),
1391 flavor,
1392 )),
1393 (Some(linker), None) => {
1394 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1395 sess.dcx().emit_fatal(errors::LinkerFileStem);
1396 });
1397 let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1398 let flavor = adjust_flavor_to_features(flavor, features);
1399 Some((linker, flavor))
1400 }
1401 (None, None) => None,
1402 }
1403 }
1404
1405 fn adjust_flavor_to_features(
1410 flavor: LinkerFlavor,
1411 features: LinkerFeaturesCli,
1412 ) -> LinkerFlavor {
1413 if features.enabled.contains(LinkerFeatures::LLD) {
1415 flavor.with_lld_enabled()
1416 } else if features.disabled.contains(LinkerFeatures::LLD) {
1417 flavor.with_lld_disabled()
1418 } else {
1419 flavor
1420 }
1421 }
1422
1423 let features = sess.opts.unstable_opts.linker_features;
1424
1425 let linker_flavor = match sess.opts.cg.linker_flavor {
1428 Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1430 Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1431 _ => sess
1433 .opts
1434 .cg
1435 .linker_flavor
1436 .map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
1437 };
1438 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1439 return ret;
1440 }
1441
1442 if let Some(ret) = infer_from(
1443 sess,
1444 sess.target.linker.as_deref().map(PathBuf::from),
1445 Some(sess.target.linker_flavor),
1446 features,
1447 ) {
1448 return ret;
1449 }
1450
1451 bug!("Not enough information provided to determine how to invoke the linker");
1452}
1453
1454fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1458 if sess.opts.debuginfo == config::DebugInfo::None {
1460 return (false, false);
1461 }
1462
1463 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1464 (SplitDebuginfo::Off, _) => (false, false),
1466 (SplitDebuginfo::Packed, _) => (false, false),
1469 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1472 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1476 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1477 }
1478}
1479
1480#[derive(PartialEq)]
1481enum RlibFlavor {
1482 Normal,
1483 StaticlibBase,
1484}
1485
1486fn print_native_static_libs(
1487 sess: &Session,
1488 out: &OutFileName,
1489 all_native_libs: &[NativeLib],
1490 all_rust_dylibs: &[&Path],
1491) {
1492 let mut lib_args: Vec<_> = all_native_libs
1493 .iter()
1494 .filter(|l| relevant_lib(sess, l))
1495 .filter_map(|lib| {
1496 let name = lib.name;
1497 match lib.kind {
1498 NativeLibKind::Static { bundle: Some(false), .. }
1499 | NativeLibKind::Dylib { .. }
1500 | NativeLibKind::Unspecified => {
1501 let verbatim = lib.verbatim;
1502 if sess.target.is_like_msvc {
1503 let (prefix, suffix) = sess.staticlib_components(verbatim);
1504 Some(format!("{prefix}{name}{suffix}"))
1505 } else if sess.target.linker_flavor.is_gnu() {
1506 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1507 } else {
1508 Some(format!("-l{name}"))
1509 }
1510 }
1511 NativeLibKind::Framework { .. } => {
1512 Some(format!("-framework {name}"))
1514 }
1515 NativeLibKind::Static { bundle: None | Some(true), .. }
1517 | NativeLibKind::LinkArg
1518 | NativeLibKind::WasmImportModule
1519 | NativeLibKind::RawDylib => None,
1520 }
1521 })
1522 .dedup()
1524 .collect();
1525 for path in all_rust_dylibs {
1526 let parent = path.parent();
1531 if let Some(dir) = parent {
1532 let dir = fix_windows_verbatim_for_gcc(dir);
1533 if sess.target.is_like_msvc {
1534 let mut arg = String::from("/LIBPATH:");
1535 arg.push_str(&dir.display().to_string());
1536 lib_args.push(arg);
1537 } else {
1538 lib_args.push("-L".to_owned());
1539 lib_args.push(dir.display().to_string());
1540 }
1541 }
1542 let stem = path.file_stem().unwrap().to_str().unwrap();
1543 let lib = if let Some(lib) = stem.strip_prefix("lib")
1545 && !sess.target.is_like_windows
1546 {
1547 lib
1548 } else {
1549 stem
1550 };
1551 let path = parent.unwrap_or_else(|| Path::new(""));
1552 if sess.target.is_like_msvc {
1553 let name = format!("{lib}.dll.lib");
1558 if path.join(&name).exists() {
1559 lib_args.push(name);
1560 }
1561 } else {
1562 lib_args.push(format!("-l{lib}"));
1563 }
1564 }
1565
1566 match out {
1567 OutFileName::Real(path) => {
1568 out.overwrite(&lib_args.join(" "), sess);
1569 sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1570 }
1571 OutFileName::Stdout => {
1572 sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1573 sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
1576 }
1577 }
1578}
1579
1580fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1581 let file_path = sess.target_tlib_path.dir.join(name);
1582 if file_path.exists() {
1583 return file_path;
1584 }
1585 if self_contained {
1587 let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1588 if file_path.exists() {
1589 return file_path;
1590 }
1591 }
1592 for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1593 let file_path = search_path.dir.join(name);
1594 if file_path.exists() {
1595 return file_path;
1596 }
1597 }
1598 PathBuf::from(name)
1599}
1600
1601fn exec_linker(
1602 sess: &Session,
1603 cmd: &Command,
1604 out_filename: &Path,
1605 flavor: LinkerFlavor,
1606 tmpdir: &Path,
1607) -> io::Result<Output> {
1608 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1618 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1619 Ok(child) => {
1620 let output = child.wait_with_output();
1621 flush_linked_file(&output, out_filename)?;
1622 return output;
1623 }
1624 Err(ref e) if command_line_too_big(e) => {
1625 info!("command line to linker was too big: {}", e);
1626 }
1627 Err(e) => return Err(e),
1628 }
1629 }
1630
1631 info!("falling back to passing arguments to linker via an @-file");
1632 let mut cmd2 = cmd.clone();
1633 let mut args = String::new();
1634 for arg in cmd2.take_args() {
1635 args.push_str(
1636 &Escape {
1637 arg: arg.to_str().unwrap(),
1638 is_like_msvc: sess.target.is_like_msvc
1643 || (cfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1644 }
1645 .to_string(),
1646 );
1647 args.push('\n');
1648 }
1649 let file = tmpdir.join("linker-arguments");
1650 let bytes = if sess.target.is_like_msvc {
1651 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1652 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1654 out.push(c as u8);
1656 out.push((c >> 8) as u8);
1657 }
1658 out
1659 } else {
1660 args.into_bytes()
1661 };
1662 fs::write(&file, &bytes)?;
1663 cmd2.arg(format!("@{}", file.display()));
1664 info!("invoking linker {:?}", cmd2);
1665 let output = cmd2.output();
1666 flush_linked_file(&output, out_filename)?;
1667 return output;
1668
1669 #[cfg(not(windows))]
1670 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1671 Ok(())
1672 }
1673
1674 #[cfg(windows)]
1675 fn flush_linked_file(
1676 command_output: &io::Result<Output>,
1677 out_filename: &Path,
1678 ) -> io::Result<()> {
1679 if let &Ok(ref out) = command_output {
1688 if out.status.success() {
1689 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1690 of.sync_all()?;
1691 }
1692 }
1693 }
1694
1695 Ok(())
1696 }
1697
1698 #[cfg(unix)]
1699 fn command_line_too_big(err: &io::Error) -> bool {
1700 err.raw_os_error() == Some(::libc::E2BIG)
1701 }
1702
1703 #[cfg(windows)]
1704 fn command_line_too_big(err: &io::Error) -> bool {
1705 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1706 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1707 }
1708
1709 #[cfg(not(any(unix, windows)))]
1710 fn command_line_too_big(_: &io::Error) -> bool {
1711 false
1712 }
1713
1714 struct Escape<'a> {
1715 arg: &'a str,
1716 is_like_msvc: bool,
1717 }
1718
1719 impl<'a> fmt::Display for Escape<'a> {
1720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1721 if self.is_like_msvc {
1722 write!(f, "\"")?;
1730 for c in self.arg.chars() {
1731 match c {
1732 '"' => write!(f, "\\{c}")?,
1733 c => write!(f, "{c}")?,
1734 }
1735 }
1736 write!(f, "\"")?;
1737 } else {
1738 for c in self.arg.chars() {
1749 match c {
1750 '\\' | ' ' => write!(f, "\\{c}")?,
1751 c => write!(f, "{c}")?,
1752 }
1753 }
1754 }
1755 Ok(())
1756 }
1757 }
1758}
1759
1760fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1761 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1762 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1763 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1764 LinkOutputKind::DynamicPicExe
1765 }
1766 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1767 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1768 LinkOutputKind::StaticPicExe
1769 }
1770 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1771 (_, true, _) => LinkOutputKind::StaticDylib,
1772 (_, false, _) => LinkOutputKind::DynamicDylib,
1773 };
1774
1775 let opts = &sess.target;
1777 let pic_exe_supported = opts.position_independent_executables;
1778 let static_pic_exe_supported = opts.static_position_independent_executables;
1779 let static_dylib_supported = opts.crt_static_allows_dylibs;
1780 match kind {
1781 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1782 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1783 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1784 _ => kind,
1785 }
1786}
1787
1788fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1790 if linker == Path::new("rust-lld") {
1792 return true;
1793 }
1794 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1795 linker.with_extension("exe")
1796 } else {
1797 linker.to_path_buf()
1798 };
1799 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1800 let full_path = dir.join(&linker_with_extension);
1801 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1803 return false;
1804 }
1805 }
1806 true
1807}
1808
1809fn self_contained_components(
1813 sess: &Session,
1814 crate_type: CrateType,
1815 linker: &Path,
1816) -> LinkSelfContainedComponents {
1817 let self_contained =
1820 if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1821 if sess.target.link_self_contained.is_disabled() {
1824 sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1825 }
1826 self_contained
1827 } else {
1828 match sess.target.link_self_contained {
1829 LinkSelfContainedDefault::False => false,
1830 LinkSelfContainedDefault::True => true,
1831
1832 LinkSelfContainedDefault::WithComponents(components) => {
1833 return components;
1836 }
1837
1838 LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1842 LinkSelfContainedDefault::InferredForMingw => {
1843 sess.host == sess.target
1844 && sess.target.vendor != "uwp"
1845 && detect_self_contained_mingw(sess, linker)
1846 }
1847 }
1848 };
1849 if self_contained {
1850 LinkSelfContainedComponents::all()
1851 } else {
1852 LinkSelfContainedComponents::empty()
1853 }
1854}
1855
1856fn add_pre_link_objects(
1858 cmd: &mut dyn Linker,
1859 sess: &Session,
1860 flavor: LinkerFlavor,
1861 link_output_kind: LinkOutputKind,
1862 self_contained: bool,
1863) {
1864 let opts = &sess.target;
1867 let empty = Default::default();
1868 let objects = if self_contained {
1869 &opts.pre_link_objects_self_contained
1870 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1871 &opts.pre_link_objects
1872 } else {
1873 &empty
1874 };
1875 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1876 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1877 }
1878}
1879
1880fn add_post_link_objects(
1882 cmd: &mut dyn Linker,
1883 sess: &Session,
1884 link_output_kind: LinkOutputKind,
1885 self_contained: bool,
1886) {
1887 let objects = if self_contained {
1888 &sess.target.post_link_objects_self_contained
1889 } else {
1890 &sess.target.post_link_objects
1891 };
1892 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1893 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1894 }
1895}
1896
1897fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1900 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1901 cmd.verbatim_args(args.iter().map(Deref::deref));
1902 }
1903
1904 cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1905}
1906
1907fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1909 match (crate_type, &sess.target.link_script) {
1910 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1911 if !sess.target.linker_flavor.is_gnu() {
1912 sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1913 }
1914
1915 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1916
1917 let path = tmpdir.join(file_name);
1918 if let Err(error) = fs::write(&path, script.as_ref()) {
1919 sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1920 }
1921
1922 cmd.link_arg("--script").link_arg(path);
1923 }
1924 _ => {}
1925 }
1926}
1927
1928fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1931 cmd.verbatim_args(&sess.opts.cg.link_args);
1932}
1933
1934fn add_late_link_args(
1937 cmd: &mut dyn Linker,
1938 sess: &Session,
1939 flavor: LinkerFlavor,
1940 crate_type: CrateType,
1941 codegen_results: &CodegenResults,
1942) {
1943 let any_dynamic_crate = crate_type == CrateType::Dylib
1944 || crate_type == CrateType::Sdylib
1945 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1946 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1947 });
1948 if any_dynamic_crate {
1949 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1950 cmd.verbatim_args(args.iter().map(Deref::deref));
1951 }
1952 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1953 cmd.verbatim_args(args.iter().map(Deref::deref));
1954 }
1955 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1956 cmd.verbatim_args(args.iter().map(Deref::deref));
1957 }
1958}
1959
1960fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1963 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1964 cmd.verbatim_args(args.iter().map(Deref::deref));
1965 }
1966}
1967
1968fn add_linked_symbol_object(
1998 cmd: &mut dyn Linker,
1999 sess: &Session,
2000 tmpdir: &Path,
2001 symbols: &[(String, SymbolExportKind)],
2002) {
2003 if symbols.is_empty() {
2004 return;
2005 }
2006
2007 let Some(mut file) = super::metadata::create_object_file(sess) else {
2008 return;
2009 };
2010
2011 if file.format() == object::BinaryFormat::Coff {
2012 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
2015
2016 file.set_mangling(object::write::Mangling::None);
2019 }
2020
2021 if file.format() == object::BinaryFormat::MachO {
2022 file.set_subsections_via_symbols();
2025 }
2026
2027 let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2030 Some(file.add_section(
2031 file.segment_name(object::write::StandardSegment::Data).to_vec(),
2032 "__data".into(),
2033 object::SectionKind::Data,
2034 ))
2035 } else {
2036 None
2037 };
2038
2039 for (sym, kind) in symbols.iter() {
2040 let symbol = file.add_symbol(object::write::Symbol {
2041 name: sym.clone().into(),
2042 value: 0,
2043 size: 0,
2044 kind: match kind {
2045 SymbolExportKind::Text => object::SymbolKind::Text,
2046 SymbolExportKind::Data => object::SymbolKind::Data,
2047 SymbolExportKind::Tls => object::SymbolKind::Tls,
2048 },
2049 scope: object::SymbolScope::Unknown,
2050 weak: false,
2051 section: object::write::SymbolSection::Undefined,
2052 flags: object::SymbolFlags::None,
2053 });
2054
2055 if let Some(section) = ld64_section_helper {
2092 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2093 .expect("failed adding relocation");
2094 }
2095 }
2096
2097 let path = tmpdir.join("symbols.o");
2098 let result = std::fs::write(&path, file.write().unwrap());
2099 if let Err(error) = result {
2100 sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2101 }
2102 cmd.add_object(&path);
2103}
2104
2105fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2107 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2108 cmd.add_object(obj);
2109 }
2110}
2111
2112fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2114 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
2115 cmd.add_object(obj);
2116 }
2117}
2118
2119fn add_local_crate_metadata_objects(
2121 cmd: &mut dyn Linker,
2122 crate_type: CrateType,
2123 codegen_results: &CodegenResults,
2124) {
2125 if matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro)
2129 && let Some(m) = &codegen_results.metadata_module
2130 && let Some(obj) = &m.object
2131 {
2132 cmd.add_object(obj);
2133 }
2134}
2135
2136fn add_library_search_dirs(
2138 cmd: &mut dyn Linker,
2139 sess: &Session,
2140 self_contained_components: LinkSelfContainedComponents,
2141 apple_sdk_root: Option<&Path>,
2142) {
2143 if !sess.opts.unstable_opts.link_native_libraries {
2144 return;
2145 }
2146
2147 let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2148 let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2149 if is_framework {
2150 cmd.framework_path(dir);
2151 } else {
2152 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2153 }
2154 ControlFlow::<()>::Continue(())
2155 });
2156}
2157
2158fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2161 match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2162 RelroLevel::Full => cmd.full_relro(),
2163 RelroLevel::Partial => cmd.partial_relro(),
2164 RelroLevel::Off => cmd.no_relro(),
2165 RelroLevel::None => {}
2166 }
2167}
2168
2169fn add_rpath_args(
2171 cmd: &mut dyn Linker,
2172 sess: &Session,
2173 codegen_results: &CodegenResults,
2174 out_filename: &Path,
2175) {
2176 if !sess.target.has_rpath {
2177 return;
2178 }
2179
2180 if sess.opts.cg.rpath {
2184 let libs = codegen_results
2185 .crate_info
2186 .used_crates
2187 .iter()
2188 .filter_map(|cnum| {
2189 codegen_results.crate_info.used_crate_source[cnum]
2190 .dylib
2191 .as_ref()
2192 .map(|(path, _)| &**path)
2193 })
2194 .collect::<Vec<_>>();
2195 let rpath_config = RPathConfig {
2196 libs: &*libs,
2197 out_filename: out_filename.to_path_buf(),
2198 is_like_darwin: sess.target.is_like_darwin,
2199 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2200 };
2201 cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2202 }
2203}
2204
2205fn linker_with_args(
2214 path: &Path,
2215 flavor: LinkerFlavor,
2216 sess: &Session,
2217 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2218 crate_type: CrateType,
2219 tmpdir: &Path,
2220 out_filename: &Path,
2221 codegen_results: &CodegenResults,
2222 self_contained_components: LinkSelfContainedComponents,
2223) -> Command {
2224 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2225 let cmd = &mut *super::linker::get_linker(
2226 sess,
2227 path,
2228 flavor,
2229 self_contained_components.are_any_components_enabled(),
2230 &codegen_results.crate_info.target_cpu,
2231 );
2232 let link_output_kind = link_output_kind(sess, crate_type);
2233
2234 cmd.export_symbols(
2242 tmpdir,
2243 crate_type,
2244 &codegen_results.crate_info.exported_symbols[&crate_type],
2245 );
2246
2247 add_pre_link_args(cmd, sess, flavor);
2252
2253 add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
2257
2258 add_linked_symbol_object(
2259 cmd,
2260 sess,
2261 tmpdir,
2262 &codegen_results.crate_info.linked_symbols[&crate_type],
2263 );
2264
2265 add_sanitizer_libraries(sess, flavor, crate_type, cmd);
2267
2268 add_local_crate_regular_objects(cmd, codegen_results);
2296 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
2297 add_local_crate_allocator_objects(cmd, codegen_results);
2298
2299 cmd.add_as_needed();
2308
2309 add_local_native_libraries(
2311 cmd,
2312 sess,
2313 archive_builder_builder,
2314 codegen_results,
2315 tmpdir,
2316 link_output_kind,
2317 );
2318
2319 add_upstream_rust_crates(
2321 cmd,
2322 sess,
2323 archive_builder_builder,
2324 codegen_results,
2325 crate_type,
2326 tmpdir,
2327 link_output_kind,
2328 );
2329
2330 add_upstream_native_libraries(
2332 cmd,
2333 sess,
2334 archive_builder_builder,
2335 codegen_results,
2336 tmpdir,
2337 link_output_kind,
2338 );
2339
2340 let raw_dylib_dir = tmpdir.join("raw-dylibs");
2342 if sess.target.binary_format == BinaryFormat::Elf {
2343 if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2348 sess.dcx().emit_fatal(errors::CreateTempDir { error })
2349 }
2350 cmd.include_path(&raw_dylib_dir);
2351 }
2352
2353 if sess.target.is_like_windows {
2355 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2356 sess,
2357 archive_builder_builder,
2358 codegen_results.crate_info.used_libraries.iter(),
2359 tmpdir,
2360 true,
2361 ) {
2362 cmd.add_object(&output_path);
2363 }
2364 } else {
2365 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2366 sess,
2367 codegen_results.crate_info.used_libraries.iter(),
2368 &raw_dylib_dir,
2369 ) {
2370 cmd.link_dylib_by_name(&link_path, true, false);
2372 }
2373 }
2374 let dependency_linkage = codegen_results
2379 .crate_info
2380 .dependency_formats
2381 .get(&crate_type)
2382 .expect("failed to find crate type in dependency format list");
2383
2384 #[allow(rustc::potential_query_instability)]
2386 let mut native_libraries_from_nonstatics = codegen_results
2387 .crate_info
2388 .native_libraries
2389 .iter()
2390 .filter_map(|(&cnum, libraries)| {
2391 if sess.target.is_like_windows {
2392 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2393 } else {
2394 Some(libraries)
2395 }
2396 })
2397 .flatten()
2398 .collect::<Vec<_>>();
2399 native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
2400
2401 if sess.target.is_like_windows {
2402 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2403 sess,
2404 archive_builder_builder,
2405 native_libraries_from_nonstatics,
2406 tmpdir,
2407 false,
2408 ) {
2409 cmd.add_object(&output_path);
2410 }
2411 } else {
2412 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2413 sess,
2414 native_libraries_from_nonstatics,
2415 &raw_dylib_dir,
2416 ) {
2417 cmd.link_dylib_by_name(&link_path, true, false);
2419 }
2420 }
2421
2422 cmd.reset_per_library_state();
2425
2426 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2430
2431 add_order_independent_options(
2436 cmd,
2437 sess,
2438 link_output_kind,
2439 self_contained_components,
2440 flavor,
2441 crate_type,
2442 codegen_results,
2443 out_filename,
2444 tmpdir,
2445 );
2446
2447 add_user_defined_link_args(cmd, sess);
2451
2452 add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
2456
2457 add_post_link_args(cmd, sess, flavor);
2464
2465 cmd.take_cmd()
2466}
2467
2468fn add_order_independent_options(
2469 cmd: &mut dyn Linker,
2470 sess: &Session,
2471 link_output_kind: LinkOutputKind,
2472 self_contained_components: LinkSelfContainedComponents,
2473 flavor: LinkerFlavor,
2474 crate_type: CrateType,
2475 codegen_results: &CodegenResults,
2476 out_filename: &Path,
2477 tmpdir: &Path,
2478) {
2479 add_lld_args(cmd, sess, flavor, self_contained_components);
2481
2482 add_apple_link_args(cmd, sess, flavor);
2483
2484 let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
2485
2486 add_link_script(cmd, sess, tmpdir, crate_type);
2487
2488 if sess.target.os == "fuchsia"
2489 && crate_type == CrateType::Executable
2490 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2491 {
2492 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2493 "asan/"
2494 } else {
2495 ""
2496 };
2497 cmd.link_arg(format!("--dynamic-linker={prefix}ld.so.1"));
2498 }
2499
2500 if sess.target.eh_frame_header {
2501 cmd.add_eh_frame_header();
2502 }
2503
2504 cmd.add_no_exec();
2506
2507 if self_contained_components.is_crt_objects_enabled() {
2508 cmd.no_crt_objects();
2509 }
2510
2511 if sess.target.os == "emscripten" {
2512 cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2513 "-fwasm-exceptions"
2514 } else if sess.panic_strategy() == PanicStrategy::Abort {
2515 "-sDISABLE_EXCEPTION_CATCHING=1"
2516 } else {
2517 "-sDISABLE_EXCEPTION_CATCHING=0"
2518 });
2519 }
2520
2521 if flavor == LinkerFlavor::Llbc {
2522 cmd.link_args(&[
2523 "--target",
2524 &versioned_llvm_target(sess),
2525 "--target-cpu",
2526 &codegen_results.crate_info.target_cpu,
2527 ]);
2528 if codegen_results.crate_info.target_features.len() > 0 {
2529 cmd.link_arg(&format!(
2530 "--target-feature={}",
2531 &codegen_results.crate_info.target_features.join(",")
2532 ));
2533 }
2534 } else if flavor == LinkerFlavor::Ptx {
2535 cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2536 } else if flavor == LinkerFlavor::Bpf {
2537 cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2538 if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2539 .into_iter()
2540 .find(|feat| !feat.is_empty())
2541 {
2542 cmd.link_args(&["--cpu-features", feat]);
2543 }
2544 }
2545
2546 cmd.linker_plugin_lto();
2547
2548 add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
2549
2550 cmd.output_filename(out_filename);
2551
2552 if crate_type == CrateType::Executable
2553 && sess.target.is_like_windows
2554 && let Some(s) = &codegen_results.crate_info.windows_subsystem
2555 {
2556 cmd.subsystem(s);
2557 }
2558
2559 if !sess.link_dead_code() {
2562 let keep_metadata =
2567 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2568 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2569 {
2570 cmd.gc_sections(keep_metadata);
2571 } else {
2572 cmd.no_gc_sections();
2573 }
2574 }
2575
2576 cmd.set_output_kind(link_output_kind, crate_type, out_filename);
2577
2578 add_relro_args(cmd, sess);
2579
2580 cmd.optimize();
2582
2583 let natvis_visualizers = collect_natvis_visualizers(
2585 tmpdir,
2586 sess,
2587 &codegen_results.crate_info.local_crate_name,
2588 &codegen_results.crate_info.natvis_debugger_visualizers,
2589 );
2590
2591 cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
2593
2594 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2597 cmd.no_default_libraries();
2598 }
2599
2600 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2601 cmd.pgo_gen();
2602 }
2603
2604 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2605 cmd.control_flow_guard();
2606 }
2607
2608 if sess.opts.unstable_opts.ehcont_guard {
2610 cmd.ehcont_guard();
2611 }
2612
2613 add_rpath_args(cmd, sess, codegen_results, out_filename);
2614}
2615
2616fn collect_natvis_visualizers(
2618 tmpdir: &Path,
2619 sess: &Session,
2620 crate_name: &Symbol,
2621 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2622) -> Vec<PathBuf> {
2623 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2624
2625 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2626 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2627
2628 match fs::write(&visualizer_out_file, &visualizer.src) {
2629 Ok(()) => {
2630 visualizer_paths.push(visualizer_out_file);
2631 }
2632 Err(error) => {
2633 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2634 path: visualizer_out_file,
2635 error,
2636 });
2637 }
2638 };
2639 }
2640 visualizer_paths
2641}
2642
2643fn add_native_libs_from_crate(
2644 cmd: &mut dyn Linker,
2645 sess: &Session,
2646 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2647 codegen_results: &CodegenResults,
2648 tmpdir: &Path,
2649 bundled_libs: &FxIndexSet<Symbol>,
2650 cnum: CrateNum,
2651 link_static: bool,
2652 link_dynamic: bool,
2653 link_output_kind: LinkOutputKind,
2654) {
2655 if !sess.opts.unstable_opts.link_native_libraries {
2656 return;
2660 }
2661
2662 if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2663 let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2665 archive_builder_builder
2666 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2667 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2668 }
2669
2670 let native_libs = match cnum {
2671 LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2672 _ => &codegen_results.crate_info.native_libraries[&cnum],
2673 };
2674
2675 let mut last = (None, NativeLibKind::Unspecified, false);
2676 for lib in native_libs {
2677 if !relevant_lib(sess, lib) {
2678 continue;
2679 }
2680
2681 last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2683 continue;
2684 } else {
2685 (Some(lib.name), lib.kind, lib.verbatim)
2686 };
2687
2688 let name = lib.name.as_str();
2689 let verbatim = lib.verbatim;
2690 match lib.kind {
2691 NativeLibKind::Static { bundle, whole_archive } => {
2692 if link_static {
2693 let bundle = bundle.unwrap_or(true);
2694 let whole_archive = whole_archive == Some(true);
2695 if bundle && cnum != LOCAL_CRATE {
2696 if let Some(filename) = lib.filename {
2697 let path = tmpdir.join(filename.as_str());
2699 cmd.link_staticlib_by_path(&path, whole_archive);
2700 }
2701 } else {
2702 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2703 }
2704 }
2705 }
2706 NativeLibKind::Dylib { as_needed } => {
2707 if link_dynamic {
2708 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2709 }
2710 }
2711 NativeLibKind::Unspecified => {
2712 if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2715 if link_static {
2716 cmd.link_staticlib_by_name(name, verbatim, false);
2717 }
2718 } else if link_dynamic {
2719 cmd.link_dylib_by_name(name, verbatim, true);
2720 }
2721 }
2722 NativeLibKind::Framework { as_needed } => {
2723 if link_dynamic {
2724 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2725 }
2726 }
2727 NativeLibKind::RawDylib => {
2728 }
2730 NativeLibKind::WasmImportModule => {}
2731 NativeLibKind::LinkArg => {
2732 if link_static {
2733 if verbatim {
2734 cmd.verbatim_arg(name);
2735 } else {
2736 cmd.link_arg(name);
2737 }
2738 }
2739 }
2740 }
2741 }
2742}
2743
2744fn add_local_native_libraries(
2745 cmd: &mut dyn Linker,
2746 sess: &Session,
2747 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2748 codegen_results: &CodegenResults,
2749 tmpdir: &Path,
2750 link_output_kind: LinkOutputKind,
2751) {
2752 let link_static = true;
2754 let link_dynamic = true;
2755 add_native_libs_from_crate(
2756 cmd,
2757 sess,
2758 archive_builder_builder,
2759 codegen_results,
2760 tmpdir,
2761 &Default::default(),
2762 LOCAL_CRATE,
2763 link_static,
2764 link_dynamic,
2765 link_output_kind,
2766 );
2767}
2768
2769fn add_upstream_rust_crates(
2770 cmd: &mut dyn Linker,
2771 sess: &Session,
2772 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2773 codegen_results: &CodegenResults,
2774 crate_type: CrateType,
2775 tmpdir: &Path,
2776 link_output_kind: LinkOutputKind,
2777) {
2778 let data = codegen_results
2786 .crate_info
2787 .dependency_formats
2788 .get(&crate_type)
2789 .expect("failed to find crate type in dependency format list");
2790
2791 if sess.target.is_like_aix {
2792 cmd.link_or_cc_arg("-bnoipath");
2798 }
2799
2800 for &cnum in &codegen_results.crate_info.used_crates {
2801 let linkage = data[cnum];
2809 let link_static_crate = linkage == Linkage::Static
2810 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2811 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2812 || codegen_results.crate_info.profiler_runtime == Some(cnum));
2813
2814 let mut bundled_libs = Default::default();
2815 match linkage {
2816 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2817 if link_static_crate {
2818 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2819 .iter()
2820 .filter_map(|lib| lib.filename)
2821 .collect();
2822 add_static_crate(
2823 cmd,
2824 sess,
2825 archive_builder_builder,
2826 codegen_results,
2827 tmpdir,
2828 cnum,
2829 &bundled_libs,
2830 );
2831 }
2832 }
2833 Linkage::Dynamic => {
2834 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2835 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2836 }
2837 }
2838
2839 let link_static = link_static_crate;
2848 let link_dynamic = false;
2850 add_native_libs_from_crate(
2851 cmd,
2852 sess,
2853 archive_builder_builder,
2854 codegen_results,
2855 tmpdir,
2856 &bundled_libs,
2857 cnum,
2858 link_static,
2859 link_dynamic,
2860 link_output_kind,
2861 );
2862 }
2863}
2864
2865fn add_upstream_native_libraries(
2866 cmd: &mut dyn Linker,
2867 sess: &Session,
2868 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2869 codegen_results: &CodegenResults,
2870 tmpdir: &Path,
2871 link_output_kind: LinkOutputKind,
2872) {
2873 for &cnum in &codegen_results.crate_info.used_crates {
2874 let link_static = false;
2880 let link_dynamic = true;
2888 add_native_libs_from_crate(
2889 cmd,
2890 sess,
2891 archive_builder_builder,
2892 codegen_results,
2893 tmpdir,
2894 &Default::default(),
2895 cnum,
2896 link_static,
2897 link_dynamic,
2898 link_output_kind,
2899 );
2900 }
2901}
2902
2903fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2913 let sysroot_lib_path = &sess.target_tlib_path.dir;
2914 let canonical_sysroot_lib_path =
2915 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2916
2917 let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2918 if canonical_lib_dir == canonical_sysroot_lib_path {
2919 sysroot_lib_path.clone()
2921 } else {
2922 fix_windows_verbatim_for_gcc(lib_dir)
2923 }
2924}
2925
2926fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2927 if let Some(dir) = path.parent() {
2928 let file_name = path.file_name().expect("library path has no file name component");
2929 rehome_sysroot_lib_dir(sess, dir).join(file_name)
2930 } else {
2931 fix_windows_verbatim_for_gcc(path)
2932 }
2933}
2934
2935fn add_static_crate(
2954 cmd: &mut dyn Linker,
2955 sess: &Session,
2956 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2957 codegen_results: &CodegenResults,
2958 tmpdir: &Path,
2959 cnum: CrateNum,
2960 bundled_lib_file_names: &FxIndexSet<Symbol>,
2961) {
2962 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2963 let cratepath = &src.rlib.as_ref().unwrap().0;
2964
2965 let mut link_upstream =
2966 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
2967
2968 if !are_upstream_rust_objects_already_included(sess)
2969 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2970 {
2971 link_upstream(cratepath);
2972 return;
2973 }
2974
2975 let dst = tmpdir.join(cratepath.file_name().unwrap());
2976 let name = cratepath.file_name().unwrap().to_str().unwrap();
2977 let name = &name[3..name.len() - 5]; let bundled_lib_file_names = bundled_lib_file_names.clone();
2979
2980 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2981 let canonical_name = name.replace('-', "_");
2982 let upstream_rust_objects_already_included =
2983 are_upstream_rust_objects_already_included(sess);
2984 let is_builtins =
2985 sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2986
2987 let mut archive = archive_builder_builder.new_archive_builder(sess);
2988 if let Err(error) = archive.add_archive(
2989 cratepath,
2990 Box::new(move |f| {
2991 if f == METADATA_FILENAME {
2992 return true;
2993 }
2994
2995 let canonical = f.replace('-', "_");
2996
2997 let is_rust_object =
2998 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
2999
3000 if upstream_rust_objects_already_included && is_rust_object && is_builtins {
3005 return true;
3006 }
3007
3008 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3014 return true;
3015 }
3016
3017 false
3018 }),
3019 ) {
3020 sess.dcx()
3021 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3022 }
3023 if archive.build(&dst) {
3024 link_upstream(&dst);
3025 }
3026 });
3027}
3028
3029fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3031 cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3032}
3033
3034fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3035 match lib.cfg {
3036 Some(ref cfg) => rustc_attr_parsing::cfg_matches(cfg, sess, CRATE_NODE_ID, None),
3037 None => true,
3038 }
3039}
3040
3041pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3042 match sess.lto() {
3043 config::Lto::Fat => true,
3044 config::Lto::Thin => {
3045 !sess.opts.cg.linker_plugin_lto.enabled()
3048 }
3049 config::Lto::No | config::Lto::ThinLocal => false,
3050 }
3051}
3052
3053fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3060 if !sess.target.is_like_darwin {
3061 return;
3062 }
3063 let LinkerFlavor::Darwin(cc, _) = flavor else {
3064 return;
3065 };
3066
3067 let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3069 let target_os = &*sess.target.os;
3070 let target_abi = &*sess.target.abi;
3071
3072 let ld64_arch = match llvm_arch {
3080 "armv7k" => "armv7k",
3081 "armv7s" => "armv7s",
3082 "arm64" => "arm64",
3083 "arm64e" => "arm64e",
3084 "arm64_32" => "arm64_32",
3085 "i386" | "i686" => "i386",
3089 "x86_64" => "x86_64",
3090 "x86_64h" => "x86_64h",
3091 _ => bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3092 };
3093
3094 if cc == Cc::No {
3095 cmd.link_args(&["-arch", ld64_arch]);
3105
3106 let platform_name = match (target_os, target_abi) {
3122 (os, "") => os,
3123 ("ios", "macabi") => "mac-catalyst",
3124 ("ios", "sim") => "ios-simulator",
3125 ("tvos", "sim") => "tvos-simulator",
3126 ("watchos", "sim") => "watchos-simulator",
3127 ("visionos", "sim") => "visionos-simulator",
3128 _ => bug!("invalid OS/ABI combination for Apple target: {target_os}, {target_abi}"),
3129 };
3130
3131 let min_version = sess.apple_deployment_target().fmt_full().to_string();
3132
3133 let sdk_version = &*min_version;
3166
3167 cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3176 } else {
3177 if target_os == "macos" {
3192 cmd.cc_args(&["-arch", ld64_arch]);
3197
3198 let version = sess.apple_deployment_target().fmt_full();
3201 cmd.cc_arg(&format!("-mmacosx-version-min={version}"));
3204
3205 } else {
3210 cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3211 }
3212 }
3213}
3214
3215fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3216 let os = &sess.target.os;
3217 if sess.target.vendor != "apple"
3218 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "visionos" | "macos")
3219 || !matches!(flavor, LinkerFlavor::Darwin(..))
3220 {
3221 return None;
3222 }
3223
3224 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
3225 return None;
3226 }
3227
3228 let sdk_root = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
3229
3230 match flavor {
3231 LinkerFlavor::Darwin(Cc::Yes, _) => {
3232 cmd.cc_arg("-isysroot");
3239 cmd.cc_arg(&sdk_root);
3240 }
3241 LinkerFlavor::Darwin(Cc::No, _) => {
3242 cmd.link_arg("-syslibroot");
3243 cmd.link_arg(&sdk_root);
3244 }
3245 _ => unreachable!(),
3246 }
3247
3248 Some(sdk_root)
3249}
3250
3251fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3252 if let Ok(sdkroot) = env::var("SDKROOT") {
3253 let p = PathBuf::from(&sdkroot);
3254
3255 match &*apple::sdk_name(&sess.target).to_lowercase() {
3264 "appletvos"
3265 if sdkroot.contains("TVSimulator.platform")
3266 || sdkroot.contains("MacOSX.platform") => {}
3267 "appletvsimulator"
3268 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3269 "iphoneos"
3270 if sdkroot.contains("iPhoneSimulator.platform")
3271 || sdkroot.contains("MacOSX.platform") => {}
3272 "iphonesimulator"
3273 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3274 }
3275 "macosx"
3276 if sdkroot.contains("iPhoneOS.platform")
3277 || sdkroot.contains("iPhoneSimulator.platform") => {}
3278 "watchos"
3279 if sdkroot.contains("WatchSimulator.platform")
3280 || sdkroot.contains("MacOSX.platform") => {}
3281 "watchsimulator"
3282 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3283 "xros"
3284 if sdkroot.contains("XRSimulator.platform")
3285 || sdkroot.contains("MacOSX.platform") => {}
3286 "xrsimulator"
3287 if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3288 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3290 _ => return Some(p),
3291 }
3292 }
3293
3294 apple::get_sdk_root(sess)
3295}
3296
3297fn add_lld_args(
3302 cmd: &mut dyn Linker,
3303 sess: &Session,
3304 flavor: LinkerFlavor,
3305 self_contained_components: LinkSelfContainedComponents,
3306) {
3307 debug!(
3308 "add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3309 flavor, self_contained_components,
3310 );
3311
3312 if !(flavor.uses_cc() && flavor.uses_lld()) {
3315 return;
3316 }
3317
3318 let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3324 let self_contained_target = self_contained_components.is_linker_enabled();
3325
3326 let self_contained_linker = self_contained_cli || self_contained_target;
3327 if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3328 let mut linker_path_exists = false;
3329 for path in sess.get_tools_search_paths(false) {
3330 let linker_path = path.join("gcc-ld");
3331 linker_path_exists |= linker_path.exists();
3332 cmd.cc_arg({
3333 let mut arg = OsString::from("-B");
3334 arg.push(linker_path);
3335 arg
3336 });
3337 }
3338 if !linker_path_exists {
3339 sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3342 }
3343 }
3344
3345 if !sess.target.is_like_wasm {
3352 cmd.cc_arg("-fuse-ld=lld");
3353
3354 if sess.target.llvm_target == "x86_64-unknown-linux-gnu" {
3380 cmd.link_arg("-znostart-stop-gc");
3381 }
3382 }
3383
3384 if !flavor.is_gnu() {
3385 if sess.target.linker_flavor != sess.host.linker_flavor {
3405 cmd.cc_arg(format!("--target={}", versioned_llvm_target(sess)));
3406 }
3407 }
3408}