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