1mod raw_dylib;
2
3use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{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 EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
27 walk_native_lib_search_dirs,
28};
29use rustc_middle::bug;
30use rustc_middle::lint::lint_level;
31use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
32use rustc_middle::middle::dependency_format::Linkage;
33use rustc_middle::middle::exported_symbols::SymbolExportKind;
34use rustc_session::config::{
35 self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
36 OutputType, PrintKind, SplitDwarfKind, Strip,
37};
38use rustc_session::lint::builtin::LINKER_MESSAGES;
39use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
40use rustc_session::search_paths::PathKind;
41use rustc_session::utils::NativeLibKind;
42use rustc_session::{Session, filesearch};
45use rustc_span::Symbol;
46use rustc_target::spec::crt_objects::CrtObjects;
47use rustc_target::spec::{
48 BinaryFormat, Cc, LinkOutputKind, LinkSelfContainedComponents, LinkSelfContainedDefault,
49 LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy, RelocModel, RelroLevel,
50 SanitizerSet, SplitDebuginfo,
51};
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 metadata: EncodedMetadata,
79 outputs: &OutputFilenames,
80) {
81 let _timer = sess.timer("link_binary");
82 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
83 let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
84 for &crate_type in &codegen_results.crate_info.crate_types {
85 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
87 && !output_metadata
88 && crate_type == CrateType::Executable
89 {
90 continue;
91 }
92
93 if invalid_output_for_target(sess, crate_type) {
94 bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
95 }
96
97 sess.time("link_binary_check_files_are_writeable", || {
98 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
99 check_file_is_writeable(obj, sess);
100 }
101 });
102
103 if outputs.outputs.should_link() {
104 let tmpdir = TempDirBuilder::new()
105 .prefix("rustc")
106 .tempdir()
107 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
108 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
109 let output = out_filename(
110 sess,
111 crate_type,
112 outputs,
113 codegen_results.crate_info.local_crate_name,
114 );
115 let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
116 let out_filename = output.file_for_writing(
117 outputs,
118 OutputType::Exe,
119 &crate_name,
120 sess.invocation_temp.as_deref(),
121 );
122 match crate_type {
123 CrateType::Rlib => {
124 let _timer = sess.timer("link_rlib");
125 info!("preparing rlib to {:?}", out_filename);
126 link_rlib(
127 sess,
128 archive_builder_builder,
129 &codegen_results,
130 &metadata,
131 RlibFlavor::Normal,
132 &path,
133 )
134 .build(&out_filename);
135 }
136 CrateType::Staticlib => {
137 link_staticlib(
138 sess,
139 archive_builder_builder,
140 &codegen_results,
141 &metadata,
142 &out_filename,
143 &path,
144 );
145 }
146 _ => {
147 link_natively(
148 sess,
149 archive_builder_builder,
150 crate_type,
151 &out_filename,
152 &codegen_results,
153 &metadata,
154 path.as_ref(),
155 );
156 }
157 }
158 if sess.opts.json_artifact_notifications {
159 sess.dcx().emit_artifact_notification(&out_filename, "link");
160 }
161
162 if sess.prof.enabled()
163 && let Some(artifact_name) = out_filename.file_name()
164 {
165 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
167
168 sess.prof.artifact_size(
169 "linked_artifact",
170 artifact_name.to_string_lossy(),
171 file_size,
172 );
173 }
174
175 if sess.target.binary_format == BinaryFormat::Elf {
176 if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
177 info!(?err, "Error while checking if gold was the linker");
178 }
179 }
180
181 if output.is_stdout() {
182 if output.is_tty() {
183 sess.dcx().emit_err(errors::BinaryOutputToTty {
184 shorthand: OutputType::Exe.shorthand(),
185 });
186 } else if let Err(e) = copy_to_stdout(&out_filename) {
187 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
188 }
189 tempfiles_for_stdout_output.push(out_filename);
190 }
191 }
192 }
193
194 sess.time("link_binary_remove_temps", || {
196 if sess.opts.cg.save_temps {
198 return;
199 }
200
201 let maybe_remove_temps_from_module =
202 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
203 if !preserve_objects && let Some(ref obj) = module.object {
204 ensure_removed(sess.dcx(), obj);
205 }
206
207 if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
208 ensure_removed(sess.dcx(), dwo_obj);
209 }
210 };
211
212 let remove_temps_from_module =
213 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
214
215 if let Some(ref allocator_module) = codegen_results.allocator_module {
217 remove_temps_from_module(allocator_module);
218 }
219
220 for temp in tempfiles_for_stdout_output {
222 ensure_removed(sess.dcx(), &temp);
223 }
224
225 if !sess.opts.output_types.should_link() {
228 return;
229 }
230
231 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
233 debug!(?preserve_objects, ?preserve_dwarf_objects);
234
235 for module in &codegen_results.modules {
236 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
237 }
238 });
239}
240
241pub fn each_linked_rlib(
244 info: &CrateInfo,
245 crate_type: Option<CrateType>,
246 f: &mut dyn FnMut(CrateNum, &Path),
247) -> Result<(), errors::LinkRlibError> {
248 let fmts = if let Some(crate_type) = crate_type {
249 let Some(fmts) = info.dependency_formats.get(&crate_type) else {
250 return Err(errors::LinkRlibError::MissingFormat);
251 };
252
253 fmts
254 } else {
255 let mut dep_formats = info.dependency_formats.iter();
256 let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
257 if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
258 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
259 ty1: format!("{ty1:?}"),
260 ty2: format!("{ty2:?}"),
261 list1: format!("{list1:?}"),
262 list2: format!("{list2:?}"),
263 });
264 }
265 list1
266 };
267
268 let used_dep_crates = info.used_crates.iter();
269 for &cnum in used_dep_crates {
270 match fmts.get(cnum) {
271 Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
272 Some(_) => {}
273 None => return Err(errors::LinkRlibError::MissingFormat),
274 }
275 let crate_name = info.crate_name[&cnum];
276 let used_crate_source = &info.used_crate_source[&cnum];
277 if let Some((path, _)) = &used_crate_source.rlib {
278 f(cnum, path);
279 } else if used_crate_source.rmeta.is_some() {
280 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
281 } else {
282 return Err(errors::LinkRlibError::NotFound { crate_name });
283 }
284 }
285 Ok(())
286}
287
288fn link_rlib<'a>(
294 sess: &'a Session,
295 archive_builder_builder: &dyn ArchiveBuilderBuilder,
296 codegen_results: &CodegenResults,
297 metadata: &EncodedMetadata,
298 flavor: RlibFlavor,
299 tmpdir: &MaybeTempDir,
300) -> Box<dyn ArchiveBuilder + 'a> {
301 let mut ab = archive_builder_builder.new_archive_builder(sess);
302
303 let trailing_metadata = match flavor {
304 RlibFlavor::Normal => {
305 let (metadata, metadata_position) =
306 create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
307 let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
308 match metadata_position {
309 MetadataPosition::First => {
310 ab.add_file(&metadata);
316 None
317 }
318 MetadataPosition::Last => Some(metadata),
319 }
320 }
321
322 RlibFlavor::StaticlibBase => None,
323 };
324
325 for m in &codegen_results.modules {
326 if let Some(obj) = m.object.as_ref() {
327 ab.add_file(obj);
328 }
329
330 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
331 ab.add_file(dwarf_obj);
332 }
333 }
334
335 match flavor {
336 RlibFlavor::Normal => {}
337 RlibFlavor::StaticlibBase => {
338 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
339 if let Some(obj) = obj {
340 ab.add_file(obj);
341 }
342 }
343 }
344
345 let mut packed_bundled_libs = Vec::new();
347
348 for lib in codegen_results.crate_info.used_libraries.iter() {
365 let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
366 continue;
367 };
368 if flavor == RlibFlavor::Normal
369 && let Some(filename) = lib.filename
370 {
371 let path = find_native_static_library(filename.as_str(), true, sess);
372 let src = read(path)
373 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
374 let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
375 let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
376 packed_bundled_libs.push(wrapper_file);
377 } else {
378 let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
379 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
380 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
381 });
382 }
383 }
384
385 if sess.target.is_like_windows {
389 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
390 sess,
391 archive_builder_builder,
392 codegen_results.crate_info.used_libraries.iter(),
393 tmpdir.as_ref(),
394 true,
395 ) {
396 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
397 sess.dcx()
398 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
399 });
400 }
401 }
402
403 if let Some(trailing_metadata) = trailing_metadata {
404 ab.add_file(&trailing_metadata);
430 }
431
432 for lib in packed_bundled_libs {
435 ab.add_file(&lib)
436 }
437
438 ab
439}
440
441fn link_staticlib(
453 sess: &Session,
454 archive_builder_builder: &dyn ArchiveBuilderBuilder,
455 codegen_results: &CodegenResults,
456 metadata: &EncodedMetadata,
457 out_filename: &Path,
458 tempdir: &MaybeTempDir,
459) {
460 info!("preparing staticlib to {:?}", out_filename);
461 let mut ab = link_rlib(
462 sess,
463 archive_builder_builder,
464 codegen_results,
465 metadata,
466 RlibFlavor::StaticlibBase,
467 tempdir,
468 );
469 let mut all_native_libs = vec![];
470
471 let res = each_linked_rlib(
472 &codegen_results.crate_info,
473 Some(CrateType::Staticlib),
474 &mut |cnum, path| {
475 let lto = are_upstream_rust_objects_already_included(sess)
476 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
477
478 let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
479 let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
480 let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
481
482 let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
483 ab.add_archive(
484 path,
485 Box::new(move |fname: &str| {
486 if fname == METADATA_FILENAME {
488 return true;
489 }
490
491 if lto && looks_like_rust_object_file(fname) {
493 return true;
494 }
495
496 if bundled_libs.contains(&Symbol::intern(fname)) {
498 return true;
499 }
500
501 false
502 }),
503 )
504 .unwrap();
505
506 archive_builder_builder
507 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
508 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
509
510 for filename in relevant_libs.iter() {
511 let joined = tempdir.as_ref().join(filename.as_str());
512 let path = joined.as_path();
513 ab.add_archive(path, Box::new(|_| false)).unwrap();
514 }
515
516 all_native_libs
517 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
518 },
519 );
520 if let Err(e) = res {
521 sess.dcx().emit_fatal(e);
522 }
523
524 ab.build(out_filename);
525
526 let crates = codegen_results.crate_info.used_crates.iter();
527
528 let fmts = codegen_results
529 .crate_info
530 .dependency_formats
531 .get(&CrateType::Staticlib)
532 .expect("no dependency formats for staticlib");
533
534 let mut all_rust_dylibs = vec![];
535 for &cnum in crates {
536 let Some(Linkage::Dynamic) = fmts.get(cnum) else {
537 continue;
538 };
539 let crate_name = codegen_results.crate_info.crate_name[&cnum];
540 let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
541 if let Some((path, _)) = &used_crate_source.dylib {
542 all_rust_dylibs.push(&**path);
543 } else if used_crate_source.rmeta.is_some() {
544 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
545 } else {
546 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
547 }
548 }
549
550 all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
551
552 for print in &sess.opts.prints {
553 if print.kind == PrintKind::NativeStaticLibs {
554 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
555 }
556 }
557}
558
559fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
562 let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
563 dwp_out_filename.push(".dwp");
564 debug!(?dwp_out_filename, ?executable_out_filename);
565
566 #[derive(Default)]
567 struct ThorinSession<Relocations> {
568 arena_data: TypedArena<Vec<u8>>,
569 arena_mmap: TypedArena<Mmap>,
570 arena_relocations: TypedArena<Relocations>,
571 }
572
573 impl<Relocations> ThorinSession<Relocations> {
574 fn alloc_mmap(&self, data: Mmap) -> &Mmap {
575 &*self.arena_mmap.alloc(data)
576 }
577 }
578
579 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
580 fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
581 &*self.arena_data.alloc(data)
582 }
583
584 fn alloc_relocation(&self, data: Relocations) -> &Relocations {
585 &*self.arena_relocations.alloc(data)
586 }
587
588 fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
589 let file = File::open(&path)?;
590 let mmap = (unsafe { Mmap::map(file) })?;
591 Ok(self.alloc_mmap(mmap))
592 }
593 }
594
595 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
596 let thorin_sess = ThorinSession::default();
597 let mut package = thorin::DwarfPackage::new(&thorin_sess);
598
599 match sess.opts.unstable_opts.split_dwarf_kind {
601 SplitDwarfKind::Single => {
602 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
603 package.add_input_object(input_obj)?;
604 }
605 }
606 SplitDwarfKind::Split => {
607 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
608 package.add_input_object(input_obj)?;
609 }
610 }
611 }
612
613 let input_rlibs = cg_results
615 .crate_info
616 .used_crate_source
617 .items()
618 .filter_map(|(_, csource)| csource.rlib.as_ref())
619 .map(|(path, _)| path)
620 .into_sorted_stable_ord();
621
622 for input_rlib in input_rlibs {
623 debug!(?input_rlib);
624 package.add_input_object(input_rlib)?;
625 }
626
627 package.add_executable(
637 executable_out_filename,
638 thorin::MissingReferencedObjectBehaviour::Skip,
639 )?;
640
641 let output_stream = BufWriter::new(
642 OpenOptions::new()
643 .read(true)
644 .write(true)
645 .create(true)
646 .truncate(true)
647 .open(dwp_out_filename)?,
648 );
649 let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
650 package.finish()?.emit(&mut output_stream)?;
651 output_stream.result()?;
652 output_stream.into_inner().flush()?;
653
654 Ok(())
655 }) {
656 Ok(()) => {}
657 Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
658 }
659}
660
661#[derive(LintDiagnostic)]
662#[diag(codegen_ssa_linker_output)]
663struct LinkerOutput {
666 inner: String,
667}
668
669fn link_natively(
674 sess: &Session,
675 archive_builder_builder: &dyn ArchiveBuilderBuilder,
676 crate_type: CrateType,
677 out_filename: &Path,
678 codegen_results: &CodegenResults,
679 metadata: &EncodedMetadata,
680 tmpdir: &Path,
681) {
682 info!("preparing {:?} to {:?}", crate_type, out_filename);
683 let (linker_path, flavor) = linker_and_flavor(sess);
684 let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
685
686 let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
691 let archive_member =
692 should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
693 let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
694
695 let mut cmd = linker_with_args(
696 &linker_path,
697 flavor,
698 sess,
699 archive_builder_builder,
700 crate_type,
701 tmpdir,
702 temp_filename,
703 codegen_results,
704 metadata,
705 self_contained_components,
706 );
707
708 linker::disable_localization(&mut cmd);
709
710 for (k, v) in sess.target.link_env.as_ref() {
711 cmd.env(k.as_ref(), v.as_ref());
712 }
713 for k in sess.target.link_env_remove.as_ref() {
714 cmd.env_remove(k.as_ref());
715 }
716
717 for print in &sess.opts.prints {
718 if print.kind == PrintKind::LinkArgs {
719 let content = format!("{cmd:?}\n");
720 print.out.overwrite(&content, sess);
721 }
722 }
723
724 sess.dcx().abort_if_errors();
726
727 info!("{cmd:?}");
729 let unknown_arg_regex =
730 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
731 let mut prog;
732 loop {
733 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
734 let Ok(ref output) = prog else {
735 break;
736 };
737 if output.status.success() {
738 break;
739 }
740 let mut out = output.stderr.clone();
741 out.extend(&output.stdout);
742 let out = String::from_utf8_lossy(&out);
743
744 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
751 && unknown_arg_regex.is_match(&out)
752 && out.contains("-no-pie")
753 && cmd.get_args().iter().any(|e| e == "-no-pie")
754 {
755 info!("linker output: {:?}", out);
756 warn!("Linker does not support -no-pie command line option. Retrying without.");
757 for arg in cmd.take_args() {
758 if arg != "-no-pie" {
759 cmd.arg(arg);
760 }
761 }
762 info!("{cmd:?}");
763 continue;
764 }
765
766 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))
772 && unknown_arg_regex.is_match(&out)
773 && out.contains("-fuse-ld=lld")
774 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
775 {
776 info!("linker output: {:?}", out);
777 info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
778 for arg in cmd.take_args() {
779 if arg.to_string_lossy() != "-fuse-ld=lld" {
780 cmd.arg(arg);
781 }
782 }
783 info!("{cmd:?}");
784 continue;
785 }
786
787 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
790 && unknown_arg_regex.is_match(&out)
791 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
792 && cmd.get_args().iter().any(|e| e == "-static-pie")
793 {
794 info!("linker output: {:?}", out);
795 warn!(
796 "Linker does not support -static-pie command line option. Retrying with -static instead."
797 );
798 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
800 let opts = &sess.target;
801 let pre_objects = if self_contained_crt_objects {
802 &opts.pre_link_objects_self_contained
803 } else {
804 &opts.pre_link_objects
805 };
806 let post_objects = if self_contained_crt_objects {
807 &opts.post_link_objects_self_contained
808 } else {
809 &opts.post_link_objects
810 };
811 let get_objects = |objects: &CrtObjects, kind| {
812 objects
813 .get(&kind)
814 .iter()
815 .copied()
816 .flatten()
817 .map(|obj| {
818 get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
819 })
820 .collect::<Vec<_>>()
821 };
822 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
823 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
824 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
825 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
826 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
829 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
830 for arg in cmd.take_args() {
831 if arg == "-static-pie" {
832 cmd.arg("-static");
834 } else if pre_objects_static_pie.contains(&arg) {
835 cmd.args(mem::take(&mut pre_objects_static));
837 } else if post_objects_static_pie.contains(&arg) {
838 cmd.args(mem::take(&mut post_objects_static));
840 } else {
841 cmd.arg(arg);
842 }
843 }
844 info!("{cmd:?}");
845 continue;
846 }
847
848 break;
849 }
850
851 match prog {
852 Ok(prog) => {
853 let is_msvc_link_exe = sess.target.is_like_msvc
854 && flavor == LinkerFlavor::Msvc(Lld::No)
855 && linker_path.to_str() == Some("link.exe");
857
858 if !prog.status.success() {
859 let mut output = prog.stderr.clone();
860 output.extend_from_slice(&prog.stdout);
861 let escaped_output = escape_linker_output(&output, flavor);
862 let err = errors::LinkingFailed {
863 linker_path: &linker_path,
864 exit_status: prog.status,
865 command: cmd,
866 escaped_output,
867 verbose: sess.opts.verbose,
868 sysroot_dir: sess.opts.sysroot.path().to_owned(),
869 };
870 sess.dcx().emit_err(err);
871 if let Some(code) = prog.status.code() {
875 if is_msvc_link_exe && (code < 1000 || code > 9999) {
878 let is_vs_installed = windows_registry::find_vs_version().is_ok();
879 let has_linker =
880 windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
881
882 sess.dcx().emit_note(errors::LinkExeUnexpectedError);
883 if is_vs_installed && has_linker {
884 sess.dcx().emit_note(errors::RepairVSBuildTools);
886 sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
887 } else if is_vs_installed {
888 sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
890 } else {
891 sess.dcx().emit_note(errors::VisualStudioNotInstalled);
893 }
894 }
895 }
896
897 sess.dcx().abort_if_errors();
898 }
899
900 let stderr = escape_string(&prog.stderr);
901 let mut stdout = escape_string(&prog.stdout);
902 info!("linker stderr:\n{}", &stderr);
903 info!("linker stdout:\n{}", &stdout);
904
905 if is_msvc_link_exe {
908 if let Ok(str) = str::from_utf8(&prog.stdout) {
909 let mut output = String::with_capacity(str.len());
910 for line in stdout.lines() {
911 if line.starts_with(" Creating library")
912 || line.starts_with("Generating code")
913 || line.starts_with("Finished generating code")
914 {
915 continue;
916 }
917 output += line;
918 output += "\r\n"
919 }
920 stdout = escape_string(output.trim().as_bytes())
921 }
922 }
923
924 let level = codegen_results.crate_info.lint_levels.linker_messages;
925 let lint = |msg| {
926 lint_level(sess, LINKER_MESSAGES, level, None, |diag| {
927 LinkerOutput { inner: msg }.decorate_lint(diag)
928 })
929 };
930
931 if !prog.stderr.is_empty() {
932 let stderr = stderr
934 .strip_prefix("warning: ")
935 .unwrap_or(&stderr)
936 .replace(": warning: ", ": ");
937 lint(format!("linker stderr: {stderr}"));
938 }
939 if !stdout.is_empty() {
940 lint(format!("linker stdout: {}", stdout))
941 }
942 }
943 Err(e) => {
944 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
945
946 let err = if linker_not_found {
947 sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
948 } else {
949 sess.dcx().emit_err(errors::UnableToExeLinker {
950 linker_path,
951 error: e,
952 command_formatted: format!("{cmd:?}"),
953 })
954 };
955
956 if sess.target.is_like_msvc && linker_not_found {
957 sess.dcx().emit_note(errors::MsvcMissingLinker);
958 sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
959 sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
960 }
961 err.raise_fatal();
962 }
963 }
964
965 match sess.split_debuginfo() {
966 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
969
970 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
973
974 SplitDebuginfo::Packed if sess.target.is_like_darwin => {
978 let prog = Command::new("dsymutil").arg(out_filename).output();
979 match prog {
980 Ok(prog) => {
981 if !prog.status.success() {
982 let mut output = prog.stderr.clone();
983 output.extend_from_slice(&prog.stdout);
984 sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
985 status: prog.status,
986 output: escape_string(&output),
987 });
988 }
989 }
990 Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
991 }
992 }
993
994 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
997
998 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1004 }
1005
1006 let strip = sess.opts.cg.strip;
1007
1008 if sess.target.is_like_darwin {
1009 let stripcmd = "rust-objcopy";
1010 match (strip, crate_type) {
1011 (Strip::Debuginfo, _) => {
1012 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1013 }
1014 (
1016 Strip::Symbols,
1017 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1018 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1019 (Strip::Symbols, _) => {
1020 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1021 }
1022 (Strip::None, _) => {}
1023 }
1024 }
1025
1026 if sess.target.is_like_solaris {
1027 let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1034 match strip {
1035 Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1037 Strip::Symbols => {}
1039 Strip::None => {}
1040 }
1041 }
1042
1043 if sess.target.is_like_aix {
1044 if !sess.host.is_like_aix {
1046 sess.dcx().emit_warn(errors::AixStripNotUsed);
1047 }
1048 let stripcmd = "/usr/bin/strip";
1049 match strip {
1050 Strip::Debuginfo => {
1051 strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1053 }
1054 Strip::Symbols => {
1055 strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1057 }
1058 Strip::None => {}
1059 }
1060 }
1061
1062 if should_archive {
1063 let mut ab = archive_builder_builder.new_archive_builder(sess);
1064 ab.add_file(temp_filename);
1065 ab.build(out_filename);
1066 }
1067}
1068
1069fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1070 let mut cmd = Command::new(util);
1071 cmd.args(options);
1072
1073 let mut new_path = sess.get_tools_search_paths(false);
1074 if let Some(path) = env::var_os("PATH") {
1075 new_path.extend(env::split_paths(&path));
1076 }
1077 cmd.env("PATH", env::join_paths(new_path).unwrap());
1078
1079 let prog = cmd.arg(out_filename).output();
1080 match prog {
1081 Ok(prog) => {
1082 if !prog.status.success() {
1083 let mut output = prog.stderr.clone();
1084 output.extend_from_slice(&prog.stdout);
1085 sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1086 util,
1087 status: prog.status,
1088 output: escape_string(&output),
1089 });
1090 }
1091 }
1092 Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1093 }
1094}
1095
1096fn escape_string(s: &[u8]) -> String {
1097 match str::from_utf8(s) {
1098 Ok(s) => s.to_owned(),
1099 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1100 }
1101}
1102
1103#[cfg(not(windows))]
1104fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1105 escape_string(s)
1106}
1107
1108#[cfg(windows)]
1111fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1112 if flavour != LinkerFlavor::Msvc(Lld::No) {
1114 return escape_string(s);
1115 }
1116 match str::from_utf8(s) {
1117 Ok(s) => return s.to_owned(),
1118 Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1119 Some(s) => s,
1120 None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1122 },
1123 }
1124}
1125
1126#[cfg(windows)]
1128mod win {
1129 use windows::Win32::Globalization::{
1130 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1131 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1132 };
1133
1134 pub(super) fn oem_code_page() -> u32 {
1137 unsafe {
1138 let mut cp: u32 = 0;
1139 let len = size_of::<u32>() / size_of::<u16>();
1142 let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1143 let len_written = GetLocaleInfoEx(
1144 LOCALE_NAME_SYSTEM_DEFAULT,
1145 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1146 Some(data),
1147 );
1148 if len_written as usize == len { cp } else { CP_OEMCP }
1149 }
1150 }
1151 pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1160 if s.len() > isize::MAX as usize {
1162 return None;
1163 }
1164 let flags = MB_ERR_INVALID_CHARS;
1166 let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1169 if len > 0 {
1170 let mut utf16 = vec![0; len as usize];
1171 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1172 if len > 0 {
1173 return utf16.get(..len as usize).map(String::from_utf16_lossy);
1174 }
1175 }
1176 None
1177 }
1178}
1179
1180fn add_sanitizer_libraries(
1181 sess: &Session,
1182 flavor: LinkerFlavor,
1183 crate_type: CrateType,
1184 linker: &mut dyn Linker,
1185) {
1186 if sess.target.is_like_android {
1187 return;
1190 }
1191
1192 if sess.opts.unstable_opts.external_clangrt {
1193 return;
1196 }
1197
1198 if matches!(crate_type, CrateType::Rlib | CrateType::Staticlib) {
1199 return;
1200 }
1201
1202 if matches!(
1207 crate_type,
1208 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1209 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1210 {
1211 return;
1212 }
1213
1214 let sanitizer = sess.opts.unstable_opts.sanitizer;
1215 if sanitizer.contains(SanitizerSet::ADDRESS) {
1216 link_sanitizer_runtime(sess, flavor, linker, "asan");
1217 }
1218 if sanitizer.contains(SanitizerSet::DATAFLOW) {
1219 link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1220 }
1221 if sanitizer.contains(SanitizerSet::LEAK)
1222 && !sanitizer.contains(SanitizerSet::ADDRESS)
1223 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1224 {
1225 link_sanitizer_runtime(sess, flavor, linker, "lsan");
1226 }
1227 if sanitizer.contains(SanitizerSet::MEMORY) {
1228 link_sanitizer_runtime(sess, flavor, linker, "msan");
1229 }
1230 if sanitizer.contains(SanitizerSet::THREAD) {
1231 link_sanitizer_runtime(sess, flavor, linker, "tsan");
1232 }
1233 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1234 link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1235 }
1236 if sanitizer.contains(SanitizerSet::SAFESTACK) {
1237 link_sanitizer_runtime(sess, flavor, linker, "safestack");
1238 }
1239}
1240
1241fn link_sanitizer_runtime(
1242 sess: &Session,
1243 flavor: LinkerFlavor,
1244 linker: &mut dyn Linker,
1245 name: &str,
1246) {
1247 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1248 let path = sess.target_tlib_path.dir.join(filename);
1249 if path.exists() {
1250 sess.target_tlib_path.dir.clone()
1251 } else {
1252 filesearch::make_target_lib_path(
1253 &sess.opts.sysroot.default,
1254 sess.opts.target_triple.tuple(),
1255 )
1256 }
1257 }
1258
1259 let channel =
1260 option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
1261
1262 if sess.target.is_like_darwin {
1263 let filename = format!("rustc{channel}_rt.{name}");
1268 let path = find_sanitizer_runtime(sess, &filename);
1269 let rpath = path.to_str().expect("non-utf8 component in path");
1270 linker.link_args(&["-rpath", rpath]);
1271 linker.link_dylib_by_name(&filename, false, true);
1272 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1273 linker.link_arg("/INFERASANLIBS");
1276 } else {
1277 let filename = format!("librustc{channel}_rt.{name}.a");
1278 let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1279 linker.link_staticlib_by_path(&path, true);
1280 }
1281}
1282
1283pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1294 !sess.target.no_builtins
1298 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1299}
1300
1301pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1303 fn infer_from(
1304 sess: &Session,
1305 linker: Option<PathBuf>,
1306 flavor: Option<LinkerFlavor>,
1307 features: LinkerFeaturesCli,
1308 ) -> Option<(PathBuf, LinkerFlavor)> {
1309 let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1310 match (linker, flavor) {
1311 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1312 (None, Some(flavor)) => Some((
1314 PathBuf::from(match flavor {
1315 LinkerFlavor::Gnu(Cc::Yes, _)
1316 | LinkerFlavor::Darwin(Cc::Yes, _)
1317 | LinkerFlavor::WasmLld(Cc::Yes)
1318 | LinkerFlavor::Unix(Cc::Yes) => {
1319 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1320 "gcc"
1327 } else {
1328 "cc"
1329 }
1330 }
1331 LinkerFlavor::Gnu(_, Lld::Yes)
1332 | LinkerFlavor::Darwin(_, Lld::Yes)
1333 | LinkerFlavor::WasmLld(..)
1334 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1335 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1336 "ld"
1337 }
1338 LinkerFlavor::Msvc(..) => "link.exe",
1339 LinkerFlavor::EmCc => {
1340 if cfg!(windows) {
1341 "emcc.bat"
1342 } else {
1343 "emcc"
1344 }
1345 }
1346 LinkerFlavor::Bpf => "bpf-linker",
1347 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1348 LinkerFlavor::Ptx => "rust-ptx-linker",
1349 }),
1350 flavor,
1351 )),
1352 (Some(linker), None) => {
1353 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1354 sess.dcx().emit_fatal(errors::LinkerFileStem);
1355 });
1356 let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1357 let flavor = adjust_flavor_to_features(flavor, features);
1358 Some((linker, flavor))
1359 }
1360 (None, None) => None,
1361 }
1362 }
1363
1364 fn adjust_flavor_to_features(
1369 flavor: LinkerFlavor,
1370 features: LinkerFeaturesCli,
1371 ) -> LinkerFlavor {
1372 if features.enabled.contains(LinkerFeatures::LLD) {
1374 flavor.with_lld_enabled()
1375 } else if features.disabled.contains(LinkerFeatures::LLD) {
1376 flavor.with_lld_disabled()
1377 } else {
1378 flavor
1379 }
1380 }
1381
1382 let features = sess.opts.unstable_opts.linker_features;
1383
1384 let linker_flavor = match sess.opts.cg.linker_flavor {
1387 Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1389 Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1390 _ => sess
1392 .opts
1393 .cg
1394 .linker_flavor
1395 .map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
1396 };
1397 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1398 return ret;
1399 }
1400
1401 if let Some(ret) = infer_from(
1402 sess,
1403 sess.target.linker.as_deref().map(PathBuf::from),
1404 Some(sess.target.linker_flavor),
1405 features,
1406 ) {
1407 return ret;
1408 }
1409
1410 bug!("Not enough information provided to determine how to invoke the linker");
1411}
1412
1413fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1417 if sess.opts.debuginfo == config::DebugInfo::None {
1419 return (false, false);
1420 }
1421
1422 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1423 (SplitDebuginfo::Off, _) => (false, false),
1425 (SplitDebuginfo::Packed, _) => (false, false),
1428 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1431 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1435 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1436 }
1437}
1438
1439#[derive(PartialEq)]
1440enum RlibFlavor {
1441 Normal,
1442 StaticlibBase,
1443}
1444
1445fn print_native_static_libs(
1446 sess: &Session,
1447 out: &OutFileName,
1448 all_native_libs: &[NativeLib],
1449 all_rust_dylibs: &[&Path],
1450) {
1451 let mut lib_args: Vec<_> = all_native_libs
1452 .iter()
1453 .filter(|l| relevant_lib(sess, l))
1454 .filter_map(|lib| {
1455 let name = lib.name;
1456 match lib.kind {
1457 NativeLibKind::Static { bundle: Some(false), .. }
1458 | NativeLibKind::Dylib { .. }
1459 | NativeLibKind::Unspecified => {
1460 let verbatim = lib.verbatim;
1461 if sess.target.is_like_msvc {
1462 let (prefix, suffix) = sess.staticlib_components(verbatim);
1463 Some(format!("{prefix}{name}{suffix}"))
1464 } else if sess.target.linker_flavor.is_gnu() {
1465 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1466 } else {
1467 Some(format!("-l{name}"))
1468 }
1469 }
1470 NativeLibKind::Framework { .. } => {
1471 Some(format!("-framework {name}"))
1473 }
1474 NativeLibKind::Static { bundle: None | Some(true), .. }
1476 | NativeLibKind::LinkArg
1477 | NativeLibKind::WasmImportModule
1478 | NativeLibKind::RawDylib => None,
1479 }
1480 })
1481 .dedup()
1483 .collect();
1484 for path in all_rust_dylibs {
1485 let parent = path.parent();
1490 if let Some(dir) = parent {
1491 let dir = fix_windows_verbatim_for_gcc(dir);
1492 if sess.target.is_like_msvc {
1493 let mut arg = String::from("/LIBPATH:");
1494 arg.push_str(&dir.display().to_string());
1495 lib_args.push(arg);
1496 } else {
1497 lib_args.push("-L".to_owned());
1498 lib_args.push(dir.display().to_string());
1499 }
1500 }
1501 let stem = path.file_stem().unwrap().to_str().unwrap();
1502 let lib = if let Some(lib) = stem.strip_prefix("lib")
1504 && !sess.target.is_like_windows
1505 {
1506 lib
1507 } else {
1508 stem
1509 };
1510 let path = parent.unwrap_or_else(|| Path::new(""));
1511 if sess.target.is_like_msvc {
1512 let name = format!("{lib}.dll.lib");
1517 if path.join(&name).exists() {
1518 lib_args.push(name);
1519 }
1520 } else {
1521 lib_args.push(format!("-l{lib}"));
1522 }
1523 }
1524
1525 match out {
1526 OutFileName::Real(path) => {
1527 out.overwrite(&lib_args.join(" "), sess);
1528 sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1529 }
1530 OutFileName::Stdout => {
1531 sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1532 sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
1535 }
1536 }
1537}
1538
1539fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1540 let file_path = sess.target_tlib_path.dir.join(name);
1541 if file_path.exists() {
1542 return file_path;
1543 }
1544 if self_contained {
1546 let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1547 if file_path.exists() {
1548 return file_path;
1549 }
1550 }
1551 for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1552 let file_path = search_path.dir.join(name);
1553 if file_path.exists() {
1554 return file_path;
1555 }
1556 }
1557 PathBuf::from(name)
1558}
1559
1560fn exec_linker(
1561 sess: &Session,
1562 cmd: &Command,
1563 out_filename: &Path,
1564 flavor: LinkerFlavor,
1565 tmpdir: &Path,
1566) -> io::Result<Output> {
1567 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1577 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1578 Ok(child) => {
1579 let output = child.wait_with_output();
1580 flush_linked_file(&output, out_filename)?;
1581 return output;
1582 }
1583 Err(ref e) if command_line_too_big(e) => {
1584 info!("command line to linker was too big: {}", e);
1585 }
1586 Err(e) => return Err(e),
1587 }
1588 }
1589
1590 info!("falling back to passing arguments to linker via an @-file");
1591 let mut cmd2 = cmd.clone();
1592 let mut args = String::new();
1593 for arg in cmd2.take_args() {
1594 args.push_str(
1595 &Escape {
1596 arg: arg.to_str().unwrap(),
1597 is_like_msvc: sess.target.is_like_msvc
1602 || (cfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1603 }
1604 .to_string(),
1605 );
1606 args.push('\n');
1607 }
1608 let file = tmpdir.join("linker-arguments");
1609 let bytes = if sess.target.is_like_msvc {
1610 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1611 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1613 out.push(c as u8);
1615 out.push((c >> 8) as u8);
1616 }
1617 out
1618 } else {
1619 args.into_bytes()
1620 };
1621 fs::write(&file, &bytes)?;
1622 cmd2.arg(format!("@{}", file.display()));
1623 info!("invoking linker {:?}", cmd2);
1624 let output = cmd2.output();
1625 flush_linked_file(&output, out_filename)?;
1626 return output;
1627
1628 #[cfg(not(windows))]
1629 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1630 Ok(())
1631 }
1632
1633 #[cfg(windows)]
1634 fn flush_linked_file(
1635 command_output: &io::Result<Output>,
1636 out_filename: &Path,
1637 ) -> io::Result<()> {
1638 if let &Ok(ref out) = command_output {
1647 if out.status.success() {
1648 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1649 of.sync_all()?;
1650 }
1651 }
1652 }
1653
1654 Ok(())
1655 }
1656
1657 #[cfg(unix)]
1658 fn command_line_too_big(err: &io::Error) -> bool {
1659 err.raw_os_error() == Some(::libc::E2BIG)
1660 }
1661
1662 #[cfg(windows)]
1663 fn command_line_too_big(err: &io::Error) -> bool {
1664 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1665 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1666 }
1667
1668 #[cfg(not(any(unix, windows)))]
1669 fn command_line_too_big(_: &io::Error) -> bool {
1670 false
1671 }
1672
1673 struct Escape<'a> {
1674 arg: &'a str,
1675 is_like_msvc: bool,
1676 }
1677
1678 impl<'a> fmt::Display for Escape<'a> {
1679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1680 if self.is_like_msvc {
1681 write!(f, "\"")?;
1689 for c in self.arg.chars() {
1690 match c {
1691 '"' => write!(f, "\\{c}")?,
1692 c => write!(f, "{c}")?,
1693 }
1694 }
1695 write!(f, "\"")?;
1696 } else {
1697 for c in self.arg.chars() {
1708 match c {
1709 '\\' | ' ' => write!(f, "\\{c}")?,
1710 c => write!(f, "{c}")?,
1711 }
1712 }
1713 }
1714 Ok(())
1715 }
1716 }
1717}
1718
1719fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1720 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1721 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1722 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1723 LinkOutputKind::DynamicPicExe
1724 }
1725 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1726 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1727 LinkOutputKind::StaticPicExe
1728 }
1729 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1730 (_, true, _) => LinkOutputKind::StaticDylib,
1731 (_, false, _) => LinkOutputKind::DynamicDylib,
1732 };
1733
1734 let opts = &sess.target;
1736 let pic_exe_supported = opts.position_independent_executables;
1737 let static_pic_exe_supported = opts.static_position_independent_executables;
1738 let static_dylib_supported = opts.crt_static_allows_dylibs;
1739 match kind {
1740 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1741 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1742 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1743 _ => kind,
1744 }
1745}
1746
1747fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1749 if linker == Path::new("rust-lld") {
1751 return true;
1752 }
1753 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1754 linker.with_extension("exe")
1755 } else {
1756 linker.to_path_buf()
1757 };
1758 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1759 let full_path = dir.join(&linker_with_extension);
1760 if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1762 return false;
1763 }
1764 }
1765 true
1766}
1767
1768fn self_contained_components(
1772 sess: &Session,
1773 crate_type: CrateType,
1774 linker: &Path,
1775) -> LinkSelfContainedComponents {
1776 let self_contained =
1779 if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1780 if sess.target.link_self_contained.is_disabled() {
1783 sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1784 }
1785 self_contained
1786 } else {
1787 match sess.target.link_self_contained {
1788 LinkSelfContainedDefault::False => false,
1789 LinkSelfContainedDefault::True => true,
1790
1791 LinkSelfContainedDefault::WithComponents(components) => {
1792 return components;
1795 }
1796
1797 LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1801 LinkSelfContainedDefault::InferredForMingw => {
1802 sess.host == sess.target
1803 && sess.target.vendor != "uwp"
1804 && detect_self_contained_mingw(sess, linker)
1805 }
1806 }
1807 };
1808 if self_contained {
1809 LinkSelfContainedComponents::all()
1810 } else {
1811 LinkSelfContainedComponents::empty()
1812 }
1813}
1814
1815fn add_pre_link_objects(
1817 cmd: &mut dyn Linker,
1818 sess: &Session,
1819 flavor: LinkerFlavor,
1820 link_output_kind: LinkOutputKind,
1821 self_contained: bool,
1822) {
1823 let opts = &sess.target;
1826 let empty = Default::default();
1827 let objects = if self_contained {
1828 &opts.pre_link_objects_self_contained
1829 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1830 &opts.pre_link_objects
1831 } else {
1832 &empty
1833 };
1834 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1835 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1836 }
1837}
1838
1839fn add_post_link_objects(
1841 cmd: &mut dyn Linker,
1842 sess: &Session,
1843 link_output_kind: LinkOutputKind,
1844 self_contained: bool,
1845) {
1846 let objects = if self_contained {
1847 &sess.target.post_link_objects_self_contained
1848 } else {
1849 &sess.target.post_link_objects
1850 };
1851 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1852 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1853 }
1854}
1855
1856fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1859 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1860 cmd.verbatim_args(args.iter().map(Deref::deref));
1861 }
1862
1863 cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1864}
1865
1866fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1868 match (crate_type, &sess.target.link_script) {
1869 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1870 if !sess.target.linker_flavor.is_gnu() {
1871 sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1872 }
1873
1874 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1875
1876 let path = tmpdir.join(file_name);
1877 if let Err(error) = fs::write(&path, script.as_ref()) {
1878 sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1879 }
1880
1881 cmd.link_arg("--script").link_arg(path);
1882 }
1883 _ => {}
1884 }
1885}
1886
1887fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1890 cmd.verbatim_args(&sess.opts.cg.link_args);
1891}
1892
1893fn add_late_link_args(
1896 cmd: &mut dyn Linker,
1897 sess: &Session,
1898 flavor: LinkerFlavor,
1899 crate_type: CrateType,
1900 codegen_results: &CodegenResults,
1901) {
1902 let any_dynamic_crate = crate_type == CrateType::Dylib
1903 || crate_type == CrateType::Sdylib
1904 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1905 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1906 });
1907 if any_dynamic_crate {
1908 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1909 cmd.verbatim_args(args.iter().map(Deref::deref));
1910 }
1911 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1912 cmd.verbatim_args(args.iter().map(Deref::deref));
1913 }
1914 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1915 cmd.verbatim_args(args.iter().map(Deref::deref));
1916 }
1917}
1918
1919fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1922 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1923 cmd.verbatim_args(args.iter().map(Deref::deref));
1924 }
1925}
1926
1927fn add_linked_symbol_object(
1957 cmd: &mut dyn Linker,
1958 sess: &Session,
1959 tmpdir: &Path,
1960 symbols: &[(String, SymbolExportKind)],
1961) {
1962 if symbols.is_empty() {
1963 return;
1964 }
1965
1966 let Some(mut file) = super::metadata::create_object_file(sess) else {
1967 return;
1968 };
1969
1970 if file.format() == object::BinaryFormat::Coff {
1971 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1974
1975 file.set_mangling(object::write::Mangling::None);
1978 }
1979
1980 if file.format() == object::BinaryFormat::MachO {
1981 file.set_subsections_via_symbols();
1985 }
1986
1987 let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
1990 Some(file.add_section(
1991 file.segment_name(object::write::StandardSegment::Data).to_vec(),
1992 "__data".into(),
1993 object::SectionKind::Data,
1994 ))
1995 } else {
1996 None
1997 };
1998
1999 for (sym, kind) in symbols.iter() {
2000 let symbol = file.add_symbol(object::write::Symbol {
2001 name: sym.clone().into(),
2002 value: 0,
2003 size: 0,
2004 kind: match kind {
2005 SymbolExportKind::Text => object::SymbolKind::Text,
2006 SymbolExportKind::Data => object::SymbolKind::Data,
2007 SymbolExportKind::Tls => object::SymbolKind::Tls,
2008 },
2009 scope: object::SymbolScope::Unknown,
2010 weak: false,
2011 section: object::write::SymbolSection::Undefined,
2012 flags: object::SymbolFlags::None,
2013 });
2014
2015 if let Some(section) = ld64_section_helper {
2052 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2053 .expect("failed adding relocation");
2054 }
2055 }
2056
2057 let path = tmpdir.join("symbols.o");
2058 let result = std::fs::write(&path, file.write().unwrap());
2059 if let Err(error) = result {
2060 sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2061 }
2062 cmd.add_object(&path);
2063}
2064
2065fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2067 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2068 cmd.add_object(obj);
2069 }
2070}
2071
2072fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2074 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
2075 cmd.add_object(obj);
2076 }
2077}
2078
2079fn add_local_crate_metadata_objects(
2081 cmd: &mut dyn Linker,
2082 sess: &Session,
2083 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2084 crate_type: CrateType,
2085 tmpdir: &Path,
2086 codegen_results: &CodegenResults,
2087 metadata: &EncodedMetadata,
2088) {
2089 if matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2093 let data = archive_builder_builder.create_dylib_metadata_wrapper(
2094 sess,
2095 &metadata,
2096 &codegen_results.crate_info.metadata_symbol,
2097 );
2098 let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
2099
2100 cmd.add_object(&obj);
2101 }
2102}
2103
2104fn add_library_search_dirs(
2106 cmd: &mut dyn Linker,
2107 sess: &Session,
2108 self_contained_components: LinkSelfContainedComponents,
2109 apple_sdk_root: Option<&Path>,
2110) {
2111 if !sess.opts.unstable_opts.link_native_libraries {
2112 return;
2113 }
2114
2115 let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2116 let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2117 if is_framework {
2118 cmd.framework_path(dir);
2119 } else {
2120 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2121 }
2122 ControlFlow::<()>::Continue(())
2123 });
2124}
2125
2126fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2129 match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2130 RelroLevel::Full => cmd.full_relro(),
2131 RelroLevel::Partial => cmd.partial_relro(),
2132 RelroLevel::Off => cmd.no_relro(),
2133 RelroLevel::None => {}
2134 }
2135}
2136
2137fn add_rpath_args(
2139 cmd: &mut dyn Linker,
2140 sess: &Session,
2141 codegen_results: &CodegenResults,
2142 out_filename: &Path,
2143) {
2144 if !sess.target.has_rpath {
2145 return;
2146 }
2147
2148 if sess.opts.cg.rpath {
2152 let libs = codegen_results
2153 .crate_info
2154 .used_crates
2155 .iter()
2156 .filter_map(|cnum| {
2157 codegen_results.crate_info.used_crate_source[cnum]
2158 .dylib
2159 .as_ref()
2160 .map(|(path, _)| &**path)
2161 })
2162 .collect::<Vec<_>>();
2163 let rpath_config = RPathConfig {
2164 libs: &*libs,
2165 out_filename: out_filename.to_path_buf(),
2166 is_like_darwin: sess.target.is_like_darwin,
2167 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2168 };
2169 cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2170 }
2171}
2172
2173fn linker_with_args(
2182 path: &Path,
2183 flavor: LinkerFlavor,
2184 sess: &Session,
2185 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2186 crate_type: CrateType,
2187 tmpdir: &Path,
2188 out_filename: &Path,
2189 codegen_results: &CodegenResults,
2190 metadata: &EncodedMetadata,
2191 self_contained_components: LinkSelfContainedComponents,
2192) -> Command {
2193 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2194 let cmd = &mut *super::linker::get_linker(
2195 sess,
2196 path,
2197 flavor,
2198 self_contained_components.are_any_components_enabled(),
2199 &codegen_results.crate_info.target_cpu,
2200 );
2201 let link_output_kind = link_output_kind(sess, crate_type);
2202
2203 cmd.export_symbols(
2211 tmpdir,
2212 crate_type,
2213 &codegen_results.crate_info.exported_symbols[&crate_type],
2214 );
2215
2216 add_pre_link_args(cmd, sess, flavor);
2221
2222 add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
2226
2227 add_linked_symbol_object(
2228 cmd,
2229 sess,
2230 tmpdir,
2231 &codegen_results.crate_info.linked_symbols[&crate_type],
2232 );
2233
2234 add_sanitizer_libraries(sess, flavor, crate_type, cmd);
2236
2237 add_local_crate_regular_objects(cmd, codegen_results);
2265 add_local_crate_metadata_objects(
2266 cmd,
2267 sess,
2268 archive_builder_builder,
2269 crate_type,
2270 tmpdir,
2271 codegen_results,
2272 metadata,
2273 );
2274 add_local_crate_allocator_objects(cmd, codegen_results);
2275
2276 cmd.add_as_needed();
2285
2286 add_local_native_libraries(
2288 cmd,
2289 sess,
2290 archive_builder_builder,
2291 codegen_results,
2292 tmpdir,
2293 link_output_kind,
2294 );
2295
2296 add_upstream_rust_crates(
2298 cmd,
2299 sess,
2300 archive_builder_builder,
2301 codegen_results,
2302 crate_type,
2303 tmpdir,
2304 link_output_kind,
2305 );
2306
2307 add_upstream_native_libraries(
2309 cmd,
2310 sess,
2311 archive_builder_builder,
2312 codegen_results,
2313 tmpdir,
2314 link_output_kind,
2315 );
2316
2317 let raw_dylib_dir = tmpdir.join("raw-dylibs");
2319 if sess.target.binary_format == BinaryFormat::Elf {
2320 if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2325 sess.dcx().emit_fatal(errors::CreateTempDir { error })
2326 }
2327 cmd.include_path(&raw_dylib_dir);
2328 }
2329
2330 if sess.target.is_like_windows {
2332 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2333 sess,
2334 archive_builder_builder,
2335 codegen_results.crate_info.used_libraries.iter(),
2336 tmpdir,
2337 true,
2338 ) {
2339 cmd.add_object(&output_path);
2340 }
2341 } else {
2342 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2343 sess,
2344 codegen_results.crate_info.used_libraries.iter(),
2345 &raw_dylib_dir,
2346 ) {
2347 cmd.link_dylib_by_name(&link_path, true, false);
2349 }
2350 }
2351 let dependency_linkage = codegen_results
2356 .crate_info
2357 .dependency_formats
2358 .get(&crate_type)
2359 .expect("failed to find crate type in dependency format list");
2360
2361 #[allow(rustc::potential_query_instability)]
2363 let mut native_libraries_from_nonstatics = codegen_results
2364 .crate_info
2365 .native_libraries
2366 .iter()
2367 .filter_map(|(&cnum, libraries)| {
2368 if sess.target.is_like_windows {
2369 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2370 } else {
2371 Some(libraries)
2372 }
2373 })
2374 .flatten()
2375 .collect::<Vec<_>>();
2376 native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
2377
2378 if sess.target.is_like_windows {
2379 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2380 sess,
2381 archive_builder_builder,
2382 native_libraries_from_nonstatics,
2383 tmpdir,
2384 false,
2385 ) {
2386 cmd.add_object(&output_path);
2387 }
2388 } else {
2389 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2390 sess,
2391 native_libraries_from_nonstatics,
2392 &raw_dylib_dir,
2393 ) {
2394 cmd.link_dylib_by_name(&link_path, true, false);
2396 }
2397 }
2398
2399 cmd.reset_per_library_state();
2402
2403 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2407
2408 add_order_independent_options(
2413 cmd,
2414 sess,
2415 link_output_kind,
2416 self_contained_components,
2417 flavor,
2418 crate_type,
2419 codegen_results,
2420 out_filename,
2421 tmpdir,
2422 );
2423
2424 add_user_defined_link_args(cmd, sess);
2428
2429 add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
2433
2434 add_post_link_args(cmd, sess, flavor);
2441
2442 cmd.take_cmd()
2443}
2444
2445fn add_order_independent_options(
2446 cmd: &mut dyn Linker,
2447 sess: &Session,
2448 link_output_kind: LinkOutputKind,
2449 self_contained_components: LinkSelfContainedComponents,
2450 flavor: LinkerFlavor,
2451 crate_type: CrateType,
2452 codegen_results: &CodegenResults,
2453 out_filename: &Path,
2454 tmpdir: &Path,
2455) {
2456 add_lld_args(cmd, sess, flavor, self_contained_components);
2458
2459 add_apple_link_args(cmd, sess, flavor);
2460
2461 let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
2462
2463 add_link_script(cmd, sess, tmpdir, crate_type);
2464
2465 if sess.target.os == "fuchsia"
2466 && crate_type == CrateType::Executable
2467 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2468 {
2469 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2470 "asan/"
2471 } else {
2472 ""
2473 };
2474 cmd.link_arg(format!("--dynamic-linker={prefix}ld.so.1"));
2475 }
2476
2477 if sess.target.eh_frame_header {
2478 cmd.add_eh_frame_header();
2479 }
2480
2481 cmd.add_no_exec();
2483
2484 if self_contained_components.is_crt_objects_enabled() {
2485 cmd.no_crt_objects();
2486 }
2487
2488 if sess.target.os == "emscripten" {
2489 cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2490 "-fwasm-exceptions"
2491 } else if sess.panic_strategy() == PanicStrategy::Abort {
2492 "-sDISABLE_EXCEPTION_CATCHING=1"
2493 } else {
2494 "-sDISABLE_EXCEPTION_CATCHING=0"
2495 });
2496 }
2497
2498 if flavor == LinkerFlavor::Llbc {
2499 cmd.link_args(&[
2500 "--target",
2501 &versioned_llvm_target(sess),
2502 "--target-cpu",
2503 &codegen_results.crate_info.target_cpu,
2504 ]);
2505 if codegen_results.crate_info.target_features.len() > 0 {
2506 cmd.link_arg(&format!(
2507 "--target-feature={}",
2508 &codegen_results.crate_info.target_features.join(",")
2509 ));
2510 }
2511 } else if flavor == LinkerFlavor::Ptx {
2512 cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2513 } else if flavor == LinkerFlavor::Bpf {
2514 cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2515 if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2516 .into_iter()
2517 .find(|feat| !feat.is_empty())
2518 {
2519 cmd.link_args(&["--cpu-features", feat]);
2520 }
2521 }
2522
2523 cmd.linker_plugin_lto();
2524
2525 add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
2526
2527 cmd.output_filename(out_filename);
2528
2529 if crate_type == CrateType::Executable
2530 && sess.target.is_like_windows
2531 && let Some(s) = &codegen_results.crate_info.windows_subsystem
2532 {
2533 cmd.subsystem(s);
2534 }
2535
2536 if !sess.link_dead_code() {
2539 let keep_metadata =
2544 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2545 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2546 {
2547 cmd.gc_sections(keep_metadata);
2548 } else {
2549 cmd.no_gc_sections();
2550 }
2551 }
2552
2553 cmd.set_output_kind(link_output_kind, crate_type, out_filename);
2554
2555 add_relro_args(cmd, sess);
2556
2557 cmd.optimize();
2559
2560 let natvis_visualizers = collect_natvis_visualizers(
2562 tmpdir,
2563 sess,
2564 &codegen_results.crate_info.local_crate_name,
2565 &codegen_results.crate_info.natvis_debugger_visualizers,
2566 );
2567
2568 cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
2570
2571 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2574 cmd.no_default_libraries();
2575 }
2576
2577 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2578 cmd.pgo_gen();
2579 }
2580
2581 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2582 cmd.control_flow_guard();
2583 }
2584
2585 if sess.opts.unstable_opts.ehcont_guard {
2587 cmd.ehcont_guard();
2588 }
2589
2590 add_rpath_args(cmd, sess, codegen_results, out_filename);
2591}
2592
2593fn collect_natvis_visualizers(
2595 tmpdir: &Path,
2596 sess: &Session,
2597 crate_name: &Symbol,
2598 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2599) -> Vec<PathBuf> {
2600 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2601
2602 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2603 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2604
2605 match fs::write(&visualizer_out_file, &visualizer.src) {
2606 Ok(()) => {
2607 visualizer_paths.push(visualizer_out_file);
2608 }
2609 Err(error) => {
2610 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2611 path: visualizer_out_file,
2612 error,
2613 });
2614 }
2615 };
2616 }
2617 visualizer_paths
2618}
2619
2620fn add_native_libs_from_crate(
2621 cmd: &mut dyn Linker,
2622 sess: &Session,
2623 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2624 codegen_results: &CodegenResults,
2625 tmpdir: &Path,
2626 bundled_libs: &FxIndexSet<Symbol>,
2627 cnum: CrateNum,
2628 link_static: bool,
2629 link_dynamic: bool,
2630 link_output_kind: LinkOutputKind,
2631) {
2632 if !sess.opts.unstable_opts.link_native_libraries {
2633 return;
2637 }
2638
2639 if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2640 let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2642 archive_builder_builder
2643 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2644 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2645 }
2646
2647 let native_libs = match cnum {
2648 LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2649 _ => &codegen_results.crate_info.native_libraries[&cnum],
2650 };
2651
2652 let mut last = (None, NativeLibKind::Unspecified, false);
2653 for lib in native_libs {
2654 if !relevant_lib(sess, lib) {
2655 continue;
2656 }
2657
2658 last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2660 continue;
2661 } else {
2662 (Some(lib.name), lib.kind, lib.verbatim)
2663 };
2664
2665 let name = lib.name.as_str();
2666 let verbatim = lib.verbatim;
2667 match lib.kind {
2668 NativeLibKind::Static { bundle, whole_archive } => {
2669 if link_static {
2670 let bundle = bundle.unwrap_or(true);
2671 let whole_archive = whole_archive == Some(true);
2672 if bundle && cnum != LOCAL_CRATE {
2673 if let Some(filename) = lib.filename {
2674 let path = tmpdir.join(filename.as_str());
2676 cmd.link_staticlib_by_path(&path, whole_archive);
2677 }
2678 } else {
2679 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2680 }
2681 }
2682 }
2683 NativeLibKind::Dylib { as_needed } => {
2684 if link_dynamic {
2685 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2686 }
2687 }
2688 NativeLibKind::Unspecified => {
2689 if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2692 if link_static {
2693 cmd.link_staticlib_by_name(name, verbatim, false);
2694 }
2695 } else if link_dynamic {
2696 cmd.link_dylib_by_name(name, verbatim, true);
2697 }
2698 }
2699 NativeLibKind::Framework { as_needed } => {
2700 if link_dynamic {
2701 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2702 }
2703 }
2704 NativeLibKind::RawDylib => {
2705 }
2707 NativeLibKind::WasmImportModule => {}
2708 NativeLibKind::LinkArg => {
2709 if link_static {
2710 if verbatim {
2711 cmd.verbatim_arg(name);
2712 } else {
2713 cmd.link_arg(name);
2714 }
2715 }
2716 }
2717 }
2718 }
2719}
2720
2721fn add_local_native_libraries(
2722 cmd: &mut dyn Linker,
2723 sess: &Session,
2724 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2725 codegen_results: &CodegenResults,
2726 tmpdir: &Path,
2727 link_output_kind: LinkOutputKind,
2728) {
2729 let link_static = true;
2731 let link_dynamic = true;
2732 add_native_libs_from_crate(
2733 cmd,
2734 sess,
2735 archive_builder_builder,
2736 codegen_results,
2737 tmpdir,
2738 &Default::default(),
2739 LOCAL_CRATE,
2740 link_static,
2741 link_dynamic,
2742 link_output_kind,
2743 );
2744}
2745
2746fn add_upstream_rust_crates(
2747 cmd: &mut dyn Linker,
2748 sess: &Session,
2749 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2750 codegen_results: &CodegenResults,
2751 crate_type: CrateType,
2752 tmpdir: &Path,
2753 link_output_kind: LinkOutputKind,
2754) {
2755 let data = codegen_results
2763 .crate_info
2764 .dependency_formats
2765 .get(&crate_type)
2766 .expect("failed to find crate type in dependency format list");
2767
2768 if sess.target.is_like_aix {
2769 cmd.link_or_cc_arg("-bnoipath");
2775 }
2776
2777 for &cnum in &codegen_results.crate_info.used_crates {
2778 let linkage = data[cnum];
2786 let link_static_crate = linkage == Linkage::Static
2787 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2788 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2789 || codegen_results.crate_info.profiler_runtime == Some(cnum));
2790
2791 let mut bundled_libs = Default::default();
2792 match linkage {
2793 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2794 if link_static_crate {
2795 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2796 .iter()
2797 .filter_map(|lib| lib.filename)
2798 .collect();
2799 add_static_crate(
2800 cmd,
2801 sess,
2802 archive_builder_builder,
2803 codegen_results,
2804 tmpdir,
2805 cnum,
2806 &bundled_libs,
2807 );
2808 }
2809 }
2810 Linkage::Dynamic => {
2811 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2812 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2813 }
2814 }
2815
2816 let link_static = link_static_crate;
2825 let link_dynamic = false;
2827 add_native_libs_from_crate(
2828 cmd,
2829 sess,
2830 archive_builder_builder,
2831 codegen_results,
2832 tmpdir,
2833 &bundled_libs,
2834 cnum,
2835 link_static,
2836 link_dynamic,
2837 link_output_kind,
2838 );
2839 }
2840}
2841
2842fn add_upstream_native_libraries(
2843 cmd: &mut dyn Linker,
2844 sess: &Session,
2845 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2846 codegen_results: &CodegenResults,
2847 tmpdir: &Path,
2848 link_output_kind: LinkOutputKind,
2849) {
2850 for &cnum in &codegen_results.crate_info.used_crates {
2851 let link_static = false;
2857 let link_dynamic = true;
2865 add_native_libs_from_crate(
2866 cmd,
2867 sess,
2868 archive_builder_builder,
2869 codegen_results,
2870 tmpdir,
2871 &Default::default(),
2872 cnum,
2873 link_static,
2874 link_dynamic,
2875 link_output_kind,
2876 );
2877 }
2878}
2879
2880fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2890 let sysroot_lib_path = &sess.target_tlib_path.dir;
2891 let canonical_sysroot_lib_path =
2892 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2893
2894 let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2895 if canonical_lib_dir == canonical_sysroot_lib_path {
2896 sysroot_lib_path.clone()
2898 } else {
2899 fix_windows_verbatim_for_gcc(lib_dir)
2900 }
2901}
2902
2903fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2904 if let Some(dir) = path.parent() {
2905 let file_name = path.file_name().expect("library path has no file name component");
2906 rehome_sysroot_lib_dir(sess, dir).join(file_name)
2907 } else {
2908 fix_windows_verbatim_for_gcc(path)
2909 }
2910}
2911
2912fn add_static_crate(
2931 cmd: &mut dyn Linker,
2932 sess: &Session,
2933 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2934 codegen_results: &CodegenResults,
2935 tmpdir: &Path,
2936 cnum: CrateNum,
2937 bundled_lib_file_names: &FxIndexSet<Symbol>,
2938) {
2939 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2940 let cratepath = &src.rlib.as_ref().unwrap().0;
2941
2942 let mut link_upstream =
2943 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
2944
2945 if !are_upstream_rust_objects_already_included(sess)
2946 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2947 {
2948 link_upstream(cratepath);
2949 return;
2950 }
2951
2952 let dst = tmpdir.join(cratepath.file_name().unwrap());
2953 let name = cratepath.file_name().unwrap().to_str().unwrap();
2954 let name = &name[3..name.len() - 5]; let bundled_lib_file_names = bundled_lib_file_names.clone();
2956
2957 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2958 let canonical_name = name.replace('-', "_");
2959 let upstream_rust_objects_already_included =
2960 are_upstream_rust_objects_already_included(sess);
2961 let is_builtins =
2962 sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2963
2964 let mut archive = archive_builder_builder.new_archive_builder(sess);
2965 if let Err(error) = archive.add_archive(
2966 cratepath,
2967 Box::new(move |f| {
2968 if f == METADATA_FILENAME {
2969 return true;
2970 }
2971
2972 let canonical = f.replace('-', "_");
2973
2974 let is_rust_object =
2975 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
2976
2977 if upstream_rust_objects_already_included && is_rust_object && is_builtins {
2982 return true;
2983 }
2984
2985 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
2991 return true;
2992 }
2993
2994 false
2995 }),
2996 ) {
2997 sess.dcx()
2998 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
2999 }
3000 if archive.build(&dst) {
3001 link_upstream(&dst);
3002 }
3003 });
3004}
3005
3006fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3008 cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3009}
3010
3011fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3012 match lib.cfg {
3013 Some(ref cfg) => rustc_attr_parsing::cfg_matches(cfg, sess, CRATE_NODE_ID, None),
3014 None => true,
3015 }
3016}
3017
3018pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3019 match sess.lto() {
3020 config::Lto::Fat => true,
3021 config::Lto::Thin => {
3022 !sess.opts.cg.linker_plugin_lto.enabled()
3025 }
3026 config::Lto::No | config::Lto::ThinLocal => false,
3027 }
3028}
3029
3030fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3037 if !sess.target.is_like_darwin {
3038 return;
3039 }
3040 let LinkerFlavor::Darwin(cc, _) = flavor else {
3041 return;
3042 };
3043
3044 let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3046 let target_os = &*sess.target.os;
3047 let target_abi = &*sess.target.abi;
3048
3049 let ld64_arch = match llvm_arch {
3057 "armv7k" => "armv7k",
3058 "armv7s" => "armv7s",
3059 "arm64" => "arm64",
3060 "arm64e" => "arm64e",
3061 "arm64_32" => "arm64_32",
3062 "i386" | "i686" => "i386",
3066 "x86_64" => "x86_64",
3067 "x86_64h" => "x86_64h",
3068 _ => bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3069 };
3070
3071 if cc == Cc::No {
3072 cmd.link_args(&["-arch", ld64_arch]);
3082
3083 let platform_name = match (target_os, target_abi) {
3099 (os, "") => os,
3100 ("ios", "macabi") => "mac-catalyst",
3101 ("ios", "sim") => "ios-simulator",
3102 ("tvos", "sim") => "tvos-simulator",
3103 ("watchos", "sim") => "watchos-simulator",
3104 ("visionos", "sim") => "visionos-simulator",
3105 _ => bug!("invalid OS/ABI combination for Apple target: {target_os}, {target_abi}"),
3106 };
3107
3108 let min_version = sess.apple_deployment_target().fmt_full().to_string();
3109
3110 let sdk_version = &*min_version;
3143
3144 cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3153 } else {
3154 if target_os == "macos" {
3169 cmd.cc_args(&["-arch", ld64_arch]);
3174
3175 let version = sess.apple_deployment_target().fmt_full();
3178 cmd.cc_arg(&format!("-mmacosx-version-min={version}"));
3181
3182 } else {
3187 cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3188 }
3189 }
3190}
3191
3192fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3193 let os = &sess.target.os;
3194 if sess.target.vendor != "apple"
3195 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "visionos" | "macos")
3196 || !matches!(flavor, LinkerFlavor::Darwin(..))
3197 {
3198 return None;
3199 }
3200
3201 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
3202 return None;
3203 }
3204
3205 let sdk_root = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
3206
3207 match flavor {
3208 LinkerFlavor::Darwin(Cc::Yes, _) => {
3209 cmd.cc_arg("-isysroot");
3216 cmd.cc_arg(&sdk_root);
3217 }
3218 LinkerFlavor::Darwin(Cc::No, _) => {
3219 cmd.link_arg("-syslibroot");
3220 cmd.link_arg(&sdk_root);
3221 }
3222 _ => unreachable!(),
3223 }
3224
3225 Some(sdk_root)
3226}
3227
3228fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3229 if let Ok(sdkroot) = env::var("SDKROOT") {
3230 let p = PathBuf::from(&sdkroot);
3231
3232 match &*apple::sdk_name(&sess.target).to_lowercase() {
3241 "appletvos"
3242 if sdkroot.contains("TVSimulator.platform")
3243 || sdkroot.contains("MacOSX.platform") => {}
3244 "appletvsimulator"
3245 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3246 "iphoneos"
3247 if sdkroot.contains("iPhoneSimulator.platform")
3248 || sdkroot.contains("MacOSX.platform") => {}
3249 "iphonesimulator"
3250 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3251 }
3252 "macosx"
3253 if sdkroot.contains("iPhoneOS.platform")
3254 || sdkroot.contains("iPhoneSimulator.platform") => {}
3255 "watchos"
3256 if sdkroot.contains("WatchSimulator.platform")
3257 || sdkroot.contains("MacOSX.platform") => {}
3258 "watchsimulator"
3259 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3260 "xros"
3261 if sdkroot.contains("XRSimulator.platform")
3262 || sdkroot.contains("MacOSX.platform") => {}
3263 "xrsimulator"
3264 if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3265 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3267 _ => return Some(p),
3268 }
3269 }
3270
3271 apple::get_sdk_root(sess)
3272}
3273
3274fn add_lld_args(
3279 cmd: &mut dyn Linker,
3280 sess: &Session,
3281 flavor: LinkerFlavor,
3282 self_contained_components: LinkSelfContainedComponents,
3283) {
3284 debug!(
3285 "add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3286 flavor, self_contained_components,
3287 );
3288
3289 if !(flavor.uses_cc() && flavor.uses_lld()) {
3292 return;
3293 }
3294
3295 let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3301 let self_contained_target = self_contained_components.is_linker_enabled();
3302
3303 let self_contained_linker = self_contained_cli || self_contained_target;
3304 if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3305 let mut linker_path_exists = false;
3306 for path in sess.get_tools_search_paths(false) {
3307 let linker_path = path.join("gcc-ld");
3308 linker_path_exists |= linker_path.exists();
3309 cmd.cc_arg({
3310 let mut arg = OsString::from("-B");
3311 arg.push(linker_path);
3312 arg
3313 });
3314 }
3315 if !linker_path_exists {
3316 sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3319 }
3320 }
3321
3322 if !sess.target.is_like_wasm {
3329 cmd.cc_arg("-fuse-ld=lld");
3330
3331 if sess.target.llvm_target == "x86_64-unknown-linux-gnu" {
3357 cmd.link_arg("-znostart-stop-gc");
3358 }
3359 }
3360
3361 if !flavor.is_gnu() {
3362 if sess.target.linker_flavor != sess.host.linker_flavor {
3382 cmd.cc_arg(format!("--target={}", versioned_llvm_target(sess)));
3383 }
3384 }
3385}
3386
3387fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3394 use object::read::elf::{FileHeader, SectionHeader};
3395 use object::read::{ReadCache, ReadRef, Result};
3396 use object::{Endianness, elf};
3397
3398 fn elf_has_gold_version_note<'a>(
3399 elf: &impl FileHeader,
3400 data: impl ReadRef<'a>,
3401 ) -> Result<bool> {
3402 let endian = elf.endian()?;
3403
3404 let section =
3405 elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3406 if let Some((_, section)) = section {
3407 if let Some(mut notes) = section.notes(endian, data)? {
3408 return Ok(notes.any(|note| {
3409 note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3410 }));
3411 }
3412 }
3413
3414 Ok(false)
3415 }
3416
3417 let data = ReadCache::new(BufReader::new(File::open(path)?));
3418
3419 let was_linked_with_gold = if sess.target.pointer_width == 64 {
3420 let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3421 elf_has_gold_version_note(elf, &data)?
3422 } else if sess.target.pointer_width == 32 {
3423 let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3424 elf_has_gold_version_note(elf, &data)?
3425 } else {
3426 return Ok(());
3427 };
3428
3429 if was_linked_with_gold {
3430 let mut warn =
3431 sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3432 warn.help("consider using LLD or ld from GNU binutils instead");
3433 warn.emit();
3434 }
3435 Ok(())
3436}