-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
link.rs
3035 lines (2778 loc) · 121 KB
/
link.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use rustc_arena::TypedArena;
use rustc_ast::CRATE_NODE_ID;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_errors::{ErrorGuaranteed, Handler};
use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_metadata::find_native_static_library;
use rustc_metadata::fs::{copy_to_stdout, emit_wrapper_file, METADATA_FILENAME};
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
use rustc_middle::middle::dependency_format::Linkage;
use rustc_middle::middle::exported_symbols::SymbolExportKind;
use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, OutFileName, Strip};
use rustc_session::config::{OutputFilenames, OutputType, PrintKind, SplitDwarfKind};
use rustc_session::cstore::DllImport;
use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
use rustc_session::search_paths::PathKind;
use rustc_session::utils::NativeLibKind;
/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.
use rustc_session::{filesearch, Session};
use rustc_span::symbol::Symbol;
use rustc_target::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld, PanicStrategy};
use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo};
use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
use super::command::Command;
use super::linker::{self, Linker};
use super::metadata::{create_wrapper_file, MetadataPosition};
use super::rpath::{self, RPathConfig};
use crate::{
errors, looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib,
};
use cc::windows_registry;
use regex::Regex;
use tempfile::Builder as TempFileBuilder;
use itertools::Itertools;
use std::cell::OnceCell;
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs::{read, File, OpenOptions};
use std::io::{BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output, Stdio};
use std::{env, fmt, fs, io, mem, str};
pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
if let Err(e) = fs::remove_file(path) {
if e.kind() != io::ErrorKind::NotFound {
diag_handler.err(format!("failed to remove {}: {}", path.display(), e));
}
}
}
/// Performs the linkage portion of the compilation phase. This will generate all
/// of the requested outputs for this compilation session.
pub fn link_binary<'a>(
sess: &'a Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
codegen_results: &CodegenResults,
outputs: &OutputFilenames,
) -> Result<(), ErrorGuaranteed> {
let _timer = sess.timer("link_binary");
let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
for &crate_type in &codegen_results.crate_info.crate_types {
// Ignore executable crates if we have -Z no-codegen, as they will error.
if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
&& !output_metadata
&& crate_type == CrateType::Executable
{
continue;
}
if invalid_output_for_target(sess, crate_type) {
bug!(
"invalid output type `{:?}` for target os `{}`",
crate_type,
sess.opts.target_triple
);
}
sess.time("link_binary_check_files_are_writeable", || {
for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
check_file_is_writeable(obj, sess);
}
});
if outputs.outputs.should_link() {
let tmpdir = TempFileBuilder::new()
.prefix("rustc")
.tempdir()
.unwrap_or_else(|error| sess.emit_fatal(errors::CreateTempDir { error }));
let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
let output = out_filename(
sess,
crate_type,
outputs,
codegen_results.crate_info.local_crate_name,
);
let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
let out_filename =
output.file_for_writing(outputs, OutputType::Exe, Some(crate_name.as_str()));
match crate_type {
CrateType::Rlib => {
let _timer = sess.timer("link_rlib");
info!("preparing rlib to {:?}", out_filename);
link_rlib(
sess,
archive_builder_builder,
codegen_results,
RlibFlavor::Normal,
&path,
)?
.build(&out_filename);
}
CrateType::Staticlib => {
link_staticlib(
sess,
archive_builder_builder,
codegen_results,
&out_filename,
&path,
)?;
}
_ => {
link_natively(
sess,
archive_builder_builder,
crate_type,
&out_filename,
codegen_results,
path.as_ref(),
)?;
}
}
if sess.opts.json_artifact_notifications {
sess.parse_sess.span_diagnostic.emit_artifact_notification(&out_filename, "link");
}
if sess.prof.enabled() {
if let Some(artifact_name) = out_filename.file_name() {
// Record size for self-profiling
let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
sess.prof.artifact_size(
"linked_artifact",
artifact_name.to_string_lossy(),
file_size,
);
}
}
if output.is_stdout() {
if output.is_tty() {
sess.emit_err(errors::BinaryOutputToTty {
shorthand: OutputType::Exe.shorthand(),
});
} else if let Err(e) = copy_to_stdout(&out_filename) {
sess.emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
}
tempfiles_for_stdout_output.push(out_filename);
}
}
}
// Remove the temporary object file and metadata if we aren't saving temps.
sess.time("link_binary_remove_temps", || {
// If the user requests that temporaries are saved, don't delete any.
if sess.opts.cg.save_temps {
return;
}
let maybe_remove_temps_from_module =
|preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
if !preserve_objects {
if let Some(ref obj) = module.object {
ensure_removed(sess.diagnostic(), obj);
}
}
if !preserve_dwarf_objects {
if let Some(ref dwo_obj) = module.dwarf_object {
ensure_removed(sess.diagnostic(), dwo_obj);
}
}
};
let remove_temps_from_module =
|module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
// Otherwise, always remove the metadata and allocator module temporaries.
if let Some(ref metadata_module) = codegen_results.metadata_module {
remove_temps_from_module(metadata_module);
}
if let Some(ref allocator_module) = codegen_results.allocator_module {
remove_temps_from_module(allocator_module);
}
// Remove the temporary files if output goes to stdout
for temp in tempfiles_for_stdout_output {
ensure_removed(sess.diagnostic(), &temp);
}
// If no requested outputs require linking, then the object temporaries should
// be kept.
if !sess.opts.output_types.should_link() {
return;
}
// Potentially keep objects for their debuginfo.
let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
debug!(?preserve_objects, ?preserve_dwarf_objects);
for module in &codegen_results.modules {
maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
}
});
Ok(())
}
// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
// crate types must use the same dependency formats.
pub fn each_linked_rlib(
info: &CrateInfo,
crate_type: Option<CrateType>,
f: &mut dyn FnMut(CrateNum, &Path),
) -> Result<(), errors::LinkRlibError> {
let crates = info.used_crates.iter();
let fmts = if crate_type.is_none() {
for combination in info.dependency_formats.iter().combinations(2) {
let (ty1, list1) = &combination[0];
let (ty2, list2) = &combination[1];
if list1 != list2 {
return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
ty1: format!("{ty1:?}"),
ty2: format!("{ty2:?}"),
list1: format!("{list1:?}"),
list2: format!("{list2:?}"),
});
}
}
if info.dependency_formats.is_empty() {
return Err(errors::LinkRlibError::MissingFormat);
}
&info.dependency_formats[0].1
} else {
let fmts = info
.dependency_formats
.iter()
.find_map(|&(ty, ref list)| if Some(ty) == crate_type { Some(list) } else { None });
let Some(fmts) = fmts else {
return Err(errors::LinkRlibError::MissingFormat);
};
fmts
};
for &cnum in crates {
match fmts.get(cnum.as_usize() - 1) {
Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
Some(_) => {}
None => return Err(errors::LinkRlibError::MissingFormat),
}
let crate_name = info.crate_name[&cnum];
let used_crate_source = &info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.rlib {
f(cnum, &path);
} else {
if used_crate_source.rmeta.is_some() {
return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
return Err(errors::LinkRlibError::NotFound { crate_name });
}
}
}
Ok(())
}
/// Create an 'rlib'.
///
/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
/// The rlib primarily contains the object file of the crate, but it also some of the object files
/// from native libraries.
fn link_rlib<'a>(
sess: &'a Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
codegen_results: &CodegenResults,
flavor: RlibFlavor,
tmpdir: &MaybeTempDir,
) -> Result<Box<dyn ArchiveBuilder<'a> + 'a>, ErrorGuaranteed> {
let lib_search_paths = archive_search_paths(sess);
let mut ab = archive_builder_builder.new_archive_builder(sess);
let trailing_metadata = match flavor {
RlibFlavor::Normal => {
let (metadata, metadata_position) =
create_wrapper_file(sess, b".rmeta".to_vec(), codegen_results.metadata.raw_data());
let metadata = emit_wrapper_file(sess, &metadata, tmpdir, METADATA_FILENAME);
match metadata_position {
MetadataPosition::First => {
// Most of the time metadata in rlib files is wrapped in a "dummy" object
// file for the target platform so the rlib can be processed entirely by
// normal linkers for the platform. Sometimes this is not possible however.
// If it is possible however, placing the metadata object first improves
// performance of getting metadata from rlibs.
ab.add_file(&metadata);
None
}
MetadataPosition::Last => Some(metadata),
}
}
RlibFlavor::StaticlibBase => None,
};
for m in &codegen_results.modules {
if let Some(obj) = m.object.as_ref() {
ab.add_file(obj);
}
if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
ab.add_file(dwarf_obj);
}
}
match flavor {
RlibFlavor::Normal => {}
RlibFlavor::StaticlibBase => {
let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
if let Some(obj) = obj {
ab.add_file(obj);
}
}
}
// Used if packed_bundled_libs flag enabled.
let mut packed_bundled_libs = Vec::new();
// Note that in this loop we are ignoring the value of `lib.cfg`. That is,
// we may not be configured to actually include a static library if we're
// adding it here. That's because later when we consume this rlib we'll
// decide whether we actually needed the static library or not.
//
// To do this "correctly" we'd need to keep track of which libraries added
// which object files to the archive. We don't do that here, however. The
// #[link(cfg(..))] feature is unstable, though, and only intended to get
// liblibc working. In that sense the check below just indicates that if
// there are any libraries we want to omit object files for at link time we
// just exclude all custom object files.
//
// Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
// feature then we'll need to figure out how to record what objects were
// loaded from the libraries found here and then encode that into the
// metadata of the rlib we're generating somehow.
for lib in codegen_results.crate_info.used_libraries.iter() {
let NativeLibKind::Static { bundle: None | Some(true), whole_archive } = lib.kind else {
continue;
};
if whole_archive == Some(true)
&& flavor == RlibFlavor::Normal
&& !codegen_results.crate_info.feature_packed_bundled_libs
{
sess.emit_err(errors::IncompatibleLinkingModifiers);
}
if flavor == RlibFlavor::Normal && let Some(filename) = lib.filename {
let path = find_native_static_library(filename.as_str(), true, &lib_search_paths, sess);
let src = read(path).map_err(|e| sess.emit_fatal(errors::ReadFileError {message: e }))?;
let (data, _) = create_wrapper_file(sess, b".bundled_lib".to_vec(), &src);
let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
packed_bundled_libs.push(wrapper_file);
} else {
let path =
find_native_static_library(lib.name.as_str(), lib.verbatim, &lib_search_paths, sess);
ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
sess.emit_fatal(errors::AddNativeLibrary { library_path: path, error })});
}
}
for (raw_dylib_name, raw_dylib_imports) in
collate_raw_dylibs(sess, codegen_results.crate_info.used_libraries.iter())?
{
let output_path = archive_builder_builder.create_dll_import_lib(
sess,
&raw_dylib_name,
&raw_dylib_imports,
tmpdir.as_ref(),
true,
);
ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
sess.emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
});
}
if let Some(trailing_metadata) = trailing_metadata {
// Note that it is important that we add all of our non-object "magical
// files" *after* all of the object files in the archive. The reason for
// this is as follows:
//
// * When performing LTO, this archive will be modified to remove
// objects from above. The reason for this is described below.
//
// * When the system linker looks at an archive, it will attempt to
// determine the architecture of the archive in order to see whether its
// linkable.
//
// The algorithm for this detection is: iterate over the files in the
// archive. Skip magical SYMDEF names. Interpret the first file as an
// object file. Read architecture from the object file.
//
// * As one can probably see, if "metadata" and "foo.bc" were placed
// before all of the objects, then the architecture of this archive would
// not be correctly inferred once 'foo.o' is removed.
//
// * Most of the time metadata in rlib files is wrapped in a "dummy" object
// file for the target platform so the rlib can be processed entirely by
// normal linkers for the platform. Sometimes this is not possible however.
//
// Basically, all this means is that this code should not move above the
// code above.
ab.add_file(&trailing_metadata);
}
// Add all bundled static native library dependencies.
// Archives added to the end of .rlib archive, see comment above for the reason.
for lib in packed_bundled_libs {
ab.add_file(&lib)
}
return Ok(ab);
}
/// Extract all symbols defined in raw-dylib libraries, collated by library name.
///
/// If we have multiple extern blocks that specify symbols defined in the same raw-dylib library,
/// then the CodegenResults value contains one NativeLib instance for each block. However, the
/// linker appears to expect only a single import library for each library used, so we need to
/// collate the symbols together by library name before generating the import libraries.
fn collate_raw_dylibs<'a, 'b>(
sess: &'a Session,
used_libraries: impl IntoIterator<Item = &'b NativeLib>,
) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed> {
// Use index maps to preserve original order of imports and libraries.
let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
for lib in used_libraries {
if lib.kind == NativeLibKind::RawDylib {
let ext = if lib.verbatim { "" } else { ".dll" };
let name = format!("{}{}", lib.name, ext);
let imports = dylib_table.entry(name.clone()).or_default();
for import in &lib.dll_imports {
if let Some(old_import) = imports.insert(import.name, import) {
// FIXME: when we add support for ordinals, figure out if we need to do anything
// if we have two DllImport values with the same name but different ordinals.
if import.calling_convention != old_import.calling_convention {
sess.emit_err(errors::MultipleExternalFuncDecl {
span: import.span,
function: import.name,
library_name: &name,
});
}
}
}
}
}
sess.compile_status()?;
Ok(dylib_table
.into_iter()
.map(|(name, imports)| {
(name, imports.into_iter().map(|(_, import)| import.clone()).collect())
})
.collect())
}
/// Create a static archive.
///
/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
/// dependencies as well.
///
/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
/// library dependencies that they're not linked in.
///
/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
/// object file (and also don't prepare the archive with a metadata file).
fn link_staticlib<'a>(
sess: &'a Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
codegen_results: &CodegenResults,
out_filename: &Path,
tempdir: &MaybeTempDir,
) -> Result<(), ErrorGuaranteed> {
info!("preparing staticlib to {:?}", out_filename);
let mut ab = link_rlib(
sess,
archive_builder_builder,
codegen_results,
RlibFlavor::StaticlibBase,
tempdir,
)?;
let mut all_native_libs = vec![];
let res = each_linked_rlib(
&codegen_results.crate_info,
Some(CrateType::Staticlib),
&mut |cnum, path| {
let lto = are_upstream_rust_objects_already_included(sess)
&& !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, &lib));
let relevant_libs: FxHashSet<_> = relevant.filter_map(|lib| lib.filename).collect();
let bundled_libs: FxHashSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
ab.add_archive(
path,
Box::new(move |fname: &str| {
// Ignore metadata files, no matter the name.
if fname == METADATA_FILENAME {
return true;
}
// Don't include Rust objects if LTO is enabled
if lto && looks_like_rust_object_file(fname) {
return true;
}
// Skip objects for bundled libs.
if bundled_libs.contains(&Symbol::intern(fname)) {
return true;
}
false
}),
)
.unwrap();
archive_builder_builder
.extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
.unwrap_or_else(|e| sess.emit_fatal(e));
for filename in relevant_libs {
let joined = tempdir.as_ref().join(filename.as_str());
let path = joined.as_path();
ab.add_archive(path, Box::new(|_| false)).unwrap();
}
all_native_libs
.extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
},
);
if let Err(e) = res {
sess.emit_fatal(e);
}
ab.build(out_filename);
let crates = codegen_results.crate_info.used_crates.iter();
let fmts = codegen_results
.crate_info
.dependency_formats
.iter()
.find_map(|&(ty, ref list)| if ty == CrateType::Staticlib { Some(list) } else { None })
.expect("no dependency formats for staticlib");
let mut all_rust_dylibs = vec![];
for &cnum in crates {
match fmts.get(cnum.as_usize() - 1) {
Some(&Linkage::Dynamic) => {}
_ => continue,
}
let crate_name = codegen_results.crate_info.crate_name[&cnum];
let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.dylib {
all_rust_dylibs.push(&**path);
} else {
if used_crate_source.rmeta.is_some() {
sess.emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
sess.emit_fatal(errors::LinkRlibError::NotFound { crate_name });
}
}
}
all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
for print in &sess.opts.prints {
if print.kind == PrintKind::NativeStaticLibs {
print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
}
}
Ok(())
}
/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
/// DWARF package.
fn link_dwarf_object<'a>(
sess: &'a Session,
cg_results: &CodegenResults,
executable_out_filename: &Path,
) {
let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
dwp_out_filename.push(".dwp");
debug!(?dwp_out_filename, ?executable_out_filename);
#[derive(Default)]
struct ThorinSession<Relocations> {
arena_data: TypedArena<Vec<u8>>,
arena_mmap: TypedArena<Mmap>,
arena_relocations: TypedArena<Relocations>,
}
impl<Relocations> ThorinSession<Relocations> {
fn alloc_mmap(&self, data: Mmap) -> &Mmap {
&*self.arena_mmap.alloc(data)
}
}
impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
&*self.arena_data.alloc(data)
}
fn alloc_relocation(&self, data: Relocations) -> &Relocations {
&*self.arena_relocations.alloc(data)
}
fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
let file = File::open(&path)?;
let mmap = (unsafe { Mmap::map(file) })?;
Ok(self.alloc_mmap(mmap))
}
}
match sess.time("run_thorin", || -> Result<(), thorin::Error> {
let thorin_sess = ThorinSession::default();
let mut package = thorin::DwarfPackage::new(&thorin_sess);
// Input objs contain .o/.dwo files from the current crate.
match sess.opts.unstable_opts.split_dwarf_kind {
SplitDwarfKind::Single => {
for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
package.add_input_object(input_obj)?;
}
}
SplitDwarfKind::Split => {
for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
package.add_input_object(input_obj)?;
}
}
}
// Input rlibs contain .o/.dwo files from dependencies.
let input_rlibs = cg_results
.crate_info
.used_crate_source
.values()
.filter_map(|csource| csource.rlib.as_ref())
.map(|(path, _)| path);
for input_rlib in input_rlibs {
debug!(?input_rlib);
package.add_input_object(input_rlib)?;
}
// Failing to read the referenced objects is expected for dependencies where the path in the
// executable will have been cleaned by Cargo, but the referenced objects will be contained
// within rlibs provided as inputs.
//
// If paths have been remapped, then .o/.dwo files from the current crate also won't be
// found, but are provided explicitly above.
//
// Adding an executable is primarily done to make `thorin` check that all the referenced
// dwarf objects are found in the end.
package.add_executable(
&executable_out_filename,
thorin::MissingReferencedObjectBehaviour::Skip,
)?;
let output_stream = BufWriter::new(
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(dwp_out_filename)?,
);
let mut output_stream = object::write::StreamingBuffer::new(output_stream);
package.finish()?.emit(&mut output_stream)?;
output_stream.result()?;
output_stream.into_inner().flush()?;
Ok(())
}) {
Ok(()) => {}
Err(e) => {
sess.emit_err(errors::ThorinErrorWrapper(e));
sess.abort_if_errors();
}
}
}
/// Create a dynamic library or executable.
///
/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
/// files as well.
fn link_natively<'a>(
sess: &'a Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
crate_type: CrateType,
out_filename: &Path,
codegen_results: &CodegenResults,
tmpdir: &Path,
) -> Result<(), ErrorGuaranteed> {
info!("preparing {:?} to {:?}", crate_type, out_filename);
let (linker_path, flavor) = linker_and_flavor(sess);
let mut cmd = linker_with_args(
&linker_path,
flavor,
sess,
archive_builder_builder,
crate_type,
tmpdir,
out_filename,
codegen_results,
)?;
linker::disable_localization(&mut cmd);
for (k, v) in sess.target.link_env.as_ref() {
cmd.env(k.as_ref(), v.as_ref());
}
for k in sess.target.link_env_remove.as_ref() {
cmd.env_remove(k.as_ref());
}
for print in &sess.opts.prints {
if print.kind == PrintKind::LinkArgs {
let content = format!("{cmd:?}");
print.out.overwrite(&content, sess);
}
}
// May have not found libraries in the right formats.
sess.abort_if_errors();
// Invoke the system linker
info!("{:?}", &cmd);
let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
let unknown_arg_regex =
Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
let mut prog;
let mut i = 0;
loop {
i += 1;
prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, tmpdir));
let Ok(ref output) = prog else {
break;
};
if output.status.success() {
break;
}
let mut out = output.stderr.clone();
out.extend(&output.stdout);
let out = String::from_utf8_lossy(&out);
// Check to see if the link failed with an error message that indicates it
// doesn't recognize the -no-pie option. If so, re-perform the link step
// without it. This is safe because if the linker doesn't support -no-pie
// then it should not default to linking executables as pie. Different
// versions of gcc seem to use different quotes in the error message so
// don't check for them.
if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
&& unknown_arg_regex.is_match(&out)
&& out.contains("-no-pie")
&& cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie")
{
info!("linker output: {:?}", out);
warn!("Linker does not support -no-pie command line option. Retrying without.");
for arg in cmd.take_args() {
if arg.to_string_lossy() != "-no-pie" {
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
continue;
}
// Detect '-static-pie' used with an older version of gcc or clang not supporting it.
// Fallback from '-static-pie' to '-static' in that case.
if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
&& unknown_arg_regex.is_match(&out)
&& (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
&& cmd.get_args().iter().any(|e| e.to_string_lossy() == "-static-pie")
{
info!("linker output: {:?}", out);
warn!(
"Linker does not support -static-pie command line option. Retrying with -static instead."
);
// Mirror `add_(pre,post)_link_objects` to replace CRT objects.
let self_contained = self_contained(sess, crate_type);
let opts = &sess.target;
let pre_objects = if self_contained {
&opts.pre_link_objects_self_contained
} else {
&opts.pre_link_objects
};
let post_objects = if self_contained {
&opts.post_link_objects_self_contained
} else {
&opts.post_link_objects
};
let get_objects = |objects: &CrtObjects, kind| {
objects
.get(&kind)
.iter()
.copied()
.flatten()
.map(|obj| get_object_file_path(sess, obj, self_contained).into_os_string())
.collect::<Vec<_>>()
};
let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
// Assume that we know insertion positions for the replacement arguments from replaced
// arguments, which is true for all supported targets.
assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
for arg in cmd.take_args() {
if arg.to_string_lossy() == "-static-pie" {
// Replace the output kind.
cmd.arg("-static");
} else if pre_objects_static_pie.contains(&arg) {
// Replace the pre-link objects (replace the first and remove the rest).
cmd.args(mem::take(&mut pre_objects_static));
} else if post_objects_static_pie.contains(&arg) {
// Replace the post-link objects (replace the first and remove the rest).
cmd.args(mem::take(&mut post_objects_static));
} else {
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
continue;
}
// Here's a terribly awful hack that really shouldn't be present in any
// compiler. Here an environment variable is supported to automatically
// retry the linker invocation if the linker looks like it segfaulted.
//
// Gee that seems odd, normally segfaults are things we want to know
// about! Unfortunately though in rust-lang/rust#38878 we're
// experiencing the linker segfaulting on Travis quite a bit which is
// causing quite a bit of pain to land PRs when they spuriously fail
// due to a segfault.
//
// The issue #38878 has some more debugging information on it as well,
// but this unfortunately looks like it's just a race condition in
// macOS's linker with some thread pool working in the background. It
// seems that no one currently knows a fix for this so in the meantime
// we're left with this...
if !retry_on_segfault || i > 3 {
break;
}
let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
let msg_bus = "clang: error: unable to execute command: Bus error: 10";
if out.contains(msg_segv) || out.contains(msg_bus) {
warn!(
?cmd, %out,
"looks like the linker segfaulted when we tried to call it, \
automatically retrying again",
);
continue;
}
if is_illegal_instruction(&output.status) {
warn!(
?cmd, %out, status = %output.status,
"looks like the linker hit an illegal instruction when we \
tried to call it, automatically retrying again.",
);
continue;
}
#[cfg(unix)]
fn is_illegal_instruction(status: &ExitStatus) -> bool {
use std::os::unix::prelude::*;
status.signal() == Some(libc::SIGILL)
}
#[cfg(not(unix))]
fn is_illegal_instruction(_status: &ExitStatus) -> bool {
false
}
}
match prog {
Ok(prog) => {
if !prog.status.success() {
let mut output = prog.stderr.clone();
output.extend_from_slice(&prog.stdout);
let escaped_output = escape_linker_output(&output, flavor);
// FIXME: Add UI tests for this error.
let err = errors::LinkingFailed {
linker_path: &linker_path,
exit_status: prog.status,
command: &cmd,
escaped_output,
};
sess.diagnostic().emit_err(err);
// If MSVC's `link.exe` was expected but the return code
// is not a Microsoft LNK error then suggest a way to fix or
// install the Visual Studio build tools.
if let Some(code) = prog.status.code() {
if sess.target.is_like_msvc
&& flavor == LinkerFlavor::Msvc(Lld::No)
// Respect the command line override
&& sess.opts.cg.linker.is_none()
// Match exactly "link.exe"
&& linker_path.to_str() == Some("link.exe")
// All Microsoft `link.exe` linking error codes are
// four digit numbers in the range 1000 to 9999 inclusive
&& (code < 1000 || code > 9999)
{
let is_vs_installed = windows_registry::find_vs_version().is_ok();
let has_linker = windows_registry::find_tool(
&sess.opts.target_triple.triple(),
"link.exe",
)
.is_some();
sess.emit_note(errors::LinkExeUnexpectedError);
if is_vs_installed && has_linker {
// the linker is broken
sess.emit_note(errors::RepairVSBuildTools);
sess.emit_note(errors::MissingCppBuildToolComponent);
} else if is_vs_installed {
// the linker is not installed
sess.emit_note(errors::SelectCppBuildToolWorkload);
} else {
// visual studio is not installed
sess.emit_note(errors::VisualStudioNotInstalled);
}
}
}
sess.abort_if_errors();
}
info!("linker stderr:\n{}", escape_string(&prog.stderr));
info!("linker stdout:\n{}", escape_string(&prog.stdout));
}
Err(e) => {
let linker_not_found = e.kind() == io::ErrorKind::NotFound;
if linker_not_found {
sess.emit_err(errors::LinkerNotFound { linker_path, error: e });
} else {
sess.emit_err(errors::UnableToExeLinker {
linker_path,
error: e,
command_formatted: format!("{:?}", &cmd),
});
}
if sess.target.is_like_msvc && linker_not_found {
sess.emit_note(errors::MsvcMissingLinker);
sess.emit_note(errors::CheckInstalledVisualStudio);
sess.emit_note(errors::InsufficientVSCodeProduct);
}
sess.abort_if_errors();
}
}
match sess.split_debuginfo() {
// If split debug information is disabled or located in individual files
// there's nothing to do here.
SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
// If packed split-debuginfo is requested, but the final compilation
// doesn't actually have any debug information, then we skip this step.
SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
// On macOS the external `dsymutil` tool is used to create the packed
// debug information. Note that this will read debug information from
// the objects on the filesystem which we'll clean up later.
SplitDebuginfo::Packed if sess.target.is_like_osx => {
let prog = Command::new("dsymutil").arg(out_filename).output();