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