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::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
11
12use cc::windows_registry;
13use itertools::Itertools;
14use regex::Regex;
15use rustc_arena::TypedArena;
16use rustc_ast::CRATE_NODE_ID;
17use rustc_data_structures::fx::FxIndexSet;
18use rustc_data_structures::memmap::Mmap;
19use rustc_data_structures::temp_dir::MaybeTempDir;
20use rustc_errors::{DiagCtxtHandle, LintDiagnostic};
21use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
22use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
23use rustc_macros::LintDiagnostic;
24use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
25use rustc_metadata::{
26 NativeLibSearchFallback, find_native_static_library, walk_native_lib_search_dirs,
27};
28use rustc_middle::bug;
29use rustc_middle::lint::lint_level;
30use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
31use rustc_middle::middle::dependency_format::Linkage;
32use rustc_middle::middle::exported_symbols::SymbolExportKind;
33use rustc_session::config::{
34 self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
35 OutputType, PrintKind, SplitDwarfKind, Strip,
36};
37use rustc_session::lint::builtin::LINKER_MESSAGES;
38use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
39use rustc_session::search_paths::PathKind;
40use rustc_session::utils::NativeLibKind;
41use rustc_session::{Session, filesearch};
44use rustc_span::Symbol;
45use rustc_target::spec::crt_objects::CrtObjects;
46use rustc_target::spec::{
47 BinaryFormat, Cc, LinkOutputKind, LinkSelfContainedComponents, LinkSelfContainedDefault,
48 LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy, RelocModel, RelroLevel,
49 SanitizerSet, SplitDebuginfo,
50};
51use tracing::{debug, info, warn};
52
53use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
54use super::command::Command;
55use super::linker::{self, Linker};
56use super::metadata::{MetadataPosition, create_wrapper_file};
57use super::rpath::{self, RPathConfig};
58use super::{apple, versioned_llvm_target};
59use crate::{
60 CodegenResults, CompiledModule, CrateInfo, NativeLib, errors, looks_like_rust_object_file,
61};
62
63pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
64 if let Err(e) = fs::remove_file(path) {
65 if e.kind() != io::ErrorKind::NotFound {
66 dcx.err(format!("failed to remove {}: {}", path.display(), e));
67 }
68 }
69}
70
71fn check_link_info_print_request(sess: &Session, crate_types: &[CrateType]) {
72 let print_native_static_libs =
73 sess.opts.prints.iter().any(|p| p.kind == PrintKind::NativeStaticLibs);
74 let has_staticlib = crate_types.iter().any(|ct| *ct == CrateType::Staticlib);
75 if print_native_static_libs {
76 if !has_staticlib {
77 sess.dcx()
78 .warn(format!("cannot output linkage information without staticlib crate-type"));
79 sess.dcx()
80 .note(format!("consider `--crate-type staticlib` to print linkage information"));
81 } else if !sess.opts.output_types.should_link() {
82 sess.dcx()
83 .warn(format!("cannot output linkage information when --emit link is not passed"));
84 }
85 }
86}
87
88pub fn link_binary(
91 sess: &Session,
92 archive_builder_builder: &dyn ArchiveBuilderBuilder,
93 codegen_results: CodegenResults,
94 outputs: &OutputFilenames,
95) {
96 let _timer = sess.timer("link_binary");
97 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
98 let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
99 for &crate_type in &codegen_results.crate_info.crate_types {
100 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
102 && !output_metadata
103 && crate_type == CrateType::Executable
104 {
105 continue;
106 }
107
108 if invalid_output_for_target(sess, crate_type) {
109 bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
110 }
111
112 sess.time("link_binary_check_files_are_writeable", || {
113 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
114 check_file_is_writeable(obj, sess);
115 }
116 });
117
118 if outputs.outputs.should_link() {
119 let tmpdir = TempDirBuilder::new()
120 .prefix("rustc")
121 .tempdir()
122 .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
123 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
124 let output = out_filename(
125 sess,
126 crate_type,
127 outputs,
128 codegen_results.crate_info.local_crate_name,
129 );
130 let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
131 let out_filename = output.file_for_writing(
132 outputs,
133 OutputType::Exe,
134 &crate_name,
135 sess.invocation_temp.as_deref(),
136 );
137 match crate_type {
138 CrateType::Rlib => {
139 let _timer = sess.timer("link_rlib");
140 info!("preparing rlib to {:?}", out_filename);
141 link_rlib(
142 sess,
143 archive_builder_builder,
144 &codegen_results,
145 RlibFlavor::Normal,
146 &path,
147 )
148 .build(&out_filename);
149 }
150 CrateType::Staticlib => {
151 link_staticlib(
152 sess,
153 archive_builder_builder,
154 &codegen_results,
155 &out_filename,
156 &path,
157 );
158 }
159 _ => {
160 link_natively(
161 sess,
162 archive_builder_builder,
163 crate_type,
164 &out_filename,
165 &codegen_results,
166 path.as_ref(),
167 );
168 }
169 }
170 if sess.opts.json_artifact_notifications {
171 sess.dcx().emit_artifact_notification(&out_filename, "link");
172 }
173
174 if sess.prof.enabled()
175 && let Some(artifact_name) = out_filename.file_name()
176 {
177 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
179
180 sess.prof.artifact_size(
181 "linked_artifact",
182 artifact_name.to_string_lossy(),
183 file_size,
184 );
185 }
186
187 if output.is_stdout() {
188 if output.is_tty() {
189 sess.dcx().emit_err(errors::BinaryOutputToTty {
190 shorthand: OutputType::Exe.shorthand(),
191 });
192 } else if let Err(e) = copy_to_stdout(&out_filename) {
193 sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
194 }
195 tempfiles_for_stdout_output.push(out_filename);
196 }
197 }
198 }
199
200 check_link_info_print_request(sess, &codegen_results.crate_info.crate_types);
201
202 sess.time("link_binary_remove_temps", || {
204 if sess.opts.cg.save_temps {
206 return;
207 }
208
209 let maybe_remove_temps_from_module =
210 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
211 if !preserve_objects && let Some(ref obj) = module.object {
212 ensure_removed(sess.dcx(), obj);
213 }
214
215 if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
216 ensure_removed(sess.dcx(), dwo_obj);
217 }
218 };
219
220 let remove_temps_from_module =
221 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
222
223 if let Some(ref metadata_module) = codegen_results.metadata_module {
225 remove_temps_from_module(metadata_module);
226 }
227
228 if let Some(ref allocator_module) = codegen_results.allocator_module {
229 remove_temps_from_module(allocator_module);
230 }
231
232 for temp in tempfiles_for_stdout_output {
234 ensure_removed(sess.dcx(), &temp);
235 }
236
237 if !sess.opts.output_types.should_link() {
240 return;
241 }
242
243 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
245 debug!(?preserve_objects, ?preserve_dwarf_objects);
246
247 for module in &codegen_results.modules {
248 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
249 }
250 });
251}
252
253pub fn each_linked_rlib(
256 info: &CrateInfo,
257 crate_type: Option<CrateType>,
258 f: &mut dyn FnMut(CrateNum, &Path),
259) -> Result<(), errors::LinkRlibError> {
260 let fmts = if let Some(crate_type) = crate_type {
261 let Some(fmts) = info.dependency_formats.get(&crate_type) else {
262 return Err(errors::LinkRlibError::MissingFormat);
263 };
264
265 fmts
266 } else {
267 let mut dep_formats = info.dependency_formats.iter();
268 let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
269 if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
270 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
271 ty1: format!("{ty1:?}"),
272 ty2: format!("{ty2:?}"),
273 list1: format!("{list1:?}"),
274 list2: format!("{list2:?}"),
275 });
276 }
277 list1
278 };
279
280 let used_dep_crates = info.used_crates.iter();
281 for &cnum in used_dep_crates {
282 match fmts.get(cnum) {
283 Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
284 Some(_) => {}
285 None => return Err(errors::LinkRlibError::MissingFormat),
286 }
287 let crate_name = info.crate_name[&cnum];
288 let used_crate_source = &info.used_crate_source[&cnum];
289 if let Some((path, _)) = &used_crate_source.rlib {
290 f(cnum, path);
291 } else if used_crate_source.rmeta.is_some() {
292 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
293 } else {
294 return Err(errors::LinkRlibError::NotFound { crate_name });
295 }
296 }
297 Ok(())
298}
299
300fn link_rlib<'a>(
306 sess: &'a Session,
307 archive_builder_builder: &dyn ArchiveBuilderBuilder,
308 codegen_results: &CodegenResults,
309 flavor: RlibFlavor,
310 tmpdir: &MaybeTempDir,
311) -> Box<dyn ArchiveBuilder + 'a> {
312 let mut ab = archive_builder_builder.new_archive_builder(sess);
313
314 let trailing_metadata = match flavor {
315 RlibFlavor::Normal => {
316 let (metadata, metadata_position) = create_wrapper_file(
317 sess,
318 ".rmeta".to_string(),
319 codegen_results.metadata.stub_or_full(),
320 );
321 let metadata = emit_wrapper_file(sess, &metadata, tmpdir, METADATA_FILENAME);
322 match metadata_position {
323 MetadataPosition::First => {
324 ab.add_file(&metadata);
330 None
331 }
332 MetadataPosition::Last => Some(metadata),
333 }
334 }
335
336 RlibFlavor::StaticlibBase => None,
337 };
338
339 for m in &codegen_results.modules {
340 if let Some(obj) = m.object.as_ref() {
341 ab.add_file(obj);
342 }
343
344 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
345 ab.add_file(dwarf_obj);
346 }
347 }
348
349 match flavor {
350 RlibFlavor::Normal => {}
351 RlibFlavor::StaticlibBase => {
352 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
353 if let Some(obj) = obj {
354 ab.add_file(obj);
355 }
356 }
357 }
358
359 let mut packed_bundled_libs = Vec::new();
361
362 for lib in codegen_results.crate_info.used_libraries.iter() {
379 let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
380 continue;
381 };
382 if flavor == RlibFlavor::Normal
383 && let Some(filename) = lib.filename
384 {
385 let path = find_native_static_library(filename.as_str(), true, sess);
386 let src = read(path)
387 .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
388 let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
389 let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
390 packed_bundled_libs.push(wrapper_file);
391 } else {
392 let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
393 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
394 sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
395 });
396 }
397 }
398
399 if sess.target.is_like_windows {
403 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
404 sess,
405 archive_builder_builder,
406 codegen_results.crate_info.used_libraries.iter(),
407 tmpdir.as_ref(),
408 true,
409 ) {
410 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
411 sess.dcx()
412 .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
413 });
414 }
415 }
416
417 if let Some(trailing_metadata) = trailing_metadata {
418 ab.add_file(&trailing_metadata);
444 }
445
446 for lib in packed_bundled_libs {
449 ab.add_file(&lib)
450 }
451
452 ab
453}
454
455fn link_staticlib(
467 sess: &Session,
468 archive_builder_builder: &dyn ArchiveBuilderBuilder,
469 codegen_results: &CodegenResults,
470 out_filename: &Path,
471 tempdir: &MaybeTempDir,
472) {
473 info!("preparing staticlib to {:?}", out_filename);
474 let mut ab = link_rlib(
475 sess,
476 archive_builder_builder,
477 codegen_results,
478 RlibFlavor::StaticlibBase,
479 tempdir,
480 );
481 let mut all_native_libs = vec![];
482
483 let res = each_linked_rlib(
484 &codegen_results.crate_info,
485 Some(CrateType::Staticlib),
486 &mut |cnum, path| {
487 let lto = are_upstream_rust_objects_already_included(sess)
488 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
489
490 let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
491 let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
492 let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
493
494 let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
495 ab.add_archive(
496 path,
497 Box::new(move |fname: &str| {
498 if fname == METADATA_FILENAME {
500 return true;
501 }
502
503 if lto && looks_like_rust_object_file(fname) {
505 return true;
506 }
507
508 if bundled_libs.contains(&Symbol::intern(fname)) {
510 return true;
511 }
512
513 false
514 }),
515 )
516 .unwrap();
517
518 archive_builder_builder
519 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
520 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
521
522 for filename in relevant_libs.iter() {
523 let joined = tempdir.as_ref().join(filename.as_str());
524 let path = joined.as_path();
525 ab.add_archive(path, Box::new(|_| false)).unwrap();
526 }
527
528 all_native_libs
529 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
530 },
531 );
532 if let Err(e) = res {
533 sess.dcx().emit_fatal(e);
534 }
535
536 ab.build(out_filename);
537
538 let crates = codegen_results.crate_info.used_crates.iter();
539
540 let fmts = codegen_results
541 .crate_info
542 .dependency_formats
543 .get(&CrateType::Staticlib)
544 .expect("no dependency formats for staticlib");
545
546 let mut all_rust_dylibs = vec![];
547 for &cnum in crates {
548 let Some(Linkage::Dynamic) = fmts.get(cnum) else {
549 continue;
550 };
551 let crate_name = codegen_results.crate_info.crate_name[&cnum];
552 let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
553 if let Some((path, _)) = &used_crate_source.dylib {
554 all_rust_dylibs.push(&**path);
555 } else if used_crate_source.rmeta.is_some() {
556 sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
557 } else {
558 sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
559 }
560 }
561
562 all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
563
564 for print in &sess.opts.prints {
565 if print.kind == PrintKind::NativeStaticLibs {
566 print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
567 }
568 }
569}
570
571fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
574 let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
575 dwp_out_filename.push(".dwp");
576 debug!(?dwp_out_filename, ?executable_out_filename);
577
578 #[derive(Default)]
579 struct ThorinSession<Relocations> {
580 arena_data: TypedArena<Vec<u8>>,
581 arena_mmap: TypedArena<Mmap>,
582 arena_relocations: TypedArena<Relocations>,
583 }
584
585 impl<Relocations> ThorinSession<Relocations> {
586 fn alloc_mmap(&self, data: Mmap) -> &Mmap {
587 &*self.arena_mmap.alloc(data)
588 }
589 }
590
591 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
592 fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
593 &*self.arena_data.alloc(data)
594 }
595
596 fn alloc_relocation(&self, data: Relocations) -> &Relocations {
597 &*self.arena_relocations.alloc(data)
598 }
599
600 fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
601 let file = File::open(&path)?;
602 let mmap = (unsafe { Mmap::map(file) })?;
603 Ok(self.alloc_mmap(mmap))
604 }
605 }
606
607 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
608 let thorin_sess = ThorinSession::default();
609 let mut package = thorin::DwarfPackage::new(&thorin_sess);
610
611 match sess.opts.unstable_opts.split_dwarf_kind {
613 SplitDwarfKind::Single => {
614 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
615 package.add_input_object(input_obj)?;
616 }
617 }
618 SplitDwarfKind::Split => {
619 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
620 package.add_input_object(input_obj)?;
621 }
622 }
623 }
624
625 let input_rlibs = cg_results
627 .crate_info
628 .used_crate_source
629 .items()
630 .filter_map(|(_, csource)| csource.rlib.as_ref())
631 .map(|(path, _)| path)
632 .into_sorted_stable_ord();
633
634 for input_rlib in input_rlibs {
635 debug!(?input_rlib);
636 package.add_input_object(input_rlib)?;
637 }
638
639 package.add_executable(
649 executable_out_filename,
650 thorin::MissingReferencedObjectBehaviour::Skip,
651 )?;
652
653 let output_stream = BufWriter::new(
654 OpenOptions::new()
655 .read(true)
656 .write(true)
657 .create(true)
658 .truncate(true)
659 .open(dwp_out_filename)?,
660 );
661 let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
662 package.finish()?.emit(&mut output_stream)?;
663 output_stream.result()?;
664 output_stream.into_inner().flush()?;
665
666 Ok(())
667 }) {
668 Ok(()) => {}
669 Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
670 }
671}
672
673#[derive(LintDiagnostic)]
674#[diag(codegen_ssa_linker_output)]
675struct LinkerOutput {
678 inner: String,
679}
680
681fn link_natively(
686 sess: &Session,
687 archive_builder_builder: &dyn ArchiveBuilderBuilder,
688 crate_type: CrateType,
689 out_filename: &Path,
690 codegen_results: &CodegenResults,
691 tmpdir: &Path,
692) {
693 info!("preparing {:?} to {:?}", crate_type, out_filename);
694 let (linker_path, flavor) = linker_and_flavor(sess);
695 let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
696
697 let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
702 let archive_member =
703 should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
704 let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
705
706 let mut cmd = linker_with_args(
707 &linker_path,
708 flavor,
709 sess,
710 archive_builder_builder,
711 crate_type,
712 tmpdir,
713 temp_filename,
714 codegen_results,
715 self_contained_components,
716 );
717
718 linker::disable_localization(&mut cmd);
719
720 for (k, v) in sess.target.link_env.as_ref() {
721 cmd.env(k.as_ref(), v.as_ref());
722 }
723 for k in sess.target.link_env_remove.as_ref() {
724 cmd.env_remove(k.as_ref());
725 }
726
727 for print in &sess.opts.prints {
728 if print.kind == PrintKind::LinkArgs {
729 let content = format!("{cmd:?}\n");
730 print.out.overwrite(&content, sess);
731 }
732 }
733
734 sess.dcx().abort_if_errors();
736
737 info!("{cmd:?}");
739 let unknown_arg_regex =
740 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
741 let mut prog;
742 loop {
743 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
744 let Ok(ref output) = prog else {
745 break;
746 };
747 if output.status.success() {
748 break;
749 }
750 let mut out = output.stderr.clone();
751 out.extend(&output.stdout);
752 let out = String::from_utf8_lossy(&out);
753
754 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
761 && unknown_arg_regex.is_match(&out)
762 && out.contains("-no-pie")
763 && cmd.get_args().iter().any(|e| e == "-no-pie")
764 {
765 info!("linker output: {:?}", out);
766 warn!("Linker does not support -no-pie command line option. Retrying without.");
767 for arg in cmd.take_args() {
768 if arg != "-no-pie" {
769 cmd.arg(arg);
770 }
771 }
772 info!("{cmd:?}");
773 continue;
774 }
775
776 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))
782 && unknown_arg_regex.is_match(&out)
783 && out.contains("-fuse-ld=lld")
784 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
785 {
786 info!("linker output: {:?}", out);
787 info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
788 for arg in cmd.take_args() {
789 if arg.to_string_lossy() != "-fuse-ld=lld" {
790 cmd.arg(arg);
791 }
792 }
793 info!("{cmd:?}");
794 continue;
795 }
796
797 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
800 && unknown_arg_regex.is_match(&out)
801 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
802 && cmd.get_args().iter().any(|e| e == "-static-pie")
803 {
804 info!("linker output: {:?}", out);
805 warn!(
806 "Linker does not support -static-pie command line option. Retrying with -static instead."
807 );
808 let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
810 let opts = &sess.target;
811 let pre_objects = if self_contained_crt_objects {
812 &opts.pre_link_objects_self_contained
813 } else {
814 &opts.pre_link_objects
815 };
816 let post_objects = if self_contained_crt_objects {
817 &opts.post_link_objects_self_contained
818 } else {
819 &opts.post_link_objects
820 };
821 let get_objects = |objects: &CrtObjects, kind| {
822 objects
823 .get(&kind)
824 .iter()
825 .copied()
826 .flatten()
827 .map(|obj| {
828 get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
829 })
830 .collect::<Vec<_>>()
831 };
832 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
833 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
834 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
835 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
836 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
839 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
840 for arg in cmd.take_args() {
841 if arg == "-static-pie" {
842 cmd.arg("-static");
844 } else if pre_objects_static_pie.contains(&arg) {
845 cmd.args(mem::take(&mut pre_objects_static));
847 } else if post_objects_static_pie.contains(&arg) {
848 cmd.args(mem::take(&mut post_objects_static));
850 } else {
851 cmd.arg(arg);
852 }
853 }
854 info!("{cmd:?}");
855 continue;
856 }
857
858 break;
859 }
860
861 match prog {
862 Ok(prog) => {
863 let is_msvc_link_exe = sess.target.is_like_msvc
864 && flavor == LinkerFlavor::Msvc(Lld::No)
865 && linker_path.to_str() == Some("link.exe");
867
868 if !prog.status.success() {
869 let mut output = prog.stderr.clone();
870 output.extend_from_slice(&prog.stdout);
871 let escaped_output = escape_linker_output(&output, flavor);
872 let err = errors::LinkingFailed {
873 linker_path: &linker_path,
874 exit_status: prog.status,
875 command: cmd,
876 escaped_output,
877 verbose: sess.opts.verbose,
878 sysroot_dir: sess.sysroot.clone(),
879 };
880 sess.dcx().emit_err(err);
881 if let Some(code) = prog.status.code() {
885 if is_msvc_link_exe && (code < 1000 || code > 9999) {
888 let is_vs_installed = windows_registry::find_vs_version().is_ok();
889 let has_linker =
890 windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
891
892 sess.dcx().emit_note(errors::LinkExeUnexpectedError);
893 if is_vs_installed && has_linker {
894 sess.dcx().emit_note(errors::RepairVSBuildTools);
896 sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
897 } else if is_vs_installed {
898 sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
900 } else {
901 sess.dcx().emit_note(errors::VisualStudioNotInstalled);
903 }
904 }
905 }
906
907 sess.dcx().abort_if_errors();
908 }
909
910 let stderr = escape_string(&prog.stderr);
911 let mut stdout = escape_string(&prog.stdout);
912 info!("linker stderr:\n{}", &stderr);
913 info!("linker stdout:\n{}", &stdout);
914
915 if is_msvc_link_exe {
918 if let Ok(str) = str::from_utf8(&prog.stdout) {
919 let mut output = String::with_capacity(str.len());
920 for line in stdout.lines() {
921 if line.starts_with(" Creating library")
922 || line.starts_with("Generating code")
923 || line.starts_with("Finished generating code")
924 {
925 continue;
926 }
927 output += line;
928 output += "\r\n"
929 }
930 stdout = escape_string(output.trim().as_bytes())
931 }
932 }
933
934 let level = codegen_results.crate_info.lint_levels.linker_messages;
935 let lint = |msg| {
936 lint_level(sess, LINKER_MESSAGES, level, None, |diag| {
937 LinkerOutput { inner: msg }.decorate_lint(diag)
938 })
939 };
940
941 if !prog.stderr.is_empty() {
942 let stderr = stderr
944 .strip_prefix("warning: ")
945 .unwrap_or(&stderr)
946 .replace(": warning: ", ": ");
947 lint(format!("linker stderr: {stderr}"));
948 }
949 if !stdout.is_empty() {
950 lint(format!("linker stdout: {}", stdout))
951 }
952 }
953 Err(e) => {
954 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
955
956 let err = if linker_not_found {
957 sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
958 } else {
959 sess.dcx().emit_err(errors::UnableToExeLinker {
960 linker_path,
961 error: e,
962 command_formatted: format!("{cmd:?}"),
963 })
964 };
965
966 if sess.target.is_like_msvc && linker_not_found {
967 sess.dcx().emit_note(errors::MsvcMissingLinker);
968 sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
969 sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
970 }
971 err.raise_fatal();
972 }
973 }
974
975 match sess.split_debuginfo() {
976 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
979
980 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
983
984 SplitDebuginfo::Packed if sess.target.is_like_darwin => {
988 let prog = Command::new("dsymutil").arg(out_filename).output();
989 match prog {
990 Ok(prog) => {
991 if !prog.status.success() {
992 let mut output = prog.stderr.clone();
993 output.extend_from_slice(&prog.stdout);
994 sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
995 status: prog.status,
996 output: escape_string(&output),
997 });
998 }
999 }
1000 Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1001 }
1002 }
1003
1004 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1007
1008 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1014 }
1015
1016 let strip = sess.opts.cg.strip;
1017
1018 if sess.target.is_like_darwin {
1019 let stripcmd = "rust-objcopy";
1020 match (strip, crate_type) {
1021 (Strip::Debuginfo, _) => {
1022 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1023 }
1024 (
1026 Strip::Symbols,
1027 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1028 ) => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1029 (Strip::Symbols, _) => {
1030 strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1031 }
1032 (Strip::None, _) => {}
1033 }
1034 }
1035
1036 if sess.target.is_like_solaris {
1037 let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1044 match strip {
1045 Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1047 Strip::Symbols => {}
1049 Strip::None => {}
1050 }
1051 }
1052
1053 if sess.target.is_like_aix {
1054 if !sess.host.is_like_aix {
1056 sess.dcx().emit_warn(errors::AixStripNotUsed);
1057 }
1058 let stripcmd = "/usr/bin/strip";
1059 match strip {
1060 Strip::Debuginfo => {
1061 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-l"])
1063 }
1064 Strip::Symbols => {
1065 strip_with_external_utility(sess, stripcmd, out_filename, &["-X32_64", "-r"])
1067 }
1068 Strip::None => {}
1069 }
1070 }
1071
1072 if should_archive {
1073 let mut ab = archive_builder_builder.new_archive_builder(sess);
1074 ab.add_file(temp_filename);
1075 ab.build(out_filename);
1076 }
1077}
1078
1079fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1080 let mut cmd = Command::new(util);
1081 cmd.args(options);
1082
1083 let mut new_path = sess.get_tools_search_paths(false);
1084 if let Some(path) = env::var_os("PATH") {
1085 new_path.extend(env::split_paths(&path));
1086 }
1087 cmd.env("PATH", env::join_paths(new_path).unwrap());
1088
1089 let prog = cmd.arg(out_filename).output();
1090 match prog {
1091 Ok(prog) => {
1092 if !prog.status.success() {
1093 let mut output = prog.stderr.clone();
1094 output.extend_from_slice(&prog.stdout);
1095 sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1096 util,
1097 status: prog.status,
1098 output: escape_string(&output),
1099 });
1100 }
1101 }
1102 Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1103 }
1104}
1105
1106fn escape_string(s: &[u8]) -> String {
1107 match str::from_utf8(s) {
1108 Ok(s) => s.to_owned(),
1109 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1110 }
1111}
1112
1113#[cfg(not(windows))]
1114fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1115 escape_string(s)
1116}
1117
1118#[cfg(windows)]
1121fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1122 if flavour != LinkerFlavor::Msvc(Lld::No) {
1124 return escape_string(s);
1125 }
1126 match str::from_utf8(s) {
1127 Ok(s) => return s.to_owned(),
1128 Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1129 Some(s) => s,
1130 None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1132 },
1133 }
1134}
1135
1136#[cfg(windows)]
1138mod win {
1139 use windows::Win32::Globalization::{
1140 CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1141 LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1142 };
1143
1144 pub(super) fn oem_code_page() -> u32 {
1147 unsafe {
1148 let mut cp: u32 = 0;
1149 let len = size_of::<u32>() / size_of::<u16>();
1152 let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1153 let len_written = GetLocaleInfoEx(
1154 LOCALE_NAME_SYSTEM_DEFAULT,
1155 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1156 Some(data),
1157 );
1158 if len_written as usize == len { cp } else { CP_OEMCP }
1159 }
1160 }
1161 pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1170 if s.len() > isize::MAX as usize {
1172 return None;
1173 }
1174 let flags = MB_ERR_INVALID_CHARS;
1176 let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1179 if len > 0 {
1180 let mut utf16 = vec![0; len as usize];
1181 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1182 if len > 0 {
1183 return utf16.get(..len as usize).map(String::from_utf16_lossy);
1184 }
1185 }
1186 None
1187 }
1188}
1189
1190fn add_sanitizer_libraries(
1191 sess: &Session,
1192 flavor: LinkerFlavor,
1193 crate_type: CrateType,
1194 linker: &mut dyn Linker,
1195) {
1196 if sess.target.is_like_android {
1197 return;
1200 }
1201
1202 if sess.opts.unstable_opts.external_clangrt {
1203 return;
1206 }
1207
1208 if matches!(crate_type, CrateType::Rlib | CrateType::Staticlib) {
1209 return;
1210 }
1211
1212 if matches!(
1217 crate_type,
1218 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1219 ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1220 {
1221 return;
1222 }
1223
1224 let sanitizer = sess.opts.unstable_opts.sanitizer;
1225 if sanitizer.contains(SanitizerSet::ADDRESS) {
1226 link_sanitizer_runtime(sess, flavor, linker, "asan");
1227 }
1228 if sanitizer.contains(SanitizerSet::DATAFLOW) {
1229 link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1230 }
1231 if sanitizer.contains(SanitizerSet::LEAK)
1232 && !sanitizer.contains(SanitizerSet::ADDRESS)
1233 && !sanitizer.contains(SanitizerSet::HWADDRESS)
1234 {
1235 link_sanitizer_runtime(sess, flavor, linker, "lsan");
1236 }
1237 if sanitizer.contains(SanitizerSet::MEMORY) {
1238 link_sanitizer_runtime(sess, flavor, linker, "msan");
1239 }
1240 if sanitizer.contains(SanitizerSet::THREAD) {
1241 link_sanitizer_runtime(sess, flavor, linker, "tsan");
1242 }
1243 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1244 link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1245 }
1246 if sanitizer.contains(SanitizerSet::SAFESTACK) {
1247 link_sanitizer_runtime(sess, flavor, linker, "safestack");
1248 }
1249}
1250
1251fn link_sanitizer_runtime(
1252 sess: &Session,
1253 flavor: LinkerFlavor,
1254 linker: &mut dyn Linker,
1255 name: &str,
1256) {
1257 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1258 let path = sess.target_tlib_path.dir.join(filename);
1259 if path.exists() {
1260 sess.target_tlib_path.dir.clone()
1261 } else {
1262 let default_sysroot = filesearch::get_or_default_sysroot();
1263 let default_tlib =
1264 filesearch::make_target_lib_path(&default_sysroot, sess.opts.target_triple.tuple());
1265 default_tlib
1266 }
1267 }
1268
1269 let channel =
1270 option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
1271
1272 if sess.target.is_like_darwin {
1273 let filename = format!("rustc{channel}_rt.{name}");
1278 let path = find_sanitizer_runtime(sess, &filename);
1279 let rpath = path.to_str().expect("non-utf8 component in path");
1280 linker.link_args(&["-rpath", rpath]);
1281 linker.link_dylib_by_name(&filename, false, true);
1282 } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1283 linker.link_arg("/INFERASANLIBS");
1286 } else {
1287 let filename = format!("librustc{channel}_rt.{name}.a");
1288 let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1289 linker.link_staticlib_by_path(&path, true);
1290 }
1291}
1292
1293pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1304 !sess.target.no_builtins
1308 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1309}
1310
1311pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1313 fn infer_from(
1314 sess: &Session,
1315 linker: Option<PathBuf>,
1316 flavor: Option<LinkerFlavor>,
1317 features: LinkerFeaturesCli,
1318 ) -> Option<(PathBuf, LinkerFlavor)> {
1319 let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1320 match (linker, flavor) {
1321 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1322 (None, Some(flavor)) => Some((
1324 PathBuf::from(match flavor {
1325 LinkerFlavor::Gnu(Cc::Yes, _)
1326 | LinkerFlavor::Darwin(Cc::Yes, _)
1327 | LinkerFlavor::WasmLld(Cc::Yes)
1328 | LinkerFlavor::Unix(Cc::Yes) => {
1329 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1330 "gcc"
1337 } else {
1338 "cc"
1339 }
1340 }
1341 LinkerFlavor::Gnu(_, Lld::Yes)
1342 | LinkerFlavor::Darwin(_, Lld::Yes)
1343 | LinkerFlavor::WasmLld(..)
1344 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1345 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1346 "ld"
1347 }
1348 LinkerFlavor::Msvc(..) => "link.exe",
1349 LinkerFlavor::EmCc => {
1350 if cfg!(windows) {
1351 "emcc.bat"
1352 } else {
1353 "emcc"
1354 }
1355 }
1356 LinkerFlavor::Bpf => "bpf-linker",
1357 LinkerFlavor::Llbc => "llvm-bitcode-linker",
1358 LinkerFlavor::Ptx => "rust-ptx-linker",
1359 }),
1360 flavor,
1361 )),
1362 (Some(linker), None) => {
1363 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1364 sess.dcx().emit_fatal(errors::LinkerFileStem);
1365 });
1366 let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1367 let flavor = adjust_flavor_to_features(flavor, features);
1368 Some((linker, flavor))
1369 }
1370 (None, None) => None,
1371 }
1372 }
1373
1374 fn adjust_flavor_to_features(
1379 flavor: LinkerFlavor,
1380 features: LinkerFeaturesCli,
1381 ) -> LinkerFlavor {
1382 if features.enabled.contains(LinkerFeatures::LLD) {
1384 flavor.with_lld_enabled()
1385 } else if features.disabled.contains(LinkerFeatures::LLD) {
1386 flavor.with_lld_disabled()
1387 } else {
1388 flavor
1389 }
1390 }
1391
1392 let features = sess.opts.unstable_opts.linker_features;
1393
1394 let linker_flavor = match sess.opts.cg.linker_flavor {
1397 Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1399 Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1400 _ => sess
1402 .opts
1403 .cg
1404 .linker_flavor
1405 .map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
1406 };
1407 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1408 return ret;
1409 }
1410
1411 if let Some(ret) = infer_from(
1412 sess,
1413 sess.target.linker.as_deref().map(PathBuf::from),
1414 Some(sess.target.linker_flavor),
1415 features,
1416 ) {
1417 return ret;
1418 }
1419
1420 bug!("Not enough information provided to determine how to invoke the linker");
1421}
1422
1423fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1427 if sess.opts.debuginfo == config::DebugInfo::None {
1429 return (false, false);
1430 }
1431
1432 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1433 (SplitDebuginfo::Off, _) => (false, false),
1435 (SplitDebuginfo::Packed, _) => (false, false),
1438 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1441 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1445 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1446 }
1447}
1448
1449#[derive(PartialEq)]
1450enum RlibFlavor {
1451 Normal,
1452 StaticlibBase,
1453}
1454
1455fn print_native_static_libs(
1456 sess: &Session,
1457 out: &OutFileName,
1458 all_native_libs: &[NativeLib],
1459 all_rust_dylibs: &[&Path],
1460) {
1461 let mut lib_args: Vec<_> = all_native_libs
1462 .iter()
1463 .filter(|l| relevant_lib(sess, l))
1464 .filter_map(|lib| {
1465 let name = lib.name;
1466 match lib.kind {
1467 NativeLibKind::Static { bundle: Some(false), .. }
1468 | NativeLibKind::Dylib { .. }
1469 | NativeLibKind::Unspecified => {
1470 let verbatim = lib.verbatim;
1471 if sess.target.is_like_msvc {
1472 let (prefix, suffix) = sess.staticlib_components(verbatim);
1473 Some(format!("{prefix}{name}{suffix}"))
1474 } else if sess.target.linker_flavor.is_gnu() {
1475 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1476 } else {
1477 Some(format!("-l{name}"))
1478 }
1479 }
1480 NativeLibKind::Framework { .. } => {
1481 Some(format!("-framework {name}"))
1483 }
1484 NativeLibKind::Static { bundle: None | Some(true), .. }
1486 | NativeLibKind::LinkArg
1487 | NativeLibKind::WasmImportModule
1488 | NativeLibKind::RawDylib => None,
1489 }
1490 })
1491 .dedup()
1493 .collect();
1494 for path in all_rust_dylibs {
1495 let parent = path.parent();
1500 if let Some(dir) = parent {
1501 let dir = fix_windows_verbatim_for_gcc(dir);
1502 if sess.target.is_like_msvc {
1503 let mut arg = String::from("/LIBPATH:");
1504 arg.push_str(&dir.display().to_string());
1505 lib_args.push(arg);
1506 } else {
1507 lib_args.push("-L".to_owned());
1508 lib_args.push(dir.display().to_string());
1509 }
1510 }
1511 let stem = path.file_stem().unwrap().to_str().unwrap();
1512 let lib = if let Some(lib) = stem.strip_prefix("lib")
1514 && !sess.target.is_like_windows
1515 {
1516 lib
1517 } else {
1518 stem
1519 };
1520 let path = parent.unwrap_or_else(|| Path::new(""));
1521 if sess.target.is_like_msvc {
1522 let name = format!("{lib}.dll.lib");
1527 if path.join(&name).exists() {
1528 lib_args.push(name);
1529 }
1530 } else {
1531 lib_args.push(format!("-l{lib}"));
1532 }
1533 }
1534
1535 match out {
1536 OutFileName::Real(path) => {
1537 out.overwrite(&lib_args.join(" "), sess);
1538 sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1539 }
1540 OutFileName::Stdout => {
1541 sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1542 sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
1545 }
1546 }
1547}
1548
1549fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1550 let file_path = sess.target_tlib_path.dir.join(name);
1551 if file_path.exists() {
1552 return file_path;
1553 }
1554 if self_contained {
1556 let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1557 if file_path.exists() {
1558 return file_path;
1559 }
1560 }
1561 for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1562 let file_path = search_path.dir.join(name);
1563 if file_path.exists() {
1564 return file_path;
1565 }
1566 }
1567 PathBuf::from(name)
1568}
1569
1570fn exec_linker(
1571 sess: &Session,
1572 cmd: &Command,
1573 out_filename: &Path,
1574 flavor: LinkerFlavor,
1575 tmpdir: &Path,
1576) -> io::Result<Output> {
1577 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1587 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1588 Ok(child) => {
1589 let output = child.wait_with_output();
1590 flush_linked_file(&output, out_filename)?;
1591 return output;
1592 }
1593 Err(ref e) if command_line_too_big(e) => {
1594 info!("command line to linker was too big: {}", e);
1595 }
1596 Err(e) => return Err(e),
1597 }
1598 }
1599
1600 info!("falling back to passing arguments to linker via an @-file");
1601 let mut cmd2 = cmd.clone();
1602 let mut args = String::new();
1603 for arg in cmd2.take_args() {
1604 args.push_str(
1605 &Escape {
1606 arg: arg.to_str().unwrap(),
1607 is_like_msvc: sess.target.is_like_msvc
1612 || (cfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1613 }
1614 .to_string(),
1615 );
1616 args.push('\n');
1617 }
1618 let file = tmpdir.join("linker-arguments");
1619 let bytes = if sess.target.is_like_msvc {
1620 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1621 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1623 out.push(c as u8);
1625 out.push((c >> 8) as u8);
1626 }
1627 out
1628 } else {
1629 args.into_bytes()
1630 };
1631 fs::write(&file, &bytes)?;
1632 cmd2.arg(format!("@{}", file.display()));
1633 info!("invoking linker {:?}", cmd2);
1634 let output = cmd2.output();
1635 flush_linked_file(&output, out_filename)?;
1636 return output;
1637
1638 #[cfg(not(windows))]
1639 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1640 Ok(())
1641 }
1642
1643 #[cfg(windows)]
1644 fn flush_linked_file(
1645 command_output: &io::Result<Output>,
1646 out_filename: &Path,
1647 ) -> io::Result<()> {
1648 if let &Ok(ref out) = command_output {
1657 if out.status.success() {
1658 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1659 of.sync_all()?;
1660 }
1661 }
1662 }
1663
1664 Ok(())
1665 }
1666
1667 #[cfg(unix)]
1668 fn command_line_too_big(err: &io::Error) -> bool {
1669 err.raw_os_error() == Some(::libc::E2BIG)
1670 }
1671
1672 #[cfg(windows)]
1673 fn command_line_too_big(err: &io::Error) -> bool {
1674 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1675 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1676 }
1677
1678 #[cfg(not(any(unix, windows)))]
1679 fn command_line_too_big(_: &io::Error) -> bool {
1680 false
1681 }
1682
1683 struct Escape<'a> {
1684 arg: &'a str,
1685 is_like_msvc: bool,
1686 }
1687
1688 impl<'a> fmt::Display for Escape<'a> {
1689 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1690 if self.is_like_msvc {
1691 write!(f, "\"")?;
1699 for c in self.arg.chars() {
1700 match c {
1701 '"' => write!(f, "\\{c}")?,
1702 c => write!(f, "{c}")?,
1703 }
1704 }
1705 write!(f, "\"")?;
1706 } else {
1707 for c in self.arg.chars() {
1718 match c {
1719 '\\' | ' ' => write!(f, "\\{c}")?,
1720 c => write!(f, "{c}")?,
1721 }
1722 }
1723 }
1724 Ok(())
1725 }
1726 }
1727}
1728
1729fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1730 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1731 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1732 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1733 LinkOutputKind::DynamicPicExe
1734 }
1735 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1736 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1737 LinkOutputKind::StaticPicExe
1738 }
1739 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1740 (_, true, _) => LinkOutputKind::StaticDylib,
1741 (_, false, _) => LinkOutputKind::DynamicDylib,
1742 };
1743
1744 let opts = &sess.target;
1746 let pic_exe_supported = opts.position_independent_executables;
1747 let static_pic_exe_supported = opts.static_position_independent_executables;
1748 let static_dylib_supported = opts.crt_static_allows_dylibs;
1749 match kind {
1750 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1751 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1752 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1753 _ => kind,
1754 }
1755}
1756
1757fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1759 if linker == Path::new("rust-lld") {
1761 return true;
1762 }
1763 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1764 linker.with_extension("exe")
1765 } else {
1766 linker.to_path_buf()
1767 };
1768 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1769 let full_path = dir.join(&linker_with_extension);
1770 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1772 return false;
1773 }
1774 }
1775 true
1776}
1777
1778fn self_contained_components(
1782 sess: &Session,
1783 crate_type: CrateType,
1784 linker: &Path,
1785) -> LinkSelfContainedComponents {
1786 let self_contained =
1789 if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1790 if sess.target.link_self_contained.is_disabled() {
1793 sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1794 }
1795 self_contained
1796 } else {
1797 match sess.target.link_self_contained {
1798 LinkSelfContainedDefault::False => false,
1799 LinkSelfContainedDefault::True => true,
1800
1801 LinkSelfContainedDefault::WithComponents(components) => {
1802 return components;
1805 }
1806
1807 LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1811 LinkSelfContainedDefault::InferredForMingw => {
1812 sess.host == sess.target
1813 && sess.target.vendor != "uwp"
1814 && detect_self_contained_mingw(sess, linker)
1815 }
1816 }
1817 };
1818 if self_contained {
1819 LinkSelfContainedComponents::all()
1820 } else {
1821 LinkSelfContainedComponents::empty()
1822 }
1823}
1824
1825fn add_pre_link_objects(
1827 cmd: &mut dyn Linker,
1828 sess: &Session,
1829 flavor: LinkerFlavor,
1830 link_output_kind: LinkOutputKind,
1831 self_contained: bool,
1832) {
1833 let opts = &sess.target;
1836 let empty = Default::default();
1837 let objects = if self_contained {
1838 &opts.pre_link_objects_self_contained
1839 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1840 &opts.pre_link_objects
1841 } else {
1842 &empty
1843 };
1844 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1845 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1846 }
1847}
1848
1849fn add_post_link_objects(
1851 cmd: &mut dyn Linker,
1852 sess: &Session,
1853 link_output_kind: LinkOutputKind,
1854 self_contained: bool,
1855) {
1856 let objects = if self_contained {
1857 &sess.target.post_link_objects_self_contained
1858 } else {
1859 &sess.target.post_link_objects
1860 };
1861 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1862 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1863 }
1864}
1865
1866fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1869 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1870 cmd.verbatim_args(args.iter().map(Deref::deref));
1871 }
1872
1873 cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1874}
1875
1876fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1878 match (crate_type, &sess.target.link_script) {
1879 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1880 if !sess.target.linker_flavor.is_gnu() {
1881 sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1882 }
1883
1884 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1885
1886 let path = tmpdir.join(file_name);
1887 if let Err(error) = fs::write(&path, script.as_ref()) {
1888 sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1889 }
1890
1891 cmd.link_arg("--script").link_arg(path);
1892 }
1893 _ => {}
1894 }
1895}
1896
1897fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1900 cmd.verbatim_args(&sess.opts.cg.link_args);
1901}
1902
1903fn add_late_link_args(
1906 cmd: &mut dyn Linker,
1907 sess: &Session,
1908 flavor: LinkerFlavor,
1909 crate_type: CrateType,
1910 codegen_results: &CodegenResults,
1911) {
1912 let any_dynamic_crate = crate_type == CrateType::Dylib
1913 || crate_type == CrateType::Sdylib
1914 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1915 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1916 });
1917 if any_dynamic_crate {
1918 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1919 cmd.verbatim_args(args.iter().map(Deref::deref));
1920 }
1921 } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1922 cmd.verbatim_args(args.iter().map(Deref::deref));
1923 }
1924 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1925 cmd.verbatim_args(args.iter().map(Deref::deref));
1926 }
1927}
1928
1929fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1932 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1933 cmd.verbatim_args(args.iter().map(Deref::deref));
1934 }
1935}
1936
1937fn add_linked_symbol_object(
1967 cmd: &mut dyn Linker,
1968 sess: &Session,
1969 tmpdir: &Path,
1970 symbols: &[(String, SymbolExportKind)],
1971) {
1972 if symbols.is_empty() {
1973 return;
1974 }
1975
1976 let Some(mut file) = super::metadata::create_object_file(sess) else {
1977 return;
1978 };
1979
1980 if file.format() == object::BinaryFormat::Coff {
1981 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1984
1985 file.set_mangling(object::write::Mangling::None);
1988 }
1989
1990 if file.format() == object::BinaryFormat::MachO {
1991 file.set_subsections_via_symbols();
1994 }
1995
1996 let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
1999 Some(file.add_section(
2000 file.segment_name(object::write::StandardSegment::Data).to_vec(),
2001 "__data".into(),
2002 object::SectionKind::Data,
2003 ))
2004 } else {
2005 None
2006 };
2007
2008 for (sym, kind) in symbols.iter() {
2009 let symbol = file.add_symbol(object::write::Symbol {
2010 name: sym.clone().into(),
2011 value: 0,
2012 size: 0,
2013 kind: match kind {
2014 SymbolExportKind::Text => object::SymbolKind::Text,
2015 SymbolExportKind::Data => object::SymbolKind::Data,
2016 SymbolExportKind::Tls => object::SymbolKind::Tls,
2017 },
2018 scope: object::SymbolScope::Unknown,
2019 weak: false,
2020 section: object::write::SymbolSection::Undefined,
2021 flags: object::SymbolFlags::None,
2022 });
2023
2024 if let Some(section) = ld64_section_helper {
2061 apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2062 .expect("failed adding relocation");
2063 }
2064 }
2065
2066 let path = tmpdir.join("symbols.o");
2067 let result = std::fs::write(&path, file.write().unwrap());
2068 if let Err(error) = result {
2069 sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2070 }
2071 cmd.add_object(&path);
2072}
2073
2074fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2076 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2077 cmd.add_object(obj);
2078 }
2079}
2080
2081fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2083 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
2084 cmd.add_object(obj);
2085 }
2086}
2087
2088fn add_local_crate_metadata_objects(
2090 cmd: &mut dyn Linker,
2091 crate_type: CrateType,
2092 codegen_results: &CodegenResults,
2093) {
2094 if matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro)
2098 && let Some(m) = &codegen_results.metadata_module
2099 && let Some(obj) = &m.object
2100 {
2101 cmd.add_object(obj);
2102 }
2103}
2104
2105fn add_library_search_dirs(
2107 cmd: &mut dyn Linker,
2108 sess: &Session,
2109 self_contained_components: LinkSelfContainedComponents,
2110 apple_sdk_root: Option<&Path>,
2111) {
2112 if !sess.opts.unstable_opts.link_native_libraries {
2113 return;
2114 }
2115
2116 let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2117 let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2118 if is_framework {
2119 cmd.framework_path(dir);
2120 } else {
2121 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2122 }
2123 ControlFlow::<()>::Continue(())
2124 });
2125}
2126
2127fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2130 match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2131 RelroLevel::Full => cmd.full_relro(),
2132 RelroLevel::Partial => cmd.partial_relro(),
2133 RelroLevel::Off => cmd.no_relro(),
2134 RelroLevel::None => {}
2135 }
2136}
2137
2138fn add_rpath_args(
2140 cmd: &mut dyn Linker,
2141 sess: &Session,
2142 codegen_results: &CodegenResults,
2143 out_filename: &Path,
2144) {
2145 if !sess.target.has_rpath {
2146 return;
2147 }
2148
2149 if sess.opts.cg.rpath {
2153 let libs = codegen_results
2154 .crate_info
2155 .used_crates
2156 .iter()
2157 .filter_map(|cnum| {
2158 codegen_results.crate_info.used_crate_source[cnum]
2159 .dylib
2160 .as_ref()
2161 .map(|(path, _)| &**path)
2162 })
2163 .collect::<Vec<_>>();
2164 let rpath_config = RPathConfig {
2165 libs: &*libs,
2166 out_filename: out_filename.to_path_buf(),
2167 is_like_darwin: sess.target.is_like_darwin,
2168 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2169 };
2170 cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2171 }
2172}
2173
2174fn linker_with_args(
2183 path: &Path,
2184 flavor: LinkerFlavor,
2185 sess: &Session,
2186 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2187 crate_type: CrateType,
2188 tmpdir: &Path,
2189 out_filename: &Path,
2190 codegen_results: &CodegenResults,
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(cmd, crate_type, codegen_results);
2266 add_local_crate_allocator_objects(cmd, codegen_results);
2267
2268 cmd.add_as_needed();
2277
2278 add_local_native_libraries(
2280 cmd,
2281 sess,
2282 archive_builder_builder,
2283 codegen_results,
2284 tmpdir,
2285 link_output_kind,
2286 );
2287
2288 add_upstream_rust_crates(
2290 cmd,
2291 sess,
2292 archive_builder_builder,
2293 codegen_results,
2294 crate_type,
2295 tmpdir,
2296 link_output_kind,
2297 );
2298
2299 add_upstream_native_libraries(
2301 cmd,
2302 sess,
2303 archive_builder_builder,
2304 codegen_results,
2305 tmpdir,
2306 link_output_kind,
2307 );
2308
2309 let raw_dylib_dir = tmpdir.join("raw-dylibs");
2311 if sess.target.binary_format == BinaryFormat::Elf {
2312 if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2317 sess.dcx().emit_fatal(errors::CreateTempDir { error })
2318 }
2319 cmd.include_path(&raw_dylib_dir);
2320 }
2321
2322 if sess.target.is_like_windows {
2324 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2325 sess,
2326 archive_builder_builder,
2327 codegen_results.crate_info.used_libraries.iter(),
2328 tmpdir,
2329 true,
2330 ) {
2331 cmd.add_object(&output_path);
2332 }
2333 } else {
2334 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2335 sess,
2336 codegen_results.crate_info.used_libraries.iter(),
2337 &raw_dylib_dir,
2338 ) {
2339 cmd.link_dylib_by_name(&link_path, true, false);
2341 }
2342 }
2343 let dependency_linkage = codegen_results
2348 .crate_info
2349 .dependency_formats
2350 .get(&crate_type)
2351 .expect("failed to find crate type in dependency format list");
2352
2353 #[allow(rustc::potential_query_instability)]
2355 let mut native_libraries_from_nonstatics = codegen_results
2356 .crate_info
2357 .native_libraries
2358 .iter()
2359 .filter_map(|(&cnum, libraries)| {
2360 if sess.target.is_like_windows {
2361 (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2362 } else {
2363 Some(libraries)
2364 }
2365 })
2366 .flatten()
2367 .collect::<Vec<_>>();
2368 native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
2369
2370 if sess.target.is_like_windows {
2371 for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2372 sess,
2373 archive_builder_builder,
2374 native_libraries_from_nonstatics,
2375 tmpdir,
2376 false,
2377 ) {
2378 cmd.add_object(&output_path);
2379 }
2380 } else {
2381 for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2382 sess,
2383 native_libraries_from_nonstatics,
2384 &raw_dylib_dir,
2385 ) {
2386 cmd.link_dylib_by_name(&link_path, true, false);
2388 }
2389 }
2390
2391 cmd.reset_per_library_state();
2394
2395 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2399
2400 add_order_independent_options(
2405 cmd,
2406 sess,
2407 link_output_kind,
2408 self_contained_components,
2409 flavor,
2410 crate_type,
2411 codegen_results,
2412 out_filename,
2413 tmpdir,
2414 );
2415
2416 add_user_defined_link_args(cmd, sess);
2420
2421 add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
2425
2426 add_post_link_args(cmd, sess, flavor);
2433
2434 cmd.take_cmd()
2435}
2436
2437fn add_order_independent_options(
2438 cmd: &mut dyn Linker,
2439 sess: &Session,
2440 link_output_kind: LinkOutputKind,
2441 self_contained_components: LinkSelfContainedComponents,
2442 flavor: LinkerFlavor,
2443 crate_type: CrateType,
2444 codegen_results: &CodegenResults,
2445 out_filename: &Path,
2446 tmpdir: &Path,
2447) {
2448 add_lld_args(cmd, sess, flavor, self_contained_components);
2450
2451 add_apple_link_args(cmd, sess, flavor);
2452
2453 let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
2454
2455 add_link_script(cmd, sess, tmpdir, crate_type);
2456
2457 if sess.target.os == "fuchsia"
2458 && crate_type == CrateType::Executable
2459 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2460 {
2461 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2462 "asan/"
2463 } else {
2464 ""
2465 };
2466 cmd.link_arg(format!("--dynamic-linker={prefix}ld.so.1"));
2467 }
2468
2469 if sess.target.eh_frame_header {
2470 cmd.add_eh_frame_header();
2471 }
2472
2473 cmd.add_no_exec();
2475
2476 if self_contained_components.is_crt_objects_enabled() {
2477 cmd.no_crt_objects();
2478 }
2479
2480 if sess.target.os == "emscripten" {
2481 cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2482 "-fwasm-exceptions"
2483 } else if sess.panic_strategy() == PanicStrategy::Abort {
2484 "-sDISABLE_EXCEPTION_CATCHING=1"
2485 } else {
2486 "-sDISABLE_EXCEPTION_CATCHING=0"
2487 });
2488 }
2489
2490 if flavor == LinkerFlavor::Llbc {
2491 cmd.link_args(&[
2492 "--target",
2493 &versioned_llvm_target(sess),
2494 "--target-cpu",
2495 &codegen_results.crate_info.target_cpu,
2496 ]);
2497 if codegen_results.crate_info.target_features.len() > 0 {
2498 cmd.link_arg(&format!(
2499 "--target-feature={}",
2500 &codegen_results.crate_info.target_features.join(",")
2501 ));
2502 }
2503 } else if flavor == LinkerFlavor::Ptx {
2504 cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2505 } else if flavor == LinkerFlavor::Bpf {
2506 cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2507 if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2508 .into_iter()
2509 .find(|feat| !feat.is_empty())
2510 {
2511 cmd.link_args(&["--cpu-features", feat]);
2512 }
2513 }
2514
2515 cmd.linker_plugin_lto();
2516
2517 add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
2518
2519 cmd.output_filename(out_filename);
2520
2521 if crate_type == CrateType::Executable
2522 && sess.target.is_like_windows
2523 && let Some(s) = &codegen_results.crate_info.windows_subsystem
2524 {
2525 cmd.subsystem(s);
2526 }
2527
2528 if !sess.link_dead_code() {
2531 let keep_metadata =
2536 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2537 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2538 {
2539 cmd.gc_sections(keep_metadata);
2540 } else {
2541 cmd.no_gc_sections();
2542 }
2543 }
2544
2545 cmd.set_output_kind(link_output_kind, crate_type, out_filename);
2546
2547 add_relro_args(cmd, sess);
2548
2549 cmd.optimize();
2551
2552 let natvis_visualizers = collect_natvis_visualizers(
2554 tmpdir,
2555 sess,
2556 &codegen_results.crate_info.local_crate_name,
2557 &codegen_results.crate_info.natvis_debugger_visualizers,
2558 );
2559
2560 cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
2562
2563 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2566 cmd.no_default_libraries();
2567 }
2568
2569 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2570 cmd.pgo_gen();
2571 }
2572
2573 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2574 cmd.control_flow_guard();
2575 }
2576
2577 if sess.opts.unstable_opts.ehcont_guard {
2579 cmd.ehcont_guard();
2580 }
2581
2582 add_rpath_args(cmd, sess, codegen_results, out_filename);
2583}
2584
2585fn collect_natvis_visualizers(
2587 tmpdir: &Path,
2588 sess: &Session,
2589 crate_name: &Symbol,
2590 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2591) -> Vec<PathBuf> {
2592 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2593
2594 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2595 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2596
2597 match fs::write(&visualizer_out_file, &visualizer.src) {
2598 Ok(()) => {
2599 visualizer_paths.push(visualizer_out_file);
2600 }
2601 Err(error) => {
2602 sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2603 path: visualizer_out_file,
2604 error,
2605 });
2606 }
2607 };
2608 }
2609 visualizer_paths
2610}
2611
2612fn add_native_libs_from_crate(
2613 cmd: &mut dyn Linker,
2614 sess: &Session,
2615 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2616 codegen_results: &CodegenResults,
2617 tmpdir: &Path,
2618 bundled_libs: &FxIndexSet<Symbol>,
2619 cnum: CrateNum,
2620 link_static: bool,
2621 link_dynamic: bool,
2622 link_output_kind: LinkOutputKind,
2623) {
2624 if !sess.opts.unstable_opts.link_native_libraries {
2625 return;
2629 }
2630
2631 if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2632 let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2634 archive_builder_builder
2635 .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2636 .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2637 }
2638
2639 let native_libs = match cnum {
2640 LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2641 _ => &codegen_results.crate_info.native_libraries[&cnum],
2642 };
2643
2644 let mut last = (None, NativeLibKind::Unspecified, false);
2645 for lib in native_libs {
2646 if !relevant_lib(sess, lib) {
2647 continue;
2648 }
2649
2650 last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2652 continue;
2653 } else {
2654 (Some(lib.name), lib.kind, lib.verbatim)
2655 };
2656
2657 let name = lib.name.as_str();
2658 let verbatim = lib.verbatim;
2659 match lib.kind {
2660 NativeLibKind::Static { bundle, whole_archive } => {
2661 if link_static {
2662 let bundle = bundle.unwrap_or(true);
2663 let whole_archive = whole_archive == Some(true);
2664 if bundle && cnum != LOCAL_CRATE {
2665 if let Some(filename) = lib.filename {
2666 let path = tmpdir.join(filename.as_str());
2668 cmd.link_staticlib_by_path(&path, whole_archive);
2669 }
2670 } else {
2671 cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2672 }
2673 }
2674 }
2675 NativeLibKind::Dylib { as_needed } => {
2676 if link_dynamic {
2677 cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2678 }
2679 }
2680 NativeLibKind::Unspecified => {
2681 if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2684 if link_static {
2685 cmd.link_staticlib_by_name(name, verbatim, false);
2686 }
2687 } else if link_dynamic {
2688 cmd.link_dylib_by_name(name, verbatim, true);
2689 }
2690 }
2691 NativeLibKind::Framework { as_needed } => {
2692 if link_dynamic {
2693 cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2694 }
2695 }
2696 NativeLibKind::RawDylib => {
2697 }
2699 NativeLibKind::WasmImportModule => {}
2700 NativeLibKind::LinkArg => {
2701 if link_static {
2702 if verbatim {
2703 cmd.verbatim_arg(name);
2704 } else {
2705 cmd.link_arg(name);
2706 }
2707 }
2708 }
2709 }
2710 }
2711}
2712
2713fn add_local_native_libraries(
2714 cmd: &mut dyn Linker,
2715 sess: &Session,
2716 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2717 codegen_results: &CodegenResults,
2718 tmpdir: &Path,
2719 link_output_kind: LinkOutputKind,
2720) {
2721 let link_static = true;
2723 let link_dynamic = true;
2724 add_native_libs_from_crate(
2725 cmd,
2726 sess,
2727 archive_builder_builder,
2728 codegen_results,
2729 tmpdir,
2730 &Default::default(),
2731 LOCAL_CRATE,
2732 link_static,
2733 link_dynamic,
2734 link_output_kind,
2735 );
2736}
2737
2738fn add_upstream_rust_crates(
2739 cmd: &mut dyn Linker,
2740 sess: &Session,
2741 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2742 codegen_results: &CodegenResults,
2743 crate_type: CrateType,
2744 tmpdir: &Path,
2745 link_output_kind: LinkOutputKind,
2746) {
2747 let data = codegen_results
2755 .crate_info
2756 .dependency_formats
2757 .get(&crate_type)
2758 .expect("failed to find crate type in dependency format list");
2759
2760 if sess.target.is_like_aix {
2761 cmd.link_or_cc_arg("-bnoipath");
2767 }
2768
2769 for &cnum in &codegen_results.crate_info.used_crates {
2770 let linkage = data[cnum];
2778 let link_static_crate = linkage == Linkage::Static
2779 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2780 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2781 || codegen_results.crate_info.profiler_runtime == Some(cnum));
2782
2783 let mut bundled_libs = Default::default();
2784 match linkage {
2785 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2786 if link_static_crate {
2787 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2788 .iter()
2789 .filter_map(|lib| lib.filename)
2790 .collect();
2791 add_static_crate(
2792 cmd,
2793 sess,
2794 archive_builder_builder,
2795 codegen_results,
2796 tmpdir,
2797 cnum,
2798 &bundled_libs,
2799 );
2800 }
2801 }
2802 Linkage::Dynamic => {
2803 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2804 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2805 }
2806 }
2807
2808 let link_static = link_static_crate;
2817 let link_dynamic = false;
2819 add_native_libs_from_crate(
2820 cmd,
2821 sess,
2822 archive_builder_builder,
2823 codegen_results,
2824 tmpdir,
2825 &bundled_libs,
2826 cnum,
2827 link_static,
2828 link_dynamic,
2829 link_output_kind,
2830 );
2831 }
2832}
2833
2834fn add_upstream_native_libraries(
2835 cmd: &mut dyn Linker,
2836 sess: &Session,
2837 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2838 codegen_results: &CodegenResults,
2839 tmpdir: &Path,
2840 link_output_kind: LinkOutputKind,
2841) {
2842 for &cnum in &codegen_results.crate_info.used_crates {
2843 let link_static = false;
2849 let link_dynamic = true;
2857 add_native_libs_from_crate(
2858 cmd,
2859 sess,
2860 archive_builder_builder,
2861 codegen_results,
2862 tmpdir,
2863 &Default::default(),
2864 cnum,
2865 link_static,
2866 link_dynamic,
2867 link_output_kind,
2868 );
2869 }
2870}
2871
2872fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2882 let sysroot_lib_path = &sess.target_tlib_path.dir;
2883 let canonical_sysroot_lib_path =
2884 { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2885
2886 let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2887 if canonical_lib_dir == canonical_sysroot_lib_path {
2888 sysroot_lib_path.clone()
2890 } else {
2891 fix_windows_verbatim_for_gcc(lib_dir)
2892 }
2893}
2894
2895fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2896 if let Some(dir) = path.parent() {
2897 let file_name = path.file_name().expect("library path has no file name component");
2898 rehome_sysroot_lib_dir(sess, dir).join(file_name)
2899 } else {
2900 fix_windows_verbatim_for_gcc(path)
2901 }
2902}
2903
2904fn add_static_crate(
2923 cmd: &mut dyn Linker,
2924 sess: &Session,
2925 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2926 codegen_results: &CodegenResults,
2927 tmpdir: &Path,
2928 cnum: CrateNum,
2929 bundled_lib_file_names: &FxIndexSet<Symbol>,
2930) {
2931 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2932 let cratepath = &src.rlib.as_ref().unwrap().0;
2933
2934 let mut link_upstream =
2935 |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
2936
2937 if !are_upstream_rust_objects_already_included(sess)
2938 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2939 {
2940 link_upstream(cratepath);
2941 return;
2942 }
2943
2944 let dst = tmpdir.join(cratepath.file_name().unwrap());
2945 let name = cratepath.file_name().unwrap().to_str().unwrap();
2946 let name = &name[3..name.len() - 5]; let bundled_lib_file_names = bundled_lib_file_names.clone();
2948
2949 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2950 let canonical_name = name.replace('-', "_");
2951 let upstream_rust_objects_already_included =
2952 are_upstream_rust_objects_already_included(sess);
2953 let is_builtins =
2954 sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2955
2956 let mut archive = archive_builder_builder.new_archive_builder(sess);
2957 if let Err(error) = archive.add_archive(
2958 cratepath,
2959 Box::new(move |f| {
2960 if f == METADATA_FILENAME {
2961 return true;
2962 }
2963
2964 let canonical = f.replace('-', "_");
2965
2966 let is_rust_object =
2967 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
2968
2969 if upstream_rust_objects_already_included && is_rust_object && is_builtins {
2974 return true;
2975 }
2976
2977 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
2983 return true;
2984 }
2985
2986 false
2987 }),
2988 ) {
2989 sess.dcx()
2990 .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
2991 }
2992 if archive.build(&dst) {
2993 link_upstream(&dst);
2994 }
2995 });
2996}
2997
2998fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3000 cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3001}
3002
3003fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3004 match lib.cfg {
3005 Some(ref cfg) => rustc_attr_parsing::cfg_matches(cfg, sess, CRATE_NODE_ID, None),
3006 None => true,
3007 }
3008}
3009
3010pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3011 match sess.lto() {
3012 config::Lto::Fat => true,
3013 config::Lto::Thin => {
3014 !sess.opts.cg.linker_plugin_lto.enabled()
3017 }
3018 config::Lto::No | config::Lto::ThinLocal => false,
3019 }
3020}
3021
3022fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3029 if !sess.target.is_like_darwin {
3030 return;
3031 }
3032 let LinkerFlavor::Darwin(cc, _) = flavor else {
3033 return;
3034 };
3035
3036 let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3038 let target_os = &*sess.target.os;
3039 let target_abi = &*sess.target.abi;
3040
3041 let ld64_arch = match llvm_arch {
3049 "armv7k" => "armv7k",
3050 "armv7s" => "armv7s",
3051 "arm64" => "arm64",
3052 "arm64e" => "arm64e",
3053 "arm64_32" => "arm64_32",
3054 "i386" | "i686" => "i386",
3058 "x86_64" => "x86_64",
3059 "x86_64h" => "x86_64h",
3060 _ => bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3061 };
3062
3063 if cc == Cc::No {
3064 cmd.link_args(&["-arch", ld64_arch]);
3074
3075 let platform_name = match (target_os, target_abi) {
3091 (os, "") => os,
3092 ("ios", "macabi") => "mac-catalyst",
3093 ("ios", "sim") => "ios-simulator",
3094 ("tvos", "sim") => "tvos-simulator",
3095 ("watchos", "sim") => "watchos-simulator",
3096 ("visionos", "sim") => "visionos-simulator",
3097 _ => bug!("invalid OS/ABI combination for Apple target: {target_os}, {target_abi}"),
3098 };
3099
3100 let min_version = sess.apple_deployment_target().fmt_full().to_string();
3101
3102 let sdk_version = &*min_version;
3135
3136 cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3145 } else {
3146 if target_os == "macos" {
3161 cmd.cc_args(&["-arch", ld64_arch]);
3166
3167 let version = sess.apple_deployment_target().fmt_full();
3170 cmd.cc_arg(&format!("-mmacosx-version-min={version}"));
3173
3174 } else {
3179 cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3180 }
3181 }
3182}
3183
3184fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3185 let os = &sess.target.os;
3186 if sess.target.vendor != "apple"
3187 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "visionos" | "macos")
3188 || !matches!(flavor, LinkerFlavor::Darwin(..))
3189 {
3190 return None;
3191 }
3192
3193 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
3194 return None;
3195 }
3196
3197 let sdk_root = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
3198
3199 match flavor {
3200 LinkerFlavor::Darwin(Cc::Yes, _) => {
3201 cmd.cc_arg("-isysroot");
3208 cmd.cc_arg(&sdk_root);
3209 }
3210 LinkerFlavor::Darwin(Cc::No, _) => {
3211 cmd.link_arg("-syslibroot");
3212 cmd.link_arg(&sdk_root);
3213 }
3214 _ => unreachable!(),
3215 }
3216
3217 Some(sdk_root)
3218}
3219
3220fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3221 if let Ok(sdkroot) = env::var("SDKROOT") {
3222 let p = PathBuf::from(&sdkroot);
3223
3224 match &*apple::sdk_name(&sess.target).to_lowercase() {
3233 "appletvos"
3234 if sdkroot.contains("TVSimulator.platform")
3235 || sdkroot.contains("MacOSX.platform") => {}
3236 "appletvsimulator"
3237 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3238 "iphoneos"
3239 if sdkroot.contains("iPhoneSimulator.platform")
3240 || sdkroot.contains("MacOSX.platform") => {}
3241 "iphonesimulator"
3242 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3243 }
3244 "macosx"
3245 if sdkroot.contains("iPhoneOS.platform")
3246 || sdkroot.contains("iPhoneSimulator.platform") => {}
3247 "watchos"
3248 if sdkroot.contains("WatchSimulator.platform")
3249 || sdkroot.contains("MacOSX.platform") => {}
3250 "watchsimulator"
3251 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3252 "xros"
3253 if sdkroot.contains("XRSimulator.platform")
3254 || sdkroot.contains("MacOSX.platform") => {}
3255 "xrsimulator"
3256 if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3257 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3259 _ => return Some(p),
3260 }
3261 }
3262
3263 apple::get_sdk_root(sess)
3264}
3265
3266fn add_lld_args(
3271 cmd: &mut dyn Linker,
3272 sess: &Session,
3273 flavor: LinkerFlavor,
3274 self_contained_components: LinkSelfContainedComponents,
3275) {
3276 debug!(
3277 "add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3278 flavor, self_contained_components,
3279 );
3280
3281 if !(flavor.uses_cc() && flavor.uses_lld()) {
3284 return;
3285 }
3286
3287 let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3293 let self_contained_target = self_contained_components.is_linker_enabled();
3294
3295 let self_contained_linker = self_contained_cli || self_contained_target;
3296 if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3297 let mut linker_path_exists = false;
3298 for path in sess.get_tools_search_paths(false) {
3299 let linker_path = path.join("gcc-ld");
3300 linker_path_exists |= linker_path.exists();
3301 cmd.cc_arg({
3302 let mut arg = OsString::from("-B");
3303 arg.push(linker_path);
3304 arg
3305 });
3306 }
3307 if !linker_path_exists {
3308 sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3311 }
3312 }
3313
3314 if !sess.target.is_like_wasm {
3321 cmd.cc_arg("-fuse-ld=lld");
3322
3323 if sess.target.llvm_target == "x86_64-unknown-linux-gnu" {
3349 cmd.link_arg("-znostart-stop-gc");
3350 }
3351 }
3352
3353 if !flavor.is_gnu() {
3354 if sess.target.linker_flavor != sess.host.linker_flavor {
3374 cmd.cc_arg(format!("--target={}", versioned_llvm_target(sess)));
3375 }
3376 }
3377}