1 use rustc_arena::TypedArena;
2 use rustc_ast::CRATE_NODE_ID;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::fx::FxIndexMap;
5 use rustc_data_structures::memmap::Mmap;
6 use rustc_data_structures::temp_dir::MaybeTempDir;
7 use rustc_errors::{ErrorGuaranteed, Handler};
8 use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
9 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
10 use rustc_metadata::find_native_static_library;
11 use rustc_metadata::fs::{copy_to_stdout, emit_wrapper_file, METADATA_FILENAME};
12 use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
13 use rustc_middle::middle::dependency_format::Linkage;
14 use rustc_middle::middle::exported_symbols::SymbolExportKind;
15 use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, Strip};
16 use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, SplitDwarfKind};
17 use rustc_session::cstore::DllImport;
18 use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
19 use rustc_session::search_paths::PathKind;
20 use rustc_session::utils::NativeLibKind;
21 /// For all the linkers we support, and information they might
22 /// need out of the shared crate context before we get rid of it.
23 use rustc_session::{filesearch, Session};
24 use rustc_span::symbol::Symbol;
25 use rustc_target::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
26 use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld, PanicStrategy};
27 use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo};
28
29 use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
30 use super::command::Command;
31 use super::linker::{self, Linker};
32 use super::metadata::{create_wrapper_file, MetadataPosition};
33 use super::rpath::{self, RPathConfig};
34 use crate::{
35 errors, looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib,
36 };
37
38 use cc::windows_registry;
39 use regex::Regex;
40 use tempfile::Builder as TempFileBuilder;
41
42 use itertools::Itertools;
43 use std::cell::OnceCell;
44 use std::collections::BTreeSet;
45 use std::ffi::OsString;
46 use std::fs::{read, File, OpenOptions};
47 use std::io::{BufWriter, Write};
48 use std::ops::Deref;
49 use std::path::{Path, PathBuf};
50 use std::process::{ExitStatus, Output, Stdio};
51 use std::{env, fmt, fs, io, mem, str};
52
ensure_removed(diag_handler: &Handler, path: &Path)53 pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
54 if let Err(e) = fs::remove_file(path) {
55 if e.kind() != io::ErrorKind::NotFound {
56 diag_handler.err(format!("failed to remove {}: {}", path.display(), e));
57 }
58 }
59 }
60
61 /// Performs the linkage portion of the compilation phase. This will generate all
62 /// of the requested outputs for this compilation session.
link_binary<'a>( sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, outputs: &OutputFilenames, ) -> Result<(), ErrorGuaranteed>63 pub fn link_binary<'a>(
64 sess: &'a Session,
65 archive_builder_builder: &dyn ArchiveBuilderBuilder,
66 codegen_results: &CodegenResults,
67 outputs: &OutputFilenames,
68 ) -> Result<(), ErrorGuaranteed> {
69 let _timer = sess.timer("link_binary");
70 let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
71 let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
72 for &crate_type in sess.crate_types().iter() {
73 // Ignore executable crates if we have -Z no-codegen, as they will error.
74 if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
75 && !output_metadata
76 && crate_type == CrateType::Executable
77 {
78 continue;
79 }
80
81 if invalid_output_for_target(sess, crate_type) {
82 bug!(
83 "invalid output type `{:?}` for target os `{}`",
84 crate_type,
85 sess.opts.target_triple
86 );
87 }
88
89 sess.time("link_binary_check_files_are_writeable", || {
90 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
91 check_file_is_writeable(obj, sess);
92 }
93 });
94
95 if outputs.outputs.should_link() {
96 let tmpdir = TempFileBuilder::new()
97 .prefix("rustc")
98 .tempdir()
99 .unwrap_or_else(|error| sess.emit_fatal(errors::CreateTempDir { error }));
100 let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
101 let output = out_filename(
102 sess,
103 crate_type,
104 outputs,
105 codegen_results.crate_info.local_crate_name,
106 );
107 let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
108 let out_filename =
109 output.file_for_writing(outputs, OutputType::Exe, Some(crate_name.as_str()));
110 match crate_type {
111 CrateType::Rlib => {
112 let _timer = sess.timer("link_rlib");
113 info!("preparing rlib to {:?}", out_filename);
114 link_rlib(
115 sess,
116 archive_builder_builder,
117 codegen_results,
118 RlibFlavor::Normal,
119 &path,
120 )?
121 .build(&out_filename);
122 }
123 CrateType::Staticlib => {
124 link_staticlib(
125 sess,
126 archive_builder_builder,
127 codegen_results,
128 &out_filename,
129 &path,
130 )?;
131 }
132 _ => {
133 link_natively(
134 sess,
135 archive_builder_builder,
136 crate_type,
137 &out_filename,
138 codegen_results,
139 path.as_ref(),
140 )?;
141 }
142 }
143 if sess.opts.json_artifact_notifications {
144 sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
145 }
146
147 if sess.prof.enabled() {
148 if let Some(artifact_name) = out_filename.file_name() {
149 // Record size for self-profiling
150 let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
151
152 sess.prof.artifact_size(
153 "linked_artifact",
154 artifact_name.to_string_lossy(),
155 file_size,
156 );
157 }
158 }
159
160 if output.is_stdout() {
161 if output.is_tty() {
162 sess.emit_err(errors::BinaryOutputToTty {
163 shorthand: OutputType::Exe.shorthand(),
164 });
165 } else if let Err(e) = copy_to_stdout(&out_filename) {
166 sess.emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
167 }
168 tempfiles_for_stdout_output.push(out_filename);
169 }
170 }
171 }
172
173 // Remove the temporary object file and metadata if we aren't saving temps.
174 sess.time("link_binary_remove_temps", || {
175 // If the user requests that temporaries are saved, don't delete any.
176 if sess.opts.cg.save_temps {
177 return;
178 }
179
180 let maybe_remove_temps_from_module =
181 |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
182 if !preserve_objects {
183 if let Some(ref obj) = module.object {
184 ensure_removed(sess.diagnostic(), obj);
185 }
186 }
187
188 if !preserve_dwarf_objects {
189 if let Some(ref dwo_obj) = module.dwarf_object {
190 ensure_removed(sess.diagnostic(), dwo_obj);
191 }
192 }
193 };
194
195 let remove_temps_from_module =
196 |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
197
198 // Otherwise, always remove the metadata and allocator module temporaries.
199 if let Some(ref metadata_module) = codegen_results.metadata_module {
200 remove_temps_from_module(metadata_module);
201 }
202
203 if let Some(ref allocator_module) = codegen_results.allocator_module {
204 remove_temps_from_module(allocator_module);
205 }
206
207 // Remove the temporary files if output goes to stdout
208 for temp in tempfiles_for_stdout_output {
209 ensure_removed(sess.diagnostic(), &temp);
210 }
211
212 // If no requested outputs require linking, then the object temporaries should
213 // be kept.
214 if !sess.opts.output_types.should_link() {
215 return;
216 }
217
218 // Potentially keep objects for their debuginfo.
219 let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
220 debug!(?preserve_objects, ?preserve_dwarf_objects);
221
222 for module in &codegen_results.modules {
223 maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
224 }
225 });
226
227 Ok(())
228 }
229
230 // Crate type is not passed when calculating the dylibs to include for LTO. In that case all
231 // crate types must use the same dependency formats.
each_linked_rlib( info: &CrateInfo, crate_type: Option<CrateType>, f: &mut dyn FnMut(CrateNum, &Path), ) -> Result<(), errors::LinkRlibError>232 pub fn each_linked_rlib(
233 info: &CrateInfo,
234 crate_type: Option<CrateType>,
235 f: &mut dyn FnMut(CrateNum, &Path),
236 ) -> Result<(), errors::LinkRlibError> {
237 let crates = info.used_crates.iter();
238
239 let fmts = if crate_type.is_none() {
240 for combination in info.dependency_formats.iter().combinations(2) {
241 let (ty1, list1) = &combination[0];
242 let (ty2, list2) = &combination[1];
243 if list1 != list2 {
244 return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
245 ty1: format!("{ty1:?}"),
246 ty2: format!("{ty2:?}"),
247 list1: format!("{list1:?}"),
248 list2: format!("{list2:?}"),
249 });
250 }
251 }
252 if info.dependency_formats.is_empty() {
253 return Err(errors::LinkRlibError::MissingFormat);
254 }
255 &info.dependency_formats[0].1
256 } else {
257 let fmts = info
258 .dependency_formats
259 .iter()
260 .find_map(|&(ty, ref list)| if Some(ty) == crate_type { Some(list) } else { None });
261
262 let Some(fmts) = fmts else {
263 return Err(errors::LinkRlibError::MissingFormat);
264 };
265
266 fmts
267 };
268
269 for &cnum in crates {
270 match fmts.get(cnum.as_usize() - 1) {
271 Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
272 Some(_) => {}
273 None => return Err(errors::LinkRlibError::MissingFormat),
274 }
275 let crate_name = info.crate_name[&cnum];
276 let used_crate_source = &info.used_crate_source[&cnum];
277 if let Some((path, _)) = &used_crate_source.rlib {
278 f(cnum, &path);
279 } else {
280 if used_crate_source.rmeta.is_some() {
281 return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
282 } else {
283 return Err(errors::LinkRlibError::NotFound { crate_name });
284 }
285 }
286 }
287 Ok(())
288 }
289
290 /// Create an 'rlib'.
291 ///
292 /// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
293 /// The rlib primarily contains the object file of the crate, but it also some of the object files
294 /// from native libraries.
link_rlib<'a>( sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, flavor: RlibFlavor, tmpdir: &MaybeTempDir, ) -> Result<Box<dyn ArchiveBuilder<'a> + 'a>, ErrorGuaranteed>295 fn link_rlib<'a>(
296 sess: &'a Session,
297 archive_builder_builder: &dyn ArchiveBuilderBuilder,
298 codegen_results: &CodegenResults,
299 flavor: RlibFlavor,
300 tmpdir: &MaybeTempDir,
301 ) -> Result<Box<dyn ArchiveBuilder<'a> + 'a>, ErrorGuaranteed> {
302 let lib_search_paths = archive_search_paths(sess);
303
304 let mut ab = archive_builder_builder.new_archive_builder(sess);
305
306 let trailing_metadata = match flavor {
307 RlibFlavor::Normal => {
308 let (metadata, metadata_position) =
309 create_wrapper_file(sess, b".rmeta".to_vec(), codegen_results.metadata.raw_data());
310 let metadata = emit_wrapper_file(sess, &metadata, tmpdir, METADATA_FILENAME);
311 match metadata_position {
312 MetadataPosition::First => {
313 // Most of the time metadata in rlib files is wrapped in a "dummy" object
314 // file for the target platform so the rlib can be processed entirely by
315 // normal linkers for the platform. Sometimes this is not possible however.
316 // If it is possible however, placing the metadata object first improves
317 // performance of getting metadata from rlibs.
318 ab.add_file(&metadata);
319 None
320 }
321 MetadataPosition::Last => Some(metadata),
322 }
323 }
324
325 RlibFlavor::StaticlibBase => None,
326 };
327
328 for m in &codegen_results.modules {
329 if let Some(obj) = m.object.as_ref() {
330 ab.add_file(obj);
331 }
332
333 if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
334 ab.add_file(dwarf_obj);
335 }
336 }
337
338 match flavor {
339 RlibFlavor::Normal => {}
340 RlibFlavor::StaticlibBase => {
341 let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
342 if let Some(obj) = obj {
343 ab.add_file(obj);
344 }
345 }
346 }
347
348 // Used if packed_bundled_libs flag enabled.
349 let mut packed_bundled_libs = Vec::new();
350
351 // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
352 // we may not be configured to actually include a static library if we're
353 // adding it here. That's because later when we consume this rlib we'll
354 // decide whether we actually needed the static library or not.
355 //
356 // To do this "correctly" we'd need to keep track of which libraries added
357 // which object files to the archive. We don't do that here, however. The
358 // #[link(cfg(..))] feature is unstable, though, and only intended to get
359 // liblibc working. In that sense the check below just indicates that if
360 // there are any libraries we want to omit object files for at link time we
361 // just exclude all custom object files.
362 //
363 // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
364 // feature then we'll need to figure out how to record what objects were
365 // loaded from the libraries found here and then encode that into the
366 // metadata of the rlib we're generating somehow.
367 for lib in codegen_results.crate_info.used_libraries.iter() {
368 let NativeLibKind::Static { bundle: None | Some(true), whole_archive } = lib.kind else {
369 continue;
370 };
371 if whole_archive == Some(true)
372 && flavor == RlibFlavor::Normal
373 && !codegen_results.crate_info.feature_packed_bundled_libs
374 {
375 sess.emit_err(errors::IncompatibleLinkingModifiers);
376 }
377 if flavor == RlibFlavor::Normal && let Some(filename) = lib.filename {
378 let path = find_native_static_library(filename.as_str(), true, &lib_search_paths, sess);
379 let src = read(path).map_err(|e| sess.emit_fatal(errors::ReadFileError {message: e }))?;
380 let (data, _) = create_wrapper_file(sess, b".bundled_lib".to_vec(), &src);
381 let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
382 packed_bundled_libs.push(wrapper_file);
383 } else {
384 let path =
385 find_native_static_library(lib.name.as_str(), lib.verbatim, &lib_search_paths, sess);
386 ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
387 sess.emit_fatal(errors::AddNativeLibrary { library_path: path, error })});
388 }
389 }
390
391 for (raw_dylib_name, raw_dylib_imports) in
392 collate_raw_dylibs(sess, codegen_results.crate_info.used_libraries.iter())?
393 {
394 let output_path = archive_builder_builder.create_dll_import_lib(
395 sess,
396 &raw_dylib_name,
397 &raw_dylib_imports,
398 tmpdir.as_ref(),
399 true,
400 );
401
402 ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
403 sess.emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
404 });
405 }
406
407 if let Some(trailing_metadata) = trailing_metadata {
408 // Note that it is important that we add all of our non-object "magical
409 // files" *after* all of the object files in the archive. The reason for
410 // this is as follows:
411 //
412 // * When performing LTO, this archive will be modified to remove
413 // objects from above. The reason for this is described below.
414 //
415 // * When the system linker looks at an archive, it will attempt to
416 // determine the architecture of the archive in order to see whether its
417 // linkable.
418 //
419 // The algorithm for this detection is: iterate over the files in the
420 // archive. Skip magical SYMDEF names. Interpret the first file as an
421 // object file. Read architecture from the object file.
422 //
423 // * As one can probably see, if "metadata" and "foo.bc" were placed
424 // before all of the objects, then the architecture of this archive would
425 // not be correctly inferred once 'foo.o' is removed.
426 //
427 // * Most of the time metadata in rlib files is wrapped in a "dummy" object
428 // file for the target platform so the rlib can be processed entirely by
429 // normal linkers for the platform. Sometimes this is not possible however.
430 //
431 // Basically, all this means is that this code should not move above the
432 // code above.
433 ab.add_file(&trailing_metadata);
434 }
435
436 // Add all bundled static native library dependencies.
437 // Archives added to the end of .rlib archive, see comment above for the reason.
438 for lib in packed_bundled_libs {
439 ab.add_file(&lib)
440 }
441
442 return Ok(ab);
443 }
444
445 /// Extract all symbols defined in raw-dylib libraries, collated by library name.
446 ///
447 /// If we have multiple extern blocks that specify symbols defined in the same raw-dylib library,
448 /// then the CodegenResults value contains one NativeLib instance for each block. However, the
449 /// linker appears to expect only a single import library for each library used, so we need to
450 /// collate the symbols together by library name before generating the import libraries.
collate_raw_dylibs<'a, 'b>( sess: &'a Session, used_libraries: impl IntoIterator<Item = &'b NativeLib>, ) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed>451 fn collate_raw_dylibs<'a, 'b>(
452 sess: &'a Session,
453 used_libraries: impl IntoIterator<Item = &'b NativeLib>,
454 ) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed> {
455 // Use index maps to preserve original order of imports and libraries.
456 let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
457
458 for lib in used_libraries {
459 if lib.kind == NativeLibKind::RawDylib {
460 let ext = if lib.verbatim { "" } else { ".dll" };
461 let name = format!("{}{}", lib.name, ext);
462 let imports = dylib_table.entry(name.clone()).or_default();
463 for import in &lib.dll_imports {
464 if let Some(old_import) = imports.insert(import.name, import) {
465 // FIXME: when we add support for ordinals, figure out if we need to do anything
466 // if we have two DllImport values with the same name but different ordinals.
467 if import.calling_convention != old_import.calling_convention {
468 sess.emit_err(errors::MultipleExternalFuncDecl {
469 span: import.span,
470 function: import.name,
471 library_name: &name,
472 });
473 }
474 }
475 }
476 }
477 }
478 sess.compile_status()?;
479 Ok(dylib_table
480 .into_iter()
481 .map(|(name, imports)| {
482 (name, imports.into_iter().map(|(_, import)| import.clone()).collect())
483 })
484 .collect())
485 }
486
487 /// Create a static archive.
488 ///
489 /// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
490 /// crates' objects into the archive. This will slurp in all of the native libraries of upstream
491 /// dependencies as well.
492 ///
493 /// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
494 /// library dependencies that they're not linked in.
495 ///
496 /// There's no need to include metadata in a static archive, so ensure to not link in the metadata
497 /// object file (and also don't prepare the archive with a metadata file).
link_staticlib<'a>( sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, out_filename: &Path, tempdir: &MaybeTempDir, ) -> Result<(), ErrorGuaranteed>498 fn link_staticlib<'a>(
499 sess: &'a Session,
500 archive_builder_builder: &dyn ArchiveBuilderBuilder,
501 codegen_results: &CodegenResults,
502 out_filename: &Path,
503 tempdir: &MaybeTempDir,
504 ) -> Result<(), ErrorGuaranteed> {
505 info!("preparing staticlib to {:?}", out_filename);
506 let mut ab = link_rlib(
507 sess,
508 archive_builder_builder,
509 codegen_results,
510 RlibFlavor::StaticlibBase,
511 tempdir,
512 )?;
513 let mut all_native_libs = vec![];
514
515 let res = each_linked_rlib(
516 &codegen_results.crate_info,
517 Some(CrateType::Staticlib),
518 &mut |cnum, path| {
519 let lto = are_upstream_rust_objects_already_included(sess)
520 && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
521
522 let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
523 let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, &lib));
524 let relevant_libs: FxHashSet<_> = relevant.filter_map(|lib| lib.filename).collect();
525
526 let bundled_libs: FxHashSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
527 ab.add_archive(
528 path,
529 Box::new(move |fname: &str| {
530 // Ignore metadata files, no matter the name.
531 if fname == METADATA_FILENAME {
532 return true;
533 }
534
535 // Don't include Rust objects if LTO is enabled
536 if lto && looks_like_rust_object_file(fname) {
537 return true;
538 }
539
540 // Skip objects for bundled libs.
541 if bundled_libs.contains(&Symbol::intern(fname)) {
542 return true;
543 }
544
545 false
546 }),
547 )
548 .unwrap();
549
550 archive_builder_builder
551 .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
552 .unwrap_or_else(|e| sess.emit_fatal(e));
553 for filename in relevant_libs {
554 let joined = tempdir.as_ref().join(filename.as_str());
555 let path = joined.as_path();
556 ab.add_archive(path, Box::new(|_| false)).unwrap();
557 }
558
559 all_native_libs
560 .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
561 },
562 );
563 if let Err(e) = res {
564 sess.emit_fatal(e);
565 }
566
567 ab.build(out_filename);
568
569 let crates = codegen_results.crate_info.used_crates.iter();
570
571 let fmts = codegen_results
572 .crate_info
573 .dependency_formats
574 .iter()
575 .find_map(|&(ty, ref list)| if ty == CrateType::Staticlib { Some(list) } else { None })
576 .expect("no dependency formats for staticlib");
577
578 let mut all_rust_dylibs = vec![];
579 for &cnum in crates {
580 match fmts.get(cnum.as_usize() - 1) {
581 Some(&Linkage::Dynamic) => {}
582 _ => continue,
583 }
584 let crate_name = codegen_results.crate_info.crate_name[&cnum];
585 let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
586 if let Some((path, _)) = &used_crate_source.dylib {
587 all_rust_dylibs.push(&**path);
588 } else {
589 if used_crate_source.rmeta.is_some() {
590 sess.emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
591 } else {
592 sess.emit_fatal(errors::LinkRlibError::NotFound { crate_name });
593 }
594 }
595 }
596
597 all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
598
599 if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
600 print_native_static_libs(sess, &all_native_libs, &all_rust_dylibs);
601 }
602
603 Ok(())
604 }
605
606 /// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
607 /// DWARF package.
link_dwarf_object<'a>( sess: &'a Session, cg_results: &CodegenResults, executable_out_filename: &Path, )608 fn link_dwarf_object<'a>(
609 sess: &'a Session,
610 cg_results: &CodegenResults,
611 executable_out_filename: &Path,
612 ) {
613 let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
614 dwp_out_filename.push(".dwp");
615 debug!(?dwp_out_filename, ?executable_out_filename);
616
617 #[derive(Default)]
618 struct ThorinSession<Relocations> {
619 arena_data: TypedArena<Vec<u8>>,
620 arena_mmap: TypedArena<Mmap>,
621 arena_relocations: TypedArena<Relocations>,
622 }
623
624 impl<Relocations> ThorinSession<Relocations> {
625 fn alloc_mmap(&self, data: Mmap) -> &Mmap {
626 &*self.arena_mmap.alloc(data)
627 }
628 }
629
630 impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
631 fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
632 &*self.arena_data.alloc(data)
633 }
634
635 fn alloc_relocation(&self, data: Relocations) -> &Relocations {
636 &*self.arena_relocations.alloc(data)
637 }
638
639 fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
640 let file = File::open(&path)?;
641 let mmap = (unsafe { Mmap::map(file) })?;
642 Ok(self.alloc_mmap(mmap))
643 }
644 }
645
646 match sess.time("run_thorin", || -> Result<(), thorin::Error> {
647 let thorin_sess = ThorinSession::default();
648 let mut package = thorin::DwarfPackage::new(&thorin_sess);
649
650 // Input objs contain .o/.dwo files from the current crate.
651 match sess.opts.unstable_opts.split_dwarf_kind {
652 SplitDwarfKind::Single => {
653 for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
654 package.add_input_object(input_obj)?;
655 }
656 }
657 SplitDwarfKind::Split => {
658 for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
659 package.add_input_object(input_obj)?;
660 }
661 }
662 }
663
664 // Input rlibs contain .o/.dwo files from dependencies.
665 let input_rlibs = cg_results
666 .crate_info
667 .used_crate_source
668 .values()
669 .filter_map(|csource| csource.rlib.as_ref())
670 .map(|(path, _)| path);
671 for input_rlib in input_rlibs {
672 debug!(?input_rlib);
673 package.add_input_object(input_rlib)?;
674 }
675
676 // Failing to read the referenced objects is expected for dependencies where the path in the
677 // executable will have been cleaned by Cargo, but the referenced objects will be contained
678 // within rlibs provided as inputs.
679 //
680 // If paths have been remapped, then .o/.dwo files from the current crate also won't be
681 // found, but are provided explicitly above.
682 //
683 // Adding an executable is primarily done to make `thorin` check that all the referenced
684 // dwarf objects are found in the end.
685 package.add_executable(
686 &executable_out_filename,
687 thorin::MissingReferencedObjectBehaviour::Skip,
688 )?;
689
690 let output_stream = BufWriter::new(
691 OpenOptions::new()
692 .read(true)
693 .write(true)
694 .create(true)
695 .truncate(true)
696 .open(dwp_out_filename)?,
697 );
698 let mut output_stream = object::write::StreamingBuffer::new(output_stream);
699 package.finish()?.emit(&mut output_stream)?;
700 output_stream.result()?;
701 output_stream.into_inner().flush()?;
702
703 Ok(())
704 }) {
705 Ok(()) => {}
706 Err(e) => {
707 sess.emit_err(errors::ThorinErrorWrapper(e));
708 sess.abort_if_errors();
709 }
710 }
711 }
712
713 /// Create a dynamic library or executable.
714 ///
715 /// This will invoke the system linker/cc to create the resulting file. This links to all upstream
716 /// files as well.
link_natively<'a>( sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, crate_type: CrateType, out_filename: &Path, codegen_results: &CodegenResults, tmpdir: &Path, ) -> Result<(), ErrorGuaranteed>717 fn link_natively<'a>(
718 sess: &'a Session,
719 archive_builder_builder: &dyn ArchiveBuilderBuilder,
720 crate_type: CrateType,
721 out_filename: &Path,
722 codegen_results: &CodegenResults,
723 tmpdir: &Path,
724 ) -> Result<(), ErrorGuaranteed> {
725 info!("preparing {:?} to {:?}", crate_type, out_filename);
726 let (linker_path, flavor) = linker_and_flavor(sess);
727 let mut cmd = linker_with_args(
728 &linker_path,
729 flavor,
730 sess,
731 archive_builder_builder,
732 crate_type,
733 tmpdir,
734 out_filename,
735 codegen_results,
736 )?;
737
738 linker::disable_localization(&mut cmd);
739
740 for (k, v) in sess.target.link_env.as_ref() {
741 cmd.env(k.as_ref(), v.as_ref());
742 }
743 for k in sess.target.link_env_remove.as_ref() {
744 cmd.env_remove(k.as_ref());
745 }
746
747 if sess.opts.prints.contains(&PrintRequest::LinkArgs) {
748 println!("{:?}", &cmd);
749 }
750
751 // May have not found libraries in the right formats.
752 sess.abort_if_errors();
753
754 // Invoke the system linker
755 info!("{:?}", &cmd);
756 let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
757 let unknown_arg_regex =
758 Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
759 let mut prog;
760 let mut i = 0;
761 loop {
762 i += 1;
763 prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
764 let Ok(ref output) = prog else {
765 break;
766 };
767 if output.status.success() {
768 break;
769 }
770 let mut out = output.stderr.clone();
771 out.extend(&output.stdout);
772 let out = String::from_utf8_lossy(&out);
773
774 // Check to see if the link failed with an error message that indicates it
775 // doesn't recognize the -no-pie option. If so, re-perform the link step
776 // without it. This is safe because if the linker doesn't support -no-pie
777 // then it should not default to linking executables as pie. Different
778 // versions of gcc seem to use different quotes in the error message so
779 // don't check for them.
780 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
781 && unknown_arg_regex.is_match(&out)
782 && out.contains("-no-pie")
783 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
784 {
785 info!("linker output: {:?}", out);
786 warn!("Linker does not support -no-pie command line option. Retrying without.");
787 for arg in cmd.take_args() {
788 if arg.to_string_lossy() != "-no-pie" {
789 cmd.arg(arg);
790 }
791 }
792 info!("{:?}", &cmd);
793 continue;
794 }
795
796 // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
797 // Fallback from '-static-pie' to '-static' in that case.
798 if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
799 && unknown_arg_regex.is_match(&out)
800 && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
801 && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
802 {
803 info!("linker output: {:?}", out);
804 warn!(
805 "Linker does not support -static-pie command line option. Retrying with -static instead."
806 );
807 // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
808 let self_contained = self_contained(sess, crate_type);
809 let opts = &sess.target;
810 let pre_objects = if self_contained {
811 &opts.pre_link_objects_self_contained
812 } else {
813 &opts.pre_link_objects
814 };
815 let post_objects = if self_contained {
816 &opts.post_link_objects_self_contained
817 } else {
818 &opts.post_link_objects
819 };
820 let get_objects = |objects: &CrtObjects, kind| {
821 objects
822 .get(&kind)
823 .iter()
824 .copied()
825 .flatten()
826 .map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
827 .collect::<Vec<_>>()
828 };
829 let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
830 let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
831 let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
832 let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
833 // Assume that we know insertion positions for the replacement arguments from replaced
834 // arguments, which is true for all supported targets.
835 assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
836 assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
837 for arg in cmd.take_args() {
838 if arg.to_string_lossy() == "-static-pie" {
839 // Replace the output kind.
840 cmd.arg("-static");
841 } else if pre_objects_static_pie.contains(&arg) {
842 // Replace the pre-link objects (replace the first and remove the rest).
843 cmd.args(mem::take(&mut pre_objects_static));
844 } else if post_objects_static_pie.contains(&arg) {
845 // Replace the post-link objects (replace the first and remove the rest).
846 cmd.args(mem::take(&mut post_objects_static));
847 } else {
848 cmd.arg(arg);
849 }
850 }
851 info!("{:?}", &cmd);
852 continue;
853 }
854
855 // Here's a terribly awful hack that really shouldn't be present in any
856 // compiler. Here an environment variable is supported to automatically
857 // retry the linker invocation if the linker looks like it segfaulted.
858 //
859 // Gee that seems odd, normally segfaults are things we want to know
860 // about! Unfortunately though in rust-lang/rust#38878 we're
861 // experiencing the linker segfaulting on Travis quite a bit which is
862 // causing quite a bit of pain to land PRs when they spuriously fail
863 // due to a segfault.
864 //
865 // The issue #38878 has some more debugging information on it as well,
866 // but this unfortunately looks like it's just a race condition in
867 // macOS's linker with some thread pool working in the background. It
868 // seems that no one currently knows a fix for this so in the meantime
869 // we're left with this...
870 if !retry_on_segfault || i > 3 {
871 break;
872 }
873 let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
874 let msg_bus = "clang: error: unable to execute command: Bus error: 10";
875 if out.contains(msg_segv) || out.contains(msg_bus) {
876 warn!(
877 ?cmd, %out,
878 "looks like the linker segfaulted when we tried to call it, \
879 automatically retrying again",
880 );
881 continue;
882 }
883
884 if is_illegal_instruction(&output.status) {
885 warn!(
886 ?cmd, %out, status = %output.status,
887 "looks like the linker hit an illegal instruction when we \
888 tried to call it, automatically retrying again.",
889 );
890 continue;
891 }
892
893 #[cfg(unix)]
894 fn is_illegal_instruction(status: &ExitStatus) -> bool {
895 use std::os::unix::prelude::*;
896 status.signal() == Some(libc::SIGILL)
897 }
898
899 #[cfg(not(unix))]
900 fn is_illegal_instruction(_status: &ExitStatus) -> bool {
901 false
902 }
903 }
904
905 match prog {
906 Ok(prog) => {
907 if !prog.status.success() {
908 let mut output = prog.stderr.clone();
909 output.extend_from_slice(&prog.stdout);
910 let escaped_output = escape_linker_output(&output, flavor);
911 // FIXME: Add UI tests for this error.
912 let err = errors::LinkingFailed {
913 linker_path: &linker_path,
914 exit_status: prog.status,
915 command: &cmd,
916 escaped_output,
917 };
918 sess.diagnostic().emit_err(err);
919 // If MSVC's `link.exe` was expected but the return code
920 // is not a Microsoft LNK error then suggest a way to fix or
921 // install the Visual Studio build tools.
922 if let Some(code) = prog.status.code() {
923 if sess.target.is_like_msvc
924 && flavor == LinkerFlavor::Msvc(Lld::No)
925 // Respect the command line override
926 && sess.opts.cg.linker.is_none()
927 // Match exactly "link.exe"
928 && linker_path.to_str() == Some("link.exe")
929 // All Microsoft `link.exe` linking error codes are
930 // four digit numbers in the range 1000 to 9999 inclusive
931 && (code < 1000 || code > 9999)
932 {
933 let is_vs_installed = windows_registry::find_vs_version().is_ok();
934 let has_linker = windows_registry::find_tool(
935 &sess.opts.target_triple.triple(),
936 "link.exe",
937 )
938 .is_some();
939
940 sess.emit_note(errors::LinkExeUnexpectedError);
941 if is_vs_installed && has_linker {
942 // the linker is broken
943 sess.emit_note(errors::RepairVSBuildTools);
944 sess.emit_note(errors::MissingCppBuildToolComponent);
945 } else if is_vs_installed {
946 // the linker is not installed
947 sess.emit_note(errors::SelectCppBuildToolWorkload);
948 } else {
949 // visual studio is not installed
950 sess.emit_note(errors::VisualStudioNotInstalled);
951 }
952 }
953 }
954
955 sess.abort_if_errors();
956 }
957 info!("linker stderr:\n{}", escape_string(&prog.stderr));
958 info!("linker stdout:\n{}", escape_string(&prog.stdout));
959 }
960 Err(e) => {
961 let linker_not_found = e.kind() == io::ErrorKind::NotFound;
962
963 if linker_not_found {
964 sess.emit_err(errors::LinkerNotFound { linker_path, error: e });
965 } else {
966 sess.emit_err(errors::UnableToExeLinker {
967 linker_path,
968 error: e,
969 command_formatted: format!("{:?}", &cmd),
970 });
971 }
972
973 if sess.target.is_like_msvc && linker_not_found {
974 sess.emit_note(errors::MsvcMissingLinker);
975 sess.emit_note(errors::CheckInstalledVisualStudio);
976 sess.emit_note(errors::InsufficientVSCodeProduct);
977 }
978 sess.abort_if_errors();
979 }
980 }
981
982 match sess.split_debuginfo() {
983 // If split debug information is disabled or located in individual files
984 // there's nothing to do here.
985 SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
986
987 // If packed split-debuginfo is requested, but the final compilation
988 // doesn't actually have any debug information, then we skip this step.
989 SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
990
991 // On macOS the external `dsymutil` tool is used to create the packed
992 // debug information. Note that this will read debug information from
993 // the objects on the filesystem which we'll clean up later.
994 SplitDebuginfo::Packed if sess.target.is_like_osx => {
995 let prog = Command::new("dsymutil").arg(out_filename).output();
996 match prog {
997 Ok(prog) => {
998 if !prog.status.success() {
999 let mut output = prog.stderr.clone();
1000 output.extend_from_slice(&prog.stdout);
1001 sess.emit_warning(errors::ProcessingDymutilFailed {
1002 status: prog.status,
1003 output: escape_string(&output),
1004 });
1005 }
1006 }
1007 Err(error) => sess.emit_fatal(errors::UnableToRunDsymutil { error }),
1008 }
1009 }
1010
1011 // On MSVC packed debug information is produced by the linker itself so
1012 // there's no need to do anything else here.
1013 SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1014
1015 // ... and otherwise we're processing a `*.dwp` packed dwarf file.
1016 //
1017 // We cannot rely on the .o paths in the executable because they may have been
1018 // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1019 // the .o/.dwo paths explicitly.
1020 SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1021 }
1022
1023 let strip = strip_value(sess);
1024
1025 if sess.target.is_like_osx {
1026 match (strip, crate_type) {
1027 (Strip::Debuginfo, _) => {
1028 strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-S"))
1029 }
1030 // Per the manpage, `-x` is the maximum safe strip level for dynamic libraries. (#93988)
1031 (Strip::Symbols, CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro) => {
1032 strip_symbols_with_external_utility(sess, "strip", &out_filename, Some("-x"))
1033 }
1034 (Strip::Symbols, _) => {
1035 strip_symbols_with_external_utility(sess, "strip", &out_filename, None)
1036 }
1037 (Strip::None, _) => {}
1038 }
1039 }
1040
1041 if sess.target.os == "illumos" {
1042 // Many illumos systems will have both the native 'strip' utility and
1043 // the GNU one. Use the native version explicitly and do not rely on
1044 // what's in the path.
1045 let stripcmd = "/usr/bin/strip";
1046 match strip {
1047 // Always preserve the symbol table (-x).
1048 Strip::Debuginfo => {
1049 strip_symbols_with_external_utility(sess, stripcmd, &out_filename, Some("-x"))
1050 }
1051 // Strip::Symbols is handled via the --strip-all linker option.
1052 Strip::Symbols => {}
1053 Strip::None => {}
1054 }
1055 }
1056
1057 Ok(())
1058 }
1059
1060 // Temporarily support both -Z strip and -C strip
strip_value(sess: &Session) -> Strip1061 fn strip_value(sess: &Session) -> Strip {
1062 match (sess.opts.unstable_opts.strip, sess.opts.cg.strip) {
1063 (s, Strip::None) => s,
1064 (_, s) => s,
1065 }
1066 }
1067
strip_symbols_with_external_utility<'a>( sess: &'a Session, util: &str, out_filename: &Path, option: Option<&str>, )1068 fn strip_symbols_with_external_utility<'a>(
1069 sess: &'a Session,
1070 util: &str,
1071 out_filename: &Path,
1072 option: Option<&str>,
1073 ) {
1074 let mut cmd = Command::new(util);
1075 if let Some(option) = option {
1076 cmd.arg(option);
1077 }
1078 let prog = cmd.arg(out_filename).output();
1079 match prog {
1080 Ok(prog) => {
1081 if !prog.status.success() {
1082 let mut output = prog.stderr.clone();
1083 output.extend_from_slice(&prog.stdout);
1084 sess.emit_warning(errors::StrippingDebugInfoFailed {
1085 util,
1086 status: prog.status,
1087 output: escape_string(&output),
1088 });
1089 }
1090 }
1091 Err(error) => sess.emit_fatal(errors::UnableToRun { util, error }),
1092 }
1093 }
1094
escape_string(s: &[u8]) -> String1095 fn escape_string(s: &[u8]) -> String {
1096 match str::from_utf8(s) {
1097 Ok(s) => s.to_owned(),
1098 Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1099 }
1100 }
1101
1102 #[cfg(not(windows))]
escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String1103 fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1104 escape_string(s)
1105 }
1106
1107 /// If the output of the msvc linker is not UTF-8 and the host is Windows,
1108 /// then try to convert the string from the OEM encoding.
1109 #[cfg(windows)]
escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String1110 fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1111 // This only applies to the actual MSVC linker.
1112 if flavour != LinkerFlavor::Msvc(Lld::No) {
1113 return escape_string(s);
1114 }
1115 match str::from_utf8(s) {
1116 Ok(s) => return s.to_owned(),
1117 Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1118 Some(s) => s,
1119 // The string is not UTF-8 and isn't valid for the OEM code page
1120 None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1121 },
1122 }
1123 }
1124
1125 /// Wrappers around the Windows API.
1126 #[cfg(windows)]
1127 mod win {
1128 use windows::Win32::Globalization::{
1129 GetLocaleInfoEx, MultiByteToWideChar, CP_OEMCP, LOCALE_IUSEUTF8LEGACYOEMCP,
1130 LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS,
1131 };
1132
1133 /// Get the Windows system OEM code page. This is most notably the code page
1134 /// used for link.exe's output.
oem_code_page() -> u321135 pub fn oem_code_page() -> u32 {
1136 unsafe {
1137 let mut cp: u32 = 0;
1138 // We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1139 // But the API requires us to pass the data as though it's a [u16] string.
1140 let len = std::mem::size_of::<u32>() / std::mem::size_of::<u16>();
1141 let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1142 let len_written = GetLocaleInfoEx(
1143 LOCALE_NAME_SYSTEM_DEFAULT,
1144 LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1145 Some(data),
1146 );
1147 if len_written as usize == len { cp } else { CP_OEMCP }
1148 }
1149 }
1150 /// Try to convert a multi-byte string to a UTF-8 string using the given code page
1151 /// The string does not need to be null terminated.
1152 ///
1153 /// This is implemented as a wrapper around `MultiByteToWideChar`.
1154 /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1155 ///
1156 /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1157 /// any invalid bytes for the expected encoding.
locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String>1158 pub fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1159 // `MultiByteToWideChar` requires a length to be a "positive integer".
1160 if s.len() > isize::MAX as usize {
1161 return None;
1162 }
1163 // Error if the string is not valid for the expected code page.
1164 let flags = MB_ERR_INVALID_CHARS;
1165 // Call MultiByteToWideChar twice.
1166 // First to calculate the length then to convert the string.
1167 let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1168 if len > 0 {
1169 let mut utf16 = vec![0; len as usize];
1170 len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1171 if len > 0 {
1172 return utf16.get(..len as usize).map(String::from_utf16_lossy);
1173 }
1174 }
1175 None
1176 }
1177 }
1178
add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker)1179 fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
1180 // On macOS the runtimes are distributed as dylibs which should be linked to
1181 // both executables and dynamic shared objects. Everywhere else the runtimes
1182 // are currently distributed as static libraries which should be linked to
1183 // executables only.
1184 let needs_runtime = !sess.target.is_like_android
1185 && match crate_type {
1186 CrateType::Executable => true,
1187 CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro => sess.target.is_like_osx,
1188 CrateType::Rlib | CrateType::Staticlib => false,
1189 };
1190
1191 if !needs_runtime {
1192 return;
1193 }
1194
1195 let sanitizer = sess.opts.unstable_opts.sanitizer;
1196 if sanitizer.contains(SanitizerSet::ADDRESS) {
1197 link_sanitizer_runtime(sess, linker, "asan");
1198 }
1199 if sanitizer.contains(SanitizerSet::LEAK) {
1200 link_sanitizer_runtime(sess, linker, "lsan");
1201 }
1202 if sanitizer.contains(SanitizerSet::MEMORY) {
1203 link_sanitizer_runtime(sess, linker, "msan");
1204 }
1205 if sanitizer.contains(SanitizerSet::THREAD) {
1206 link_sanitizer_runtime(sess, linker, "tsan");
1207 }
1208 if sanitizer.contains(SanitizerSet::HWADDRESS) {
1209 link_sanitizer_runtime(sess, linker, "hwasan");
1210 }
1211 if sanitizer.contains(SanitizerSet::SAFESTACK) {
1212 link_sanitizer_runtime(sess, linker, "safestack");
1213 }
1214 }
1215
link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str)1216 fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
1217 fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1218 let session_tlib =
1219 filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
1220 let path = session_tlib.join(filename);
1221 if path.exists() {
1222 return session_tlib;
1223 } else {
1224 let default_sysroot =
1225 filesearch::get_or_default_sysroot().expect("Failed finding sysroot");
1226 let default_tlib = filesearch::make_target_lib_path(
1227 &default_sysroot,
1228 sess.opts.target_triple.triple(),
1229 );
1230 return default_tlib;
1231 }
1232 }
1233
1234 let channel = option_env!("CFG_RELEASE_CHANNEL")
1235 .map(|channel| format!("-{}", channel))
1236 .unwrap_or_default();
1237
1238 if sess.target.is_like_osx {
1239 // On Apple platforms, the sanitizer is always built as a dylib, and
1240 // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1241 // rpath to the library as well (the rpath should be absolute, see
1242 // PR #41352 for details).
1243 let filename = format!("rustc{}_rt.{}", channel, name);
1244 let path = find_sanitizer_runtime(&sess, &filename);
1245 let rpath = path.to_str().expect("non-utf8 component in path");
1246 linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
1247 linker.link_dylib(&filename, false, true);
1248 } else {
1249 let filename = format!("librustc{}_rt.{}.a", channel, name);
1250 let path = find_sanitizer_runtime(&sess, &filename).join(&filename);
1251 linker.link_whole_rlib(&path);
1252 }
1253 }
1254
1255 /// Returns a boolean indicating whether the specified crate should be ignored
1256 /// during LTO.
1257 ///
1258 /// Crates ignored during LTO are not lumped together in the "massive object
1259 /// file" that we create and are linked in their normal rlib states. See
1260 /// comments below for what crates do not participate in LTO.
1261 ///
1262 /// It's unusual for a crate to not participate in LTO. Typically only
1263 /// compiler-specific and unstable crates have a reason to not participate in
1264 /// LTO.
ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool1265 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1266 // If our target enables builtin function lowering in LLVM then the
1267 // crates providing these functions don't participate in LTO (e.g.
1268 // no_builtins or compiler builtins crates).
1269 !sess.target.no_builtins
1270 && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1271 }
1272
1273 /// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor)1274 pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1275 fn infer_from(
1276 sess: &Session,
1277 linker: Option<PathBuf>,
1278 flavor: Option<LinkerFlavor>,
1279 ) -> Option<(PathBuf, LinkerFlavor)> {
1280 match (linker, flavor) {
1281 (Some(linker), Some(flavor)) => Some((linker, flavor)),
1282 // only the linker flavor is known; use the default linker for the selected flavor
1283 (None, Some(flavor)) => Some((
1284 PathBuf::from(match flavor {
1285 LinkerFlavor::Gnu(Cc::Yes, _)
1286 | LinkerFlavor::Darwin(Cc::Yes, _)
1287 | LinkerFlavor::WasmLld(Cc::Yes)
1288 | LinkerFlavor::Unix(Cc::Yes) => {
1289 if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1290 // On historical Solaris systems, "cc" may have
1291 // been Sun Studio, which is not flag-compatible
1292 // with "gcc". This history casts a long shadow,
1293 // and many modern illumos distributions today
1294 // ship GCC as "gcc" without also making it
1295 // available as "cc".
1296 "gcc"
1297 } else {
1298 "cc"
1299 }
1300 }
1301 LinkerFlavor::Gnu(_, Lld::Yes)
1302 | LinkerFlavor::Darwin(_, Lld::Yes)
1303 | LinkerFlavor::WasmLld(..)
1304 | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1305 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1306 "ld"
1307 }
1308 LinkerFlavor::Msvc(..) => "link.exe",
1309 LinkerFlavor::EmCc => {
1310 if cfg!(windows) {
1311 "emcc.bat"
1312 } else {
1313 "emcc"
1314 }
1315 }
1316 LinkerFlavor::Bpf => "bpf-linker",
1317 LinkerFlavor::Ptx => "rust-ptx-linker",
1318 }),
1319 flavor,
1320 )),
1321 (Some(linker), None) => {
1322 let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1323 sess.emit_fatal(errors::LinkerFileStem);
1324 });
1325 let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1326 Some((linker, flavor))
1327 }
1328 (None, None) => None,
1329 }
1330 }
1331
1332 // linker and linker flavor specified via command line have precedence over what the target
1333 // specification specifies
1334 let linker_flavor =
1335 sess.opts.cg.linker_flavor.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor));
1336 if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor) {
1337 return ret;
1338 }
1339
1340 if let Some(ret) = infer_from(
1341 sess,
1342 sess.target.linker.as_deref().map(PathBuf::from),
1343 Some(sess.target.linker_flavor),
1344 ) {
1345 return ret;
1346 }
1347
1348 bug!("Not enough information provided to determine how to invoke the linker");
1349 }
1350
1351 /// Returns a pair of boolean indicating whether we should preserve the object and
1352 /// dwarf object files on the filesystem for their debug information. This is often
1353 /// useful with split-dwarf like schemes.
preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool)1354 fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1355 // If the objects don't have debuginfo there's nothing to preserve.
1356 if sess.opts.debuginfo == config::DebugInfo::None {
1357 return (false, false);
1358 }
1359
1360 match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1361 // If there is no split debuginfo then do not preserve objects.
1362 (SplitDebuginfo::Off, _) => (false, false),
1363 // If there is packed split debuginfo, then the debuginfo in the objects
1364 // has been packaged and the objects can be deleted.
1365 (SplitDebuginfo::Packed, _) => (false, false),
1366 // If there is unpacked split debuginfo and the current target can not use
1367 // split dwarf, then keep objects.
1368 (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1369 // If there is unpacked split debuginfo and the target can use split dwarf, then
1370 // keep the object containing that debuginfo (whether that is an object file or
1371 // dwarf object file depends on the split dwarf kind).
1372 (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1373 (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1374 }
1375 }
1376
archive_search_paths(sess: &Session) -> Vec<PathBuf>1377 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
1378 sess.target_filesearch(PathKind::Native).search_path_dirs()
1379 }
1380
1381 #[derive(PartialEq)]
1382 enum RlibFlavor {
1383 Normal,
1384 StaticlibBase,
1385 }
1386
print_native_static_libs( sess: &Session, all_native_libs: &[NativeLib], all_rust_dylibs: &[&Path], )1387 fn print_native_static_libs(
1388 sess: &Session,
1389 all_native_libs: &[NativeLib],
1390 all_rust_dylibs: &[&Path],
1391 ) {
1392 let mut lib_args: Vec<_> = all_native_libs
1393 .iter()
1394 .filter(|l| relevant_lib(sess, l))
1395 .filter_map(|lib| {
1396 let name = lib.name;
1397 match lib.kind {
1398 NativeLibKind::Static { bundle: Some(false), .. }
1399 | NativeLibKind::Dylib { .. }
1400 | NativeLibKind::Unspecified => {
1401 let verbatim = lib.verbatim;
1402 if sess.target.is_like_msvc {
1403 Some(format!("{}{}", name, if verbatim { "" } else { ".lib" }))
1404 } else if sess.target.linker_flavor.is_gnu() {
1405 Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1406 } else {
1407 Some(format!("-l{}", name))
1408 }
1409 }
1410 NativeLibKind::Framework { .. } => {
1411 // ld-only syntax, since there are no frameworks in MSVC
1412 Some(format!("-framework {}", name))
1413 }
1414 // These are included, no need to print them
1415 NativeLibKind::Static { bundle: None | Some(true), .. }
1416 | NativeLibKind::LinkArg
1417 | NativeLibKind::WasmImportModule
1418 | NativeLibKind::RawDylib => None,
1419 }
1420 })
1421 .collect();
1422 for path in all_rust_dylibs {
1423 // FIXME deduplicate with add_dynamic_crate
1424
1425 // Just need to tell the linker about where the library lives and
1426 // what its name is
1427 let parent = path.parent();
1428 if let Some(dir) = parent {
1429 let dir = fix_windows_verbatim_for_gcc(dir);
1430 if sess.target.is_like_msvc {
1431 let mut arg = String::from("/LIBPATH:");
1432 arg.push_str(&dir.display().to_string());
1433 lib_args.push(arg);
1434 } else {
1435 lib_args.push("-L".to_owned());
1436 lib_args.push(dir.display().to_string());
1437 }
1438 }
1439 let stem = path.file_stem().unwrap().to_str().unwrap();
1440 // Convert library file-stem into a cc -l argument.
1441 let prefix = if stem.starts_with("lib") && !sess.target.is_like_windows { 3 } else { 0 };
1442 let lib = &stem[prefix..];
1443 let path = parent.unwrap_or_else(|| Path::new(""));
1444 if sess.target.is_like_msvc {
1445 // When producing a dll, the MSVC linker may not actually emit a
1446 // `foo.lib` file if the dll doesn't actually export any symbols, so we
1447 // check to see if the file is there and just omit linking to it if it's
1448 // not present.
1449 let name = format!("{}.dll.lib", lib);
1450 if path.join(&name).exists() {
1451 lib_args.push(name);
1452 }
1453 } else {
1454 lib_args.push(format!("-l{}", lib));
1455 }
1456 }
1457 if !lib_args.is_empty() {
1458 sess.emit_note(errors::StaticLibraryNativeArtifacts);
1459 // Prefix for greppability
1460 // Note: This must not be translated as tools are allowed to depend on this exact string.
1461 sess.note_without_error(format!("native-static-libs: {}", &lib_args.join(" ")));
1462 }
1463 }
1464
get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf1465 fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1466 let fs = sess.target_filesearch(PathKind::Native);
1467 let file_path = fs.get_lib_path().join(name);
1468 if file_path.exists() {
1469 return file_path;
1470 }
1471 // Special directory with objects used only in self-contained linkage mode
1472 if self_contained {
1473 let file_path = fs.get_self_contained_lib_path().join(name);
1474 if file_path.exists() {
1475 return file_path;
1476 }
1477 }
1478 for search_path in fs.search_paths() {
1479 let file_path = search_path.dir.join(name);
1480 if file_path.exists() {
1481 return file_path;
1482 }
1483 }
1484 PathBuf::from(name)
1485 }
1486
exec_linker( sess: &Session, cmd: &Command, out_filename: &Path, tmpdir: &Path, ) -> io::Result<Output>1487 fn exec_linker(
1488 sess: &Session,
1489 cmd: &Command,
1490 out_filename: &Path,
1491 tmpdir: &Path,
1492 ) -> io::Result<Output> {
1493 // When attempting to spawn the linker we run a risk of blowing out the
1494 // size limits for spawning a new process with respect to the arguments
1495 // we pass on the command line.
1496 //
1497 // Here we attempt to handle errors from the OS saying "your list of
1498 // arguments is too big" by reinvoking the linker again with an `@`-file
1499 // that contains all the arguments. The theory is that this is then
1500 // accepted on all linkers and the linker will read all its options out of
1501 // there instead of looking at the command line.
1502 if !cmd.very_likely_to_exceed_some_spawn_limit() {
1503 match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1504 Ok(child) => {
1505 let output = child.wait_with_output();
1506 flush_linked_file(&output, out_filename)?;
1507 return output;
1508 }
1509 Err(ref e) if command_line_too_big(e) => {
1510 info!("command line to linker was too big: {}", e);
1511 }
1512 Err(e) => return Err(e),
1513 }
1514 }
1515
1516 info!("falling back to passing arguments to linker via an @-file");
1517 let mut cmd2 = cmd.clone();
1518 let mut args = String::new();
1519 for arg in cmd2.take_args() {
1520 args.push_str(
1521 &Escape { arg: arg.to_str().unwrap(), is_like_msvc: sess.target.is_like_msvc }
1522 .to_string(),
1523 );
1524 args.push('\n');
1525 }
1526 let file = tmpdir.join("linker-arguments");
1527 let bytes = if sess.target.is_like_msvc {
1528 let mut out = Vec::with_capacity((1 + args.len()) * 2);
1529 // start the stream with a UTF-16 BOM
1530 for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1531 // encode in little endian
1532 out.push(c as u8);
1533 out.push((c >> 8) as u8);
1534 }
1535 out
1536 } else {
1537 args.into_bytes()
1538 };
1539 fs::write(&file, &bytes)?;
1540 cmd2.arg(format!("@{}", file.display()));
1541 info!("invoking linker {:?}", cmd2);
1542 let output = cmd2.output();
1543 flush_linked_file(&output, out_filename)?;
1544 return output;
1545
1546 #[cfg(not(windows))]
1547 fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1548 Ok(())
1549 }
1550
1551 #[cfg(windows)]
1552 fn flush_linked_file(
1553 command_output: &io::Result<Output>,
1554 out_filename: &Path,
1555 ) -> io::Result<()> {
1556 // On Windows, under high I/O load, output buffers are sometimes not flushed,
1557 // even long after process exit, causing nasty, non-reproducible output bugs.
1558 //
1559 // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1560 //
1561 // А full writeup of the original Chrome bug can be found at
1562 // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1563
1564 if let &Ok(ref out) = command_output {
1565 if out.status.success() {
1566 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1567 of.sync_all()?;
1568 }
1569 }
1570 }
1571
1572 Ok(())
1573 }
1574
1575 #[cfg(unix)]
1576 fn command_line_too_big(err: &io::Error) -> bool {
1577 err.raw_os_error() == Some(::libc::E2BIG)
1578 }
1579
1580 #[cfg(windows)]
1581 fn command_line_too_big(err: &io::Error) -> bool {
1582 const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1583 err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1584 }
1585
1586 #[cfg(not(any(unix, windows)))]
1587 fn command_line_too_big(_: &io::Error) -> bool {
1588 false
1589 }
1590
1591 struct Escape<'a> {
1592 arg: &'a str,
1593 is_like_msvc: bool,
1594 }
1595
1596 impl<'a> fmt::Display for Escape<'a> {
1597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1598 if self.is_like_msvc {
1599 // This is "documented" at
1600 // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1601 //
1602 // Unfortunately there's not a great specification of the
1603 // syntax I could find online (at least) but some local
1604 // testing showed that this seemed sufficient-ish to catch
1605 // at least a few edge cases.
1606 write!(f, "\"")?;
1607 for c in self.arg.chars() {
1608 match c {
1609 '"' => write!(f, "\\{}", c)?,
1610 c => write!(f, "{}", c)?,
1611 }
1612 }
1613 write!(f, "\"")?;
1614 } else {
1615 // This is documented at https://linux.die.net/man/1/ld, namely:
1616 //
1617 // > Options in file are separated by whitespace. A whitespace
1618 // > character may be included in an option by surrounding the
1619 // > entire option in either single or double quotes. Any
1620 // > character (including a backslash) may be included by
1621 // > prefixing the character to be included with a backslash.
1622 //
1623 // We put an argument on each line, so all we need to do is
1624 // ensure the line is interpreted as one whole argument.
1625 for c in self.arg.chars() {
1626 match c {
1627 '\\' | ' ' => write!(f, "\\{}", c)?,
1628 c => write!(f, "{}", c)?,
1629 }
1630 }
1631 }
1632 Ok(())
1633 }
1634 }
1635 }
1636
link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind1637 fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1638 let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1639 (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1640 (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1641 LinkOutputKind::DynamicPicExe
1642 }
1643 (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1644 (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1645 LinkOutputKind::StaticPicExe
1646 }
1647 (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1648 (_, true, _) => LinkOutputKind::StaticDylib,
1649 (_, false, _) => LinkOutputKind::DynamicDylib,
1650 };
1651
1652 // Adjust the output kind to target capabilities.
1653 let opts = &sess.target;
1654 let pic_exe_supported = opts.position_independent_executables;
1655 let static_pic_exe_supported = opts.static_position_independent_executables;
1656 let static_dylib_supported = opts.crt_static_allows_dylibs;
1657 match kind {
1658 LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1659 LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1660 LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1661 _ => kind,
1662 }
1663 }
1664
1665 // Returns true if linker is located within sysroot
detect_self_contained_mingw(sess: &Session) -> bool1666 fn detect_self_contained_mingw(sess: &Session) -> bool {
1667 let (linker, _) = linker_and_flavor(&sess);
1668 // Assume `-C linker=rust-lld` as self-contained mode
1669 if linker == Path::new("rust-lld") {
1670 return true;
1671 }
1672 let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1673 linker.with_extension("exe")
1674 } else {
1675 linker
1676 };
1677 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1678 let full_path = dir.join(&linker_with_extension);
1679 // If linker comes from sysroot assume self-contained mode
1680 if full_path.is_file() && !full_path.starts_with(&sess.sysroot) {
1681 return false;
1682 }
1683 }
1684 true
1685 }
1686
1687 /// Various toolchain components used during linking are used from rustc distribution
1688 /// instead of being found somewhere on the host system.
1689 /// We only provide such support for a very limited number of targets.
self_contained(sess: &Session, crate_type: CrateType) -> bool1690 fn self_contained(sess: &Session, crate_type: CrateType) -> bool {
1691 if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1692 if sess.target.link_self_contained == LinkSelfContainedDefault::False {
1693 sess.emit_err(errors::UnsupportedLinkSelfContained);
1694 }
1695 return self_contained;
1696 }
1697
1698 match sess.target.link_self_contained {
1699 LinkSelfContainedDefault::False => false,
1700 LinkSelfContainedDefault::True => true,
1701 // FIXME: Find a better heuristic for "native musl toolchain is available",
1702 // based on host and linker path, for example.
1703 // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1704 LinkSelfContainedDefault::Musl => sess.crt_static(Some(crate_type)),
1705 LinkSelfContainedDefault::Mingw => {
1706 sess.host == sess.target
1707 && sess.target.vendor != "uwp"
1708 && detect_self_contained_mingw(&sess)
1709 }
1710 }
1711 }
1712
1713 /// Add pre-link object files defined by the target spec.
add_pre_link_objects( cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor, link_output_kind: LinkOutputKind, self_contained: bool, )1714 fn add_pre_link_objects(
1715 cmd: &mut dyn Linker,
1716 sess: &Session,
1717 flavor: LinkerFlavor,
1718 link_output_kind: LinkOutputKind,
1719 self_contained: bool,
1720 ) {
1721 // FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1722 // so Fuchsia has to be special-cased.
1723 let opts = &sess.target;
1724 let empty = Default::default();
1725 let objects = if self_contained {
1726 &opts.pre_link_objects_self_contained
1727 } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1728 &opts.pre_link_objects
1729 } else {
1730 &empty
1731 };
1732 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1733 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1734 }
1735 }
1736
1737 /// Add post-link object files defined by the target spec.
add_post_link_objects( cmd: &mut dyn Linker, sess: &Session, link_output_kind: LinkOutputKind, self_contained: bool, )1738 fn add_post_link_objects(
1739 cmd: &mut dyn Linker,
1740 sess: &Session,
1741 link_output_kind: LinkOutputKind,
1742 self_contained: bool,
1743 ) {
1744 let objects = if self_contained {
1745 &sess.target.post_link_objects_self_contained
1746 } else {
1747 &sess.target.post_link_objects
1748 };
1749 for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1750 cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1751 }
1752 }
1753
1754 /// Add arbitrary "pre-link" args defined by the target spec or from command line.
1755 /// FIXME: Determine where exactly these args need to be inserted.
add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor)1756 fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1757 if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1758 cmd.args(args.iter().map(Deref::deref));
1759 }
1760 cmd.args(&sess.opts.unstable_opts.pre_link_args);
1761 }
1762
1763 /// Add a link script embedded in the target, if applicable.
add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType)1764 fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1765 match (crate_type, &sess.target.link_script) {
1766 (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1767 if !sess.target.linker_flavor.is_gnu() {
1768 sess.emit_fatal(errors::LinkScriptUnavailable);
1769 }
1770
1771 let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1772
1773 let path = tmpdir.join(file_name);
1774 if let Err(error) = fs::write(&path, script.as_ref()) {
1775 sess.emit_fatal(errors::LinkScriptWriteFailure { path, error });
1776 }
1777
1778 cmd.arg("--script");
1779 cmd.arg(path);
1780 }
1781 _ => {}
1782 }
1783 }
1784
1785 /// Add arbitrary "user defined" args defined from command line.
1786 /// FIXME: Determine where exactly these args need to be inserted.
add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session)1787 fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1788 cmd.args(&sess.opts.cg.link_args);
1789 }
1790
1791 /// Add arbitrary "late link" args defined by the target spec.
1792 /// FIXME: Determine where exactly these args need to be inserted.
add_late_link_args( cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor, crate_type: CrateType, codegen_results: &CodegenResults, )1793 fn add_late_link_args(
1794 cmd: &mut dyn Linker,
1795 sess: &Session,
1796 flavor: LinkerFlavor,
1797 crate_type: CrateType,
1798 codegen_results: &CodegenResults,
1799 ) {
1800 let any_dynamic_crate = crate_type == CrateType::Dylib
1801 || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1802 *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1803 });
1804 if any_dynamic_crate {
1805 if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1806 cmd.args(args.iter().map(Deref::deref));
1807 }
1808 } else {
1809 if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1810 cmd.args(args.iter().map(Deref::deref));
1811 }
1812 }
1813 if let Some(args) = sess.target.late_link_args.get(&flavor) {
1814 cmd.args(args.iter().map(Deref::deref));
1815 }
1816 }
1817
1818 /// Add arbitrary "post-link" args defined by the target spec.
1819 /// FIXME: Determine where exactly these args need to be inserted.
add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor)1820 fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1821 if let Some(args) = sess.target.post_link_args.get(&flavor) {
1822 cmd.args(args.iter().map(Deref::deref));
1823 }
1824 }
1825
1826 /// Add a synthetic object file that contains reference to all symbols that we want to expose to
1827 /// the linker.
1828 ///
1829 /// Background: we implement rlibs as static library (archives). Linkers treat archives
1830 /// differently from object files: all object files participate in linking, while archives will
1831 /// only participate in linking if they can satisfy at least one undefined reference (version
1832 /// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1833 /// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1834 /// can't keep them either. This causes #47384.
1835 ///
1836 /// To keep them around, we could use `--whole-archive` and equivalents to force rlib to
1837 /// participate in linking like object files, but this proves to be expensive (#93791). Therefore
1838 /// we instead just introduce an undefined reference to them. This could be done by `-u` command
1839 /// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1840 /// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1841 /// from removing them, and this is especially problematic for embedded programming where every
1842 /// byte counts.
1843 ///
1844 /// This method creates a synthetic object file, which contains undefined references to all symbols
1845 /// that are necessary for the linking. They are only present in symbol table but not actually
1846 /// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1847 /// unused `#[no_mangle]` or `#[used]` can still be discard by GC sections.
1848 ///
1849 /// There's a few internal crates in the standard library (aka libcore and
1850 /// libstd) which actually have a circular dependence upon one another. This
1851 /// currently arises through "weak lang items" where libcore requires things
1852 /// like `rust_begin_unwind` but libstd ends up defining it. To get this
1853 /// circular dependence to work correctly we declare some of these things
1854 /// in this synthetic object.
add_linked_symbol_object( cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, symbols: &[(String, SymbolExportKind)], )1855 fn add_linked_symbol_object(
1856 cmd: &mut dyn Linker,
1857 sess: &Session,
1858 tmpdir: &Path,
1859 symbols: &[(String, SymbolExportKind)],
1860 ) {
1861 if symbols.is_empty() {
1862 return;
1863 }
1864
1865 let Some(mut file) = super::metadata::create_object_file(sess) else {
1866 return;
1867 };
1868
1869 // NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1870 // so add an empty section.
1871 if file.format() == object::BinaryFormat::Coff {
1872 file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1873
1874 // We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1875 // default mangler in `object` crate.
1876 file.set_mangling(object::write::Mangling::None);
1877
1878 // Add feature flags to the object file. On MSVC this is optional but LLD will complain if
1879 // not present.
1880 let mut feature = 0;
1881
1882 if file.architecture() == object::Architecture::I386 {
1883 // Indicate that all SEH handlers are registered in .sxdata section.
1884 // We don't have generate any code, so we don't need .sxdata section but LLD still
1885 // expects us to set this bit (see #96498).
1886 // Reference: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
1887 feature |= 1;
1888 }
1889
1890 file.add_symbol(object::write::Symbol {
1891 name: "@feat.00".into(),
1892 value: feature,
1893 size: 0,
1894 kind: object::SymbolKind::Data,
1895 scope: object::SymbolScope::Compilation,
1896 weak: false,
1897 section: object::write::SymbolSection::Absolute,
1898 flags: object::SymbolFlags::None,
1899 });
1900 }
1901
1902 for (sym, kind) in symbols.iter() {
1903 file.add_symbol(object::write::Symbol {
1904 name: sym.clone().into(),
1905 value: 0,
1906 size: 0,
1907 kind: match kind {
1908 SymbolExportKind::Text => object::SymbolKind::Text,
1909 SymbolExportKind::Data => object::SymbolKind::Data,
1910 SymbolExportKind::Tls => object::SymbolKind::Tls,
1911 },
1912 scope: object::SymbolScope::Unknown,
1913 weak: false,
1914 section: object::write::SymbolSection::Undefined,
1915 flags: object::SymbolFlags::None,
1916 });
1917 }
1918
1919 let path = tmpdir.join("symbols.o");
1920 let result = std::fs::write(&path, file.write().unwrap());
1921 if let Err(error) = result {
1922 sess.emit_fatal(errors::FailedToWrite { path, error });
1923 }
1924 cmd.add_object(&path);
1925 }
1926
1927 /// Add object files containing code from the current crate.
add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults)1928 fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1929 for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
1930 cmd.add_object(obj);
1931 }
1932 }
1933
1934 /// Add object files for allocator code linked once for the whole crate tree.
add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults)1935 fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
1936 if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
1937 cmd.add_object(obj);
1938 }
1939 }
1940
1941 /// Add object files containing metadata for the current crate.
add_local_crate_metadata_objects( cmd: &mut dyn Linker, crate_type: CrateType, codegen_results: &CodegenResults, )1942 fn add_local_crate_metadata_objects(
1943 cmd: &mut dyn Linker,
1944 crate_type: CrateType,
1945 codegen_results: &CodegenResults,
1946 ) {
1947 // When linking a dynamic library, we put the metadata into a section of the
1948 // executable. This metadata is in a separate object file from the main
1949 // object file, so we link that in here.
1950 if crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro {
1951 if let Some(obj) = codegen_results.metadata_module.as_ref().and_then(|m| m.object.as_ref())
1952 {
1953 cmd.add_object(obj);
1954 }
1955 }
1956 }
1957
1958 /// Add sysroot and other globally set directories to the directory search list.
add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool)1959 fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) {
1960 // The default library location, we need this to find the runtime.
1961 // The location of crates will be determined as needed.
1962 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
1963 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1964
1965 // Special directory with libraries used only in self-contained linkage mode
1966 if self_contained {
1967 let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path();
1968 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
1969 }
1970 }
1971
1972 /// Add options making relocation sections in the produced ELF files read-only
1973 /// and suppressing lazy binding.
add_relro_args(cmd: &mut dyn Linker, sess: &Session)1974 fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
1975 match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
1976 RelroLevel::Full => cmd.full_relro(),
1977 RelroLevel::Partial => cmd.partial_relro(),
1978 RelroLevel::Off => cmd.no_relro(),
1979 RelroLevel::None => {}
1980 }
1981 }
1982
1983 /// Add library search paths used at runtime by dynamic linkers.
add_rpath_args( cmd: &mut dyn Linker, sess: &Session, codegen_results: &CodegenResults, out_filename: &Path, )1984 fn add_rpath_args(
1985 cmd: &mut dyn Linker,
1986 sess: &Session,
1987 codegen_results: &CodegenResults,
1988 out_filename: &Path,
1989 ) {
1990 // FIXME (#2397): At some point we want to rpath our guesses as to
1991 // where extern libraries might live, based on the
1992 // add_lib_search_paths
1993 if sess.opts.cg.rpath {
1994 let libs = codegen_results
1995 .crate_info
1996 .used_crates
1997 .iter()
1998 .filter_map(|cnum| {
1999 codegen_results.crate_info.used_crate_source[cnum]
2000 .dylib
2001 .as_ref()
2002 .map(|(path, _)| &**path)
2003 })
2004 .collect::<Vec<_>>();
2005 let mut rpath_config = RPathConfig {
2006 libs: &*libs,
2007 out_filename: out_filename.to_path_buf(),
2008 has_rpath: sess.target.has_rpath,
2009 is_like_osx: sess.target.is_like_osx,
2010 linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2011 };
2012 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
2013 }
2014 }
2015
2016 /// Produce the linker command line containing linker path and arguments.
2017 ///
2018 /// When comments in the function say "order-(in)dependent" they mean order-dependence between
2019 /// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2020 /// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2021 /// to the linking process as a whole.
2022 /// Order-independent options may still override each other in order-dependent fashion,
2023 /// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
linker_with_args<'a>( path: &Path, flavor: LinkerFlavor, sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, crate_type: CrateType, tmpdir: &Path, out_filename: &Path, codegen_results: &CodegenResults, ) -> Result<Command, ErrorGuaranteed>2024 fn linker_with_args<'a>(
2025 path: &Path,
2026 flavor: LinkerFlavor,
2027 sess: &'a Session,
2028 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2029 crate_type: CrateType,
2030 tmpdir: &Path,
2031 out_filename: &Path,
2032 codegen_results: &CodegenResults,
2033 ) -> Result<Command, ErrorGuaranteed> {
2034 let self_contained = self_contained(sess, crate_type);
2035 let cmd = &mut *super::linker::get_linker(
2036 sess,
2037 path,
2038 flavor,
2039 self_contained,
2040 &codegen_results.crate_info.target_cpu,
2041 );
2042 let link_output_kind = link_output_kind(sess, crate_type);
2043
2044 // ------------ Early order-dependent options ------------
2045
2046 // If we're building something like a dynamic library then some platforms
2047 // need to make sure that all symbols are exported correctly from the
2048 // dynamic library.
2049 // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2050 // at least on some platforms (e.g. windows-gnu).
2051 cmd.export_symbols(
2052 tmpdir,
2053 crate_type,
2054 &codegen_results.crate_info.exported_symbols[&crate_type],
2055 );
2056
2057 // Can be used for adding custom CRT objects or overriding order-dependent options above.
2058 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2059 // introduce a target spec option for order-independent linker options and migrate built-in
2060 // specs to it.
2061 add_pre_link_args(cmd, sess, flavor);
2062
2063 // ------------ Object code and libraries, order-dependent ------------
2064
2065 // Pre-link CRT objects.
2066 add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained);
2067
2068 add_linked_symbol_object(
2069 cmd,
2070 sess,
2071 tmpdir,
2072 &codegen_results.crate_info.linked_symbols[&crate_type],
2073 );
2074
2075 // Sanitizer libraries.
2076 add_sanitizer_libraries(sess, crate_type, cmd);
2077
2078 // Object code from the current crate.
2079 // Take careful note of the ordering of the arguments we pass to the linker
2080 // here. Linkers will assume that things on the left depend on things to the
2081 // right. Things on the right cannot depend on things on the left. This is
2082 // all formally implemented in terms of resolving symbols (libs on the right
2083 // resolve unknown symbols of libs on the left, but not vice versa).
2084 //
2085 // For this reason, we have organized the arguments we pass to the linker as
2086 // such:
2087 //
2088 // 1. The local object that LLVM just generated
2089 // 2. Local native libraries
2090 // 3. Upstream rust libraries
2091 // 4. Upstream native libraries
2092 //
2093 // The rationale behind this ordering is that those items lower down in the
2094 // list can't depend on items higher up in the list. For example nothing can
2095 // depend on what we just generated (e.g., that'd be a circular dependency).
2096 // Upstream rust libraries are not supposed to depend on our local native
2097 // libraries as that would violate the structure of the DAG, in that
2098 // scenario they are required to link to them as well in a shared fashion.
2099 //
2100 // Note that upstream rust libraries may contain native dependencies as
2101 // well, but they also can't depend on what we just started to add to the
2102 // link line. And finally upstream native libraries can't depend on anything
2103 // in this DAG so far because they can only depend on other native libraries
2104 // and such dependencies are also required to be specified.
2105 add_local_crate_regular_objects(cmd, codegen_results);
2106 add_local_crate_metadata_objects(cmd, crate_type, codegen_results);
2107 add_local_crate_allocator_objects(cmd, codegen_results);
2108
2109 // Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2110 // at the point at which they are specified on the command line.
2111 // Must be passed before any (dynamic) libraries to have effect on them.
2112 // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2113 // so it will ignore unreferenced ELF sections from relocatable objects.
2114 // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2115 // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2116 // and move this option back to the top.
2117 cmd.add_as_needed();
2118
2119 // Local native libraries of all kinds.
2120 add_local_native_libraries(
2121 cmd,
2122 sess,
2123 archive_builder_builder,
2124 codegen_results,
2125 tmpdir,
2126 link_output_kind,
2127 );
2128
2129 // Upstream rust crates and their non-dynamic native libraries.
2130 add_upstream_rust_crates(
2131 cmd,
2132 sess,
2133 archive_builder_builder,
2134 codegen_results,
2135 crate_type,
2136 tmpdir,
2137 link_output_kind,
2138 );
2139
2140 // Dynamic native libraries from upstream crates.
2141 add_upstream_native_libraries(
2142 cmd,
2143 sess,
2144 archive_builder_builder,
2145 codegen_results,
2146 tmpdir,
2147 link_output_kind,
2148 );
2149
2150 // Link with the import library generated for any raw-dylib functions.
2151 for (raw_dylib_name, raw_dylib_imports) in
2152 collate_raw_dylibs(sess, codegen_results.crate_info.used_libraries.iter())?
2153 {
2154 cmd.add_object(&archive_builder_builder.create_dll_import_lib(
2155 sess,
2156 &raw_dylib_name,
2157 &raw_dylib_imports,
2158 tmpdir,
2159 true,
2160 ));
2161 }
2162 // As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2163 // they are used within inlined functions or instantiated generic functions. We do this *after*
2164 // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2165 // by the linker.
2166 let (_, dependency_linkage) = codegen_results
2167 .crate_info
2168 .dependency_formats
2169 .iter()
2170 .find(|(ty, _)| *ty == crate_type)
2171 .expect("failed to find crate type in dependency format list");
2172 let native_libraries_from_nonstatics = codegen_results
2173 .crate_info
2174 .native_libraries
2175 .iter()
2176 .filter_map(|(cnum, libraries)| {
2177 (dependency_linkage[cnum.as_usize() - 1] != Linkage::Static).then_some(libraries)
2178 })
2179 .flatten();
2180 for (raw_dylib_name, raw_dylib_imports) in
2181 collate_raw_dylibs(sess, native_libraries_from_nonstatics)?
2182 {
2183 cmd.add_object(&archive_builder_builder.create_dll_import_lib(
2184 sess,
2185 &raw_dylib_name,
2186 &raw_dylib_imports,
2187 tmpdir,
2188 false,
2189 ));
2190 }
2191
2192 // Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2193 // command line shorter, reset it to default here before adding more libraries.
2194 cmd.reset_per_library_state();
2195
2196 // FIXME: Built-in target specs occasionally use this for linking system libraries,
2197 // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2198 // and remove the option.
2199 add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2200
2201 // ------------ Arbitrary order-independent options ------------
2202
2203 // Add order-independent options determined by rustc from its compiler options,
2204 // target properties and source code.
2205 add_order_independent_options(
2206 cmd,
2207 sess,
2208 link_output_kind,
2209 self_contained,
2210 flavor,
2211 crate_type,
2212 codegen_results,
2213 out_filename,
2214 tmpdir,
2215 );
2216
2217 // Can be used for arbitrary order-independent options.
2218 // In practice may also be occasionally used for linking native libraries.
2219 // Passed after compiler-generated options to support manual overriding when necessary.
2220 add_user_defined_link_args(cmd, sess);
2221
2222 // ------------ Object code and libraries, order-dependent ------------
2223
2224 // Post-link CRT objects.
2225 add_post_link_objects(cmd, sess, link_output_kind, self_contained);
2226
2227 // ------------ Late order-dependent options ------------
2228
2229 // Doesn't really make sense.
2230 // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2231 // introduce a target spec option for order-independent linker options, migrate built-in specs
2232 // to it and remove the option.
2233 add_post_link_args(cmd, sess, flavor);
2234
2235 Ok(cmd.take_cmd())
2236 }
2237
add_order_independent_options( cmd: &mut dyn Linker, sess: &Session, link_output_kind: LinkOutputKind, self_contained: bool, flavor: LinkerFlavor, crate_type: CrateType, codegen_results: &CodegenResults, out_filename: &Path, tmpdir: &Path, )2238 fn add_order_independent_options(
2239 cmd: &mut dyn Linker,
2240 sess: &Session,
2241 link_output_kind: LinkOutputKind,
2242 self_contained: bool,
2243 flavor: LinkerFlavor,
2244 crate_type: CrateType,
2245 codegen_results: &CodegenResults,
2246 out_filename: &Path,
2247 tmpdir: &Path,
2248 ) {
2249 // Take care of the flavors and CLI options requesting the `lld` linker.
2250 add_lld_args(cmd, sess, flavor);
2251
2252 add_apple_sdk(cmd, sess, flavor);
2253
2254 add_link_script(cmd, sess, tmpdir, crate_type);
2255
2256 if sess.target.os == "fuchsia"
2257 && crate_type == CrateType::Executable
2258 && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2259 {
2260 let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2261 "asan/"
2262 } else {
2263 ""
2264 };
2265 cmd.arg(format!("--dynamic-linker={}ld.so.1", prefix));
2266 }
2267
2268 if sess.target.eh_frame_header {
2269 cmd.add_eh_frame_header();
2270 }
2271
2272 // Make the binary compatible with data execution prevention schemes.
2273 cmd.add_no_exec();
2274
2275 if self_contained {
2276 cmd.no_crt_objects();
2277 }
2278
2279 if sess.target.os == "emscripten" {
2280 cmd.arg("-s");
2281 cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
2282 "DISABLE_EXCEPTION_CATCHING=1"
2283 } else {
2284 "DISABLE_EXCEPTION_CATCHING=0"
2285 });
2286 }
2287
2288 if flavor == LinkerFlavor::Ptx {
2289 // Provide the linker with fallback to internal `target-cpu`.
2290 cmd.arg("--fallback-arch");
2291 cmd.arg(&codegen_results.crate_info.target_cpu);
2292 } else if flavor == LinkerFlavor::Bpf {
2293 cmd.arg("--cpu");
2294 cmd.arg(&codegen_results.crate_info.target_cpu);
2295 if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2296 .into_iter()
2297 .find(|feat| !feat.is_empty())
2298 {
2299 cmd.arg("--cpu-features");
2300 cmd.arg(feat);
2301 }
2302 }
2303
2304 cmd.linker_plugin_lto();
2305
2306 add_library_search_dirs(cmd, sess, self_contained);
2307
2308 cmd.output_filename(out_filename);
2309
2310 if crate_type == CrateType::Executable && sess.target.is_like_windows {
2311 if let Some(ref s) = codegen_results.crate_info.windows_subsystem {
2312 cmd.subsystem(s);
2313 }
2314 }
2315
2316 // Try to strip as much out of the generated object by removing unused
2317 // sections if possible. See more comments in linker.rs
2318 if !sess.link_dead_code() {
2319 // If PGO is enabled sometimes gc_sections will remove the profile data section
2320 // as it appears to be unused. This can then cause the PGO profile file to lose
2321 // some functions. If we are generating a profile we shouldn't strip those metadata
2322 // sections to ensure we have all the data for PGO.
2323 let keep_metadata =
2324 crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2325 if crate_type != CrateType::Executable || !sess.opts.unstable_opts.export_executable_symbols
2326 {
2327 cmd.gc_sections(keep_metadata);
2328 } else {
2329 cmd.no_gc_sections();
2330 }
2331 }
2332
2333 cmd.set_output_kind(link_output_kind, out_filename);
2334
2335 add_relro_args(cmd, sess);
2336
2337 // Pass optimization flags down to the linker.
2338 cmd.optimize();
2339
2340 // Gather the set of NatVis files, if any, and write them out to a temp directory.
2341 let natvis_visualizers = collect_natvis_visualizers(
2342 tmpdir,
2343 sess,
2344 &codegen_results.crate_info.local_crate_name,
2345 &codegen_results.crate_info.natvis_debugger_visualizers,
2346 );
2347
2348 // Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2349 cmd.debuginfo(strip_value(sess), &natvis_visualizers);
2350
2351 // We want to prevent the compiler from accidentally leaking in any system libraries,
2352 // so by default we tell linkers not to link to any default libraries.
2353 if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2354 cmd.no_default_libraries();
2355 }
2356
2357 if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2358 cmd.pgo_gen();
2359 }
2360
2361 if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2362 cmd.control_flow_guard();
2363 }
2364
2365 add_rpath_args(cmd, sess, codegen_results, out_filename);
2366 }
2367
2368 // Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
collect_natvis_visualizers( tmpdir: &Path, sess: &Session, crate_name: &Symbol, natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>, ) -> Vec<PathBuf>2369 fn collect_natvis_visualizers(
2370 tmpdir: &Path,
2371 sess: &Session,
2372 crate_name: &Symbol,
2373 natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2374 ) -> Vec<PathBuf> {
2375 let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2376
2377 for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2378 let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2379
2380 match fs::write(&visualizer_out_file, &visualizer.src) {
2381 Ok(()) => {
2382 visualizer_paths.push(visualizer_out_file);
2383 }
2384 Err(error) => {
2385 sess.emit_warning(errors::UnableToWriteDebuggerVisualizer {
2386 path: visualizer_out_file,
2387 error,
2388 });
2389 }
2390 };
2391 }
2392 visualizer_paths
2393 }
2394
add_native_libs_from_crate( cmd: &mut dyn Linker, sess: &Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, tmpdir: &Path, search_paths: &OnceCell<Vec<PathBuf>>, bundled_libs: &FxHashSet<Symbol>, cnum: CrateNum, link_static: bool, link_dynamic: bool, link_output_kind: LinkOutputKind, )2395 fn add_native_libs_from_crate(
2396 cmd: &mut dyn Linker,
2397 sess: &Session,
2398 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2399 codegen_results: &CodegenResults,
2400 tmpdir: &Path,
2401 search_paths: &OnceCell<Vec<PathBuf>>,
2402 bundled_libs: &FxHashSet<Symbol>,
2403 cnum: CrateNum,
2404 link_static: bool,
2405 link_dynamic: bool,
2406 link_output_kind: LinkOutputKind,
2407 ) {
2408 if !sess.opts.unstable_opts.link_native_libraries {
2409 // If `-Zlink-native-libraries=false` is set, then the assumption is that an
2410 // external build system already has the native dependencies defined, and it
2411 // will provide them to the linker itself.
2412 return;
2413 }
2414
2415 if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2416 // If rlib contains native libs as archives, unpack them to tmpdir.
2417 let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2418 archive_builder_builder
2419 .extract_bundled_libs(rlib, tmpdir, &bundled_libs)
2420 .unwrap_or_else(|e| sess.emit_fatal(e));
2421 }
2422
2423 let native_libs = match cnum {
2424 LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2425 _ => &codegen_results.crate_info.native_libraries[&cnum],
2426 };
2427
2428 let mut last = (None, NativeLibKind::Unspecified, false);
2429 for lib in native_libs {
2430 if !relevant_lib(sess, lib) {
2431 continue;
2432 }
2433
2434 // Skip if this library is the same as the last.
2435 last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2436 continue;
2437 } else {
2438 (Some(lib.name), lib.kind, lib.verbatim)
2439 };
2440
2441 let name = lib.name.as_str();
2442 let verbatim = lib.verbatim;
2443 match lib.kind {
2444 NativeLibKind::Static { bundle, whole_archive } => {
2445 if link_static {
2446 let bundle = bundle.unwrap_or(true);
2447 let whole_archive = whole_archive == Some(true)
2448 // Backward compatibility case: this can be a rlib (so `+whole-archive`
2449 // cannot be added explicitly if necessary, see the error in `fn link_rlib`)
2450 // compiled as an executable due to `--test`. Use whole-archive implicitly,
2451 // like before the introduction of native lib modifiers.
2452 || (whole_archive == None
2453 && bundle
2454 && cnum == LOCAL_CRATE
2455 && sess.is_test_crate());
2456
2457 if bundle && cnum != LOCAL_CRATE {
2458 if let Some(filename) = lib.filename {
2459 // If rlib contains native libs as archives, they are unpacked to tmpdir.
2460 let path = tmpdir.join(filename.as_str());
2461 if whole_archive {
2462 cmd.link_whole_rlib(&path);
2463 } else {
2464 cmd.link_rlib(&path);
2465 }
2466 }
2467 } else {
2468 if whole_archive {
2469 cmd.link_whole_staticlib(
2470 name,
2471 verbatim,
2472 &search_paths.get_or_init(|| archive_search_paths(sess)),
2473 );
2474 } else {
2475 cmd.link_staticlib(name, verbatim)
2476 }
2477 }
2478 }
2479 }
2480 NativeLibKind::Dylib { as_needed } => {
2481 if link_dynamic {
2482 cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
2483 }
2484 }
2485 NativeLibKind::Unspecified => {
2486 // If we are generating a static binary, prefer static library when the
2487 // link kind is unspecified.
2488 if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2489 if link_static {
2490 cmd.link_staticlib(name, verbatim)
2491 }
2492 } else {
2493 if link_dynamic {
2494 cmd.link_dylib(name, verbatim, true);
2495 }
2496 }
2497 }
2498 NativeLibKind::Framework { as_needed } => {
2499 if link_dynamic {
2500 cmd.link_framework(name, as_needed.unwrap_or(true))
2501 }
2502 }
2503 NativeLibKind::RawDylib => {
2504 // Handled separately in `linker_with_args`.
2505 }
2506 NativeLibKind::WasmImportModule => {}
2507 NativeLibKind::LinkArg => {
2508 if link_static {
2509 cmd.arg(name);
2510 }
2511 }
2512 }
2513 }
2514 }
2515
add_local_native_libraries( cmd: &mut dyn Linker, sess: &Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, tmpdir: &Path, link_output_kind: LinkOutputKind, )2516 fn add_local_native_libraries(
2517 cmd: &mut dyn Linker,
2518 sess: &Session,
2519 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2520 codegen_results: &CodegenResults,
2521 tmpdir: &Path,
2522 link_output_kind: LinkOutputKind,
2523 ) {
2524 if sess.opts.unstable_opts.link_native_libraries {
2525 // User-supplied library search paths (-L on the command line). These are the same paths
2526 // used to find Rust crates, so some of them may have been added already by the previous
2527 // crate linking code. This only allows them to be found at compile time so it is still
2528 // entirely up to outside forces to make sure that library can be found at runtime.
2529 for search_path in sess.target_filesearch(PathKind::All).search_paths() {
2530 match search_path.kind {
2531 PathKind::Framework => cmd.framework_path(&search_path.dir),
2532 _ => cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)),
2533 }
2534 }
2535 }
2536
2537 let search_paths = OnceCell::new();
2538 // All static and dynamic native library dependencies are linked to the local crate.
2539 let link_static = true;
2540 let link_dynamic = true;
2541 add_native_libs_from_crate(
2542 cmd,
2543 sess,
2544 archive_builder_builder,
2545 codegen_results,
2546 tmpdir,
2547 &search_paths,
2548 &Default::default(),
2549 LOCAL_CRATE,
2550 link_static,
2551 link_dynamic,
2552 link_output_kind,
2553 );
2554 }
2555
add_upstream_rust_crates<'a>( cmd: &mut dyn Linker, sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, crate_type: CrateType, tmpdir: &Path, link_output_kind: LinkOutputKind, )2556 fn add_upstream_rust_crates<'a>(
2557 cmd: &mut dyn Linker,
2558 sess: &'a Session,
2559 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2560 codegen_results: &CodegenResults,
2561 crate_type: CrateType,
2562 tmpdir: &Path,
2563 link_output_kind: LinkOutputKind,
2564 ) {
2565 // All of the heavy lifting has previously been accomplished by the
2566 // dependency_format module of the compiler. This is just crawling the
2567 // output of that module, adding crates as necessary.
2568 //
2569 // Linking to a rlib involves just passing it to the linker (the linker
2570 // will slurp up the object files inside), and linking to a dynamic library
2571 // involves just passing the right -l flag.
2572 let (_, data) = codegen_results
2573 .crate_info
2574 .dependency_formats
2575 .iter()
2576 .find(|(ty, _)| *ty == crate_type)
2577 .expect("failed to find crate type in dependency format list");
2578
2579 let search_paths = OnceCell::new();
2580 for &cnum in &codegen_results.crate_info.used_crates {
2581 // We may not pass all crates through to the linker. Some crates may appear statically in
2582 // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2583 // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2584 // Even if they were already included into a dylib
2585 // (e.g. `libstd` when `-C prefer-dynamic` is used).
2586 // FIXME: `dependency_formats` can report `profiler_builtins` as `NotLinked` for some
2587 // reason, it shouldn't do that because `profiler_builtins` should indeed be linked.
2588 let linkage = data[cnum.as_usize() - 1];
2589 let link_static_crate = linkage == Linkage::Static
2590 || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2591 && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2592 || codegen_results.crate_info.profiler_runtime == Some(cnum));
2593
2594 let mut bundled_libs = Default::default();
2595 match linkage {
2596 Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2597 if link_static_crate {
2598 bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2599 .iter()
2600 .filter_map(|lib| lib.filename)
2601 .collect();
2602 add_static_crate(
2603 cmd,
2604 sess,
2605 archive_builder_builder,
2606 codegen_results,
2607 tmpdir,
2608 cnum,
2609 &bundled_libs,
2610 );
2611 }
2612 }
2613 Linkage::Dynamic => {
2614 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2615 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2616 }
2617 }
2618
2619 // Static libraries are linked for a subset of linked upstream crates.
2620 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2621 // because the rlib is just an archive.
2622 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
2623 // the native library because it is already linked into the dylib, and even if
2624 // inline/const/generic functions from the dylib can refer to symbols from the native
2625 // library, those symbols should be exported and available from the dylib anyway.
2626 // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
2627 let link_static = link_static_crate;
2628 // Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
2629 let link_dynamic = false;
2630 add_native_libs_from_crate(
2631 cmd,
2632 sess,
2633 archive_builder_builder,
2634 codegen_results,
2635 tmpdir,
2636 &search_paths,
2637 &bundled_libs,
2638 cnum,
2639 link_static,
2640 link_dynamic,
2641 link_output_kind,
2642 );
2643 }
2644 }
2645
add_upstream_native_libraries( cmd: &mut dyn Linker, sess: &Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, tmpdir: &Path, link_output_kind: LinkOutputKind, )2646 fn add_upstream_native_libraries(
2647 cmd: &mut dyn Linker,
2648 sess: &Session,
2649 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2650 codegen_results: &CodegenResults,
2651 tmpdir: &Path,
2652 link_output_kind: LinkOutputKind,
2653 ) {
2654 let search_path = OnceCell::new();
2655 for &cnum in &codegen_results.crate_info.used_crates {
2656 // Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
2657 // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
2658 // are linked together with their respective upstream crates, and in their originally
2659 // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
2660 // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
2661 let link_static = false;
2662 // Dynamic libraries are linked for all linked upstream crates.
2663 // 1. If the upstream crate is a directly linked rlib then we must link the native library
2664 // because the rlib is just an archive.
2665 // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
2666 // the native library too because inline/const/generic functions from the dylib can refer
2667 // to symbols from the native library, so the native library providing those symbols should
2668 // be available when linking our final binary.
2669 let link_dynamic = true;
2670 add_native_libs_from_crate(
2671 cmd,
2672 sess,
2673 archive_builder_builder,
2674 codegen_results,
2675 tmpdir,
2676 &search_path,
2677 &Default::default(),
2678 cnum,
2679 link_static,
2680 link_dynamic,
2681 link_output_kind,
2682 );
2683 }
2684 }
2685
2686 // Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
2687 // to be relative to the sysroot directory, which may be a relative path specified by the user.
2688 //
2689 // If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
2690 // linker command line can be non-deterministic due to the paths including the current working
2691 // directory. The linker command line needs to be deterministic since it appears inside the PDB
2692 // file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
2693 //
2694 // The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
rehome_sysroot_lib_dir<'a>(sess: &'a Session, lib_dir: &Path) -> PathBuf2695 fn rehome_sysroot_lib_dir<'a>(sess: &'a Session, lib_dir: &Path) -> PathBuf {
2696 let sysroot_lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
2697 let canonical_sysroot_lib_path =
2698 { try_canonicalize(&sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2699
2700 let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2701 if canonical_lib_dir == canonical_sysroot_lib_path {
2702 // This path, returned by `target_filesearch().get_lib_path()`, has
2703 // already had `fix_windows_verbatim_for_gcc()` applied if needed.
2704 sysroot_lib_path
2705 } else {
2706 fix_windows_verbatim_for_gcc(&lib_dir)
2707 }
2708 }
2709
2710 // Adds the static "rlib" versions of all crates to the command line.
2711 // There's a bit of magic which happens here specifically related to LTO,
2712 // namely that we remove upstream object files.
2713 //
2714 // When performing LTO, almost(*) all of the bytecode from the upstream
2715 // libraries has already been included in our object file output. As a
2716 // result we need to remove the object files in the upstream libraries so
2717 // the linker doesn't try to include them twice (or whine about duplicate
2718 // symbols). We must continue to include the rest of the rlib, however, as
2719 // it may contain static native libraries which must be linked in.
2720 //
2721 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
2722 // their bytecode wasn't included. The object files in those libraries must
2723 // still be passed to the linker.
2724 //
2725 // Note, however, that if we're not doing LTO we can just pass the rlib
2726 // blindly to the linker (fast) because it's fine if it's not actually
2727 // included as we're at the end of the dependency chain.
add_static_crate<'a>( cmd: &mut dyn Linker, sess: &'a Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, codegen_results: &CodegenResults, tmpdir: &Path, cnum: CrateNum, bundled_lib_file_names: &FxHashSet<Symbol>, )2728 fn add_static_crate<'a>(
2729 cmd: &mut dyn Linker,
2730 sess: &'a Session,
2731 archive_builder_builder: &dyn ArchiveBuilderBuilder,
2732 codegen_results: &CodegenResults,
2733 tmpdir: &Path,
2734 cnum: CrateNum,
2735 bundled_lib_file_names: &FxHashSet<Symbol>,
2736 ) {
2737 let src = &codegen_results.crate_info.used_crate_source[&cnum];
2738 let cratepath = &src.rlib.as_ref().unwrap().0;
2739
2740 let mut link_upstream = |path: &Path| {
2741 let rlib_path = if let Some(dir) = path.parent() {
2742 let file_name = path.file_name().expect("rlib path has no file name path component");
2743 rehome_sysroot_lib_dir(sess, &dir).join(file_name)
2744 } else {
2745 fix_windows_verbatim_for_gcc(path)
2746 };
2747 cmd.link_rlib(&rlib_path);
2748 };
2749
2750 if !are_upstream_rust_objects_already_included(sess)
2751 || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2752 {
2753 link_upstream(cratepath);
2754 return;
2755 }
2756
2757 let dst = tmpdir.join(cratepath.file_name().unwrap());
2758 let name = cratepath.file_name().unwrap().to_str().unwrap();
2759 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2760 let bundled_lib_file_names = bundled_lib_file_names.clone();
2761
2762 sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2763 let canonical_name = name.replace('-', "_");
2764 let upstream_rust_objects_already_included =
2765 are_upstream_rust_objects_already_included(sess);
2766 let is_builtins =
2767 sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2768
2769 let mut archive = archive_builder_builder.new_archive_builder(sess);
2770 if let Err(error) = archive.add_archive(
2771 cratepath,
2772 Box::new(move |f| {
2773 if f == METADATA_FILENAME {
2774 return true;
2775 }
2776
2777 let canonical = f.replace('-', "_");
2778
2779 let is_rust_object =
2780 canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);
2781
2782 // If we're performing LTO and this is a rust-generated object
2783 // file, then we don't need the object file as it's part of the
2784 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2785 // though, so we let that object file slide.
2786 if upstream_rust_objects_already_included && is_rust_object && is_builtins {
2787 return true;
2788 }
2789
2790 // We skip native libraries because:
2791 // 1. This native libraries won't be used from the generated rlib,
2792 // so we can throw them away to avoid the copying work.
2793 // 2. We can't allow it to be a single remaining entry in archive
2794 // as some linkers may complain on that.
2795 if bundled_lib_file_names.contains(&Symbol::intern(f)) {
2796 return true;
2797 }
2798
2799 false
2800 }),
2801 ) {
2802 sess.emit_fatal(errors::RlibArchiveBuildFailure { error });
2803 }
2804 if archive.build(&dst) {
2805 link_upstream(&dst);
2806 }
2807 });
2808 }
2809
2810 // Same thing as above, but for dynamic crates instead of static crates.
add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path)2811 fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
2812 // Just need to tell the linker about where the library lives and
2813 // what its name is
2814 let parent = cratepath.parent();
2815 if let Some(dir) = parent {
2816 cmd.include_path(&rehome_sysroot_lib_dir(sess, dir));
2817 }
2818 let stem = cratepath.file_stem().unwrap().to_str().unwrap();
2819 // Convert library file-stem into a cc -l argument.
2820 let prefix = if stem.starts_with("lib") && !sess.target.is_like_windows { 3 } else { 0 };
2821 cmd.link_rust_dylib(&stem[prefix..], parent.unwrap_or_else(|| Path::new("")));
2822 }
2823
relevant_lib(sess: &Session, lib: &NativeLib) -> bool2824 fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
2825 match lib.cfg {
2826 Some(ref cfg) => rustc_attr::cfg_matches(cfg, &sess.parse_sess, CRATE_NODE_ID, None),
2827 None => true,
2828 }
2829 }
2830
are_upstream_rust_objects_already_included(sess: &Session) -> bool2831 pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
2832 match sess.lto() {
2833 config::Lto::Fat => true,
2834 config::Lto::Thin => {
2835 // If we defer LTO to the linker, we haven't run LTO ourselves, so
2836 // any upstream object files have not been copied yet.
2837 !sess.opts.cg.linker_plugin_lto.enabled()
2838 }
2839 config::Lto::No | config::Lto::ThinLocal => false,
2840 }
2841 }
2842
add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor)2843 fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2844 let arch = &sess.target.arch;
2845 let os = &sess.target.os;
2846 let llvm_target = &sess.target.llvm_target;
2847 if sess.target.vendor != "apple"
2848 || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "macos")
2849 || !matches!(flavor, LinkerFlavor::Darwin(..))
2850 {
2851 return;
2852 }
2853
2854 if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) {
2855 return;
2856 }
2857
2858 let sdk_name = match (arch.as_ref(), os.as_ref()) {
2859 ("aarch64", "tvos") => "appletvos",
2860 ("x86_64", "tvos") => "appletvsimulator",
2861 ("arm", "ios") => "iphoneos",
2862 ("aarch64", "ios") if llvm_target.contains("macabi") => "macosx",
2863 ("aarch64", "ios") if llvm_target.ends_with("-simulator") => "iphonesimulator",
2864 ("aarch64", "ios") => "iphoneos",
2865 ("x86", "ios") => "iphonesimulator",
2866 ("x86_64", "ios") if llvm_target.contains("macabi") => "macosx",
2867 ("x86_64", "ios") => "iphonesimulator",
2868 ("x86_64", "watchos") => "watchsimulator",
2869 ("arm64_32", "watchos") => "watchos",
2870 ("aarch64", "watchos") if llvm_target.ends_with("-simulator") => "watchsimulator",
2871 ("aarch64", "watchos") => "watchos",
2872 ("arm", "watchos") => "watchos",
2873 (_, "macos") => "macosx",
2874 _ => {
2875 sess.emit_err(errors::UnsupportedArch { arch, os });
2876 return;
2877 }
2878 };
2879 let sdk_root = match get_apple_sdk_root(sdk_name) {
2880 Ok(s) => s,
2881 Err(e) => {
2882 sess.emit_err(e);
2883 return;
2884 }
2885 };
2886
2887 match flavor {
2888 LinkerFlavor::Darwin(Cc::Yes, _) => {
2889 cmd.args(&["-isysroot", &sdk_root, "-Wl,-syslibroot", &sdk_root]);
2890 }
2891 LinkerFlavor::Darwin(Cc::No, _) => {
2892 cmd.args(&["-syslibroot", &sdk_root]);
2893 }
2894 _ => unreachable!(),
2895 }
2896 }
2897
get_apple_sdk_root(sdk_name: &str) -> Result<String, errors::AppleSdkRootError<'_>>2898 fn get_apple_sdk_root(sdk_name: &str) -> Result<String, errors::AppleSdkRootError<'_>> {
2899 // Following what clang does
2900 // (https://github.com/llvm/llvm-project/blob/
2901 // 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
2902 // to allow the SDK path to be set. (For clang, xcrun sets
2903 // SDKROOT; for rustc, the user or build system can set it, or we
2904 // can fall back to checking for xcrun on PATH.)
2905 if let Ok(sdkroot) = env::var("SDKROOT") {
2906 let p = Path::new(&sdkroot);
2907 match sdk_name {
2908 // Ignore `SDKROOT` if it's clearly set for the wrong platform.
2909 "appletvos"
2910 if sdkroot.contains("TVSimulator.platform")
2911 || sdkroot.contains("MacOSX.platform") => {}
2912 "appletvsimulator"
2913 if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2914 "iphoneos"
2915 if sdkroot.contains("iPhoneSimulator.platform")
2916 || sdkroot.contains("MacOSX.platform") => {}
2917 "iphonesimulator"
2918 if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
2919 }
2920 "macosx10.15"
2921 if sdkroot.contains("iPhoneOS.platform")
2922 || sdkroot.contains("iPhoneSimulator.platform") => {}
2923 "watchos"
2924 if sdkroot.contains("WatchSimulator.platform")
2925 || sdkroot.contains("MacOSX.platform") => {}
2926 "watchsimulator"
2927 if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
2928 // Ignore `SDKROOT` if it's not a valid path.
2929 _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
2930 _ => return Ok(sdkroot),
2931 }
2932 }
2933 let res =
2934 Command::new("xcrun").arg("--show-sdk-path").arg("-sdk").arg(sdk_name).output().and_then(
2935 |output| {
2936 if output.status.success() {
2937 Ok(String::from_utf8(output.stdout).unwrap())
2938 } else {
2939 let error = String::from_utf8(output.stderr);
2940 let error = format!("process exit with error: {}", error.unwrap());
2941 Err(io::Error::new(io::ErrorKind::Other, &error[..]))
2942 }
2943 },
2944 );
2945
2946 match res {
2947 Ok(output) => Ok(output.trim().to_string()),
2948 Err(error) => Err(errors::AppleSdkRootError::SdkPath { sdk_name, error }),
2949 }
2950 }
2951
2952 /// When using the linker flavors opting in to `lld`, or the unstable `-Zgcc-ld=lld` flag, add the
2953 /// necessary paths and arguments to invoke it:
2954 /// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
2955 /// - or any `lld` available to `cc`.
add_lld_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor)2956 fn add_lld_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
2957 let unstable_use_lld = sess.opts.unstable_opts.gcc_ld.is_some();
2958 debug!("add_lld_args requested, flavor: '{flavor:?}', `-Zgcc-ld=lld`: {unstable_use_lld}");
2959
2960 // Sanity check: using the old unstable `-Zgcc-ld=lld` option requires a `cc`-using flavor.
2961 let flavor_uses_cc = flavor.uses_cc();
2962 if unstable_use_lld && !flavor_uses_cc {
2963 sess.emit_fatal(errors::OptionGccOnly);
2964 }
2965
2966 // If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
2967 // we don't need to do anything.
2968 let use_lld = flavor.uses_lld() || unstable_use_lld;
2969 if !flavor_uses_cc || !use_lld {
2970 return;
2971 }
2972
2973 let self_contained_linker = sess.opts.cg.link_self_contained.linker();
2974
2975 // FIXME: some targets default to using `lld`, but users can only override the linker on the CLI
2976 // and cannot yet select the precise linker flavor to opt out of that. See for example issue
2977 // #113597 for the `thumbv6m-none-eabi` target: a driver is used, and its default linker
2978 // conflicts with the target's flavor, causing unexpected arguments being passed.
2979 //
2980 // Until the new `LinkerFlavor`-like CLI options are stabilized, we only adopt MCP510's behavior
2981 // if its dedicated unstable CLI flags are used, to keep the current sub-optimal stable
2982 // behavior.
2983 let using_mcp510 =
2984 self_contained_linker || sess.opts.cg.linker_flavor.is_some_and(|f| f.is_unstable());
2985 if !using_mcp510 && !unstable_use_lld {
2986 return;
2987 }
2988
2989 // 1. Implement the "self-contained" part of this feature by adding rustc distribution
2990 // directories to the tool's search path.
2991 if self_contained_linker || unstable_use_lld {
2992 for path in sess.get_tools_search_paths(false) {
2993 cmd.arg({
2994 let mut arg = OsString::from("-B");
2995 arg.push(path.join("gcc-ld"));
2996 arg
2997 });
2998 }
2999 }
3000
3001 // 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3002 // `lld` as the linker.
3003 cmd.arg("-fuse-ld=lld");
3004
3005 if !flavor.is_gnu() {
3006 // Tell clang to use a non-default LLD flavor.
3007 // Gcc doesn't understand the target option, but we currently assume
3008 // that gcc is not used for Apple and Wasm targets (#97402).
3009 //
3010 // Note that we don't want to do that by default on macOS: e.g. passing a
3011 // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3012 // shown in issue #101653 and the discussion in PR #101792.
3013 //
3014 // It could be required in some cases of cross-compiling with
3015 // `-Zgcc-ld=lld`, but this is generally unspecified, and we don't know
3016 // which specific versions of clang, macOS SDK, host and target OS
3017 // combinations impact us here.
3018 //
3019 // So we do a simple first-approximation until we know more of what the
3020 // Apple targets require (and which would be handled prior to hitting this
3021 // `-Zgcc-ld=lld` codepath anyway), but the expectation is that until then
3022 // this should be manually passed if needed. We specify the target when
3023 // targeting a different linker flavor on macOS, and that's also always
3024 // the case when targeting WASM.
3025 if sess.target.linker_flavor != sess.host.linker_flavor {
3026 cmd.arg(format!("--target={}", sess.target.llvm_target));
3027 }
3028 }
3029 }
3030