forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.rs
2846 lines (2598 loc) · 115 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;
use rustc_hir::def_id::CrateNum;
use rustc_metadata::find_native_static_library;
use rustc_metadata::fs::{emit_metadata, METADATA_FILENAME};
use rustc_middle::middle::dependency_format::Linkage;
use rustc_middle::middle::exported_symbols::SymbolExportKind;
use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, LdImpl, Strip};
use rustc_session::config::{OutputFilenames, OutputType, PrintRequest, 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_span::DebuggerVisualizerFile;
use rustc_target::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy};
use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, Target};
use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
use super::command::Command;
use super::linker::{self, Linker};
use super::metadata::{create_rmeta_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 std::borrow::Borrow;
use std::cell::OnceCell;
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs::{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);
for &crate_type in sess.crate_types().iter() {
// 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 out_filename = out_filename(
sess,
crate_type,
outputs,
codegen_results.crate_info.local_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,
);
}
}
}
}
// 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);
}
// 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(())
}
pub fn each_linked_rlib(
info: &CrateInfo,
f: &mut dyn FnMut(CrateNum, &Path),
) -> Result<(), errors::LinkRlibError> {
let crates = info.used_crates.iter();
let mut fmts = None;
for (ty, list) in info.dependency_formats.iter() {
match ty {
CrateType::Executable
| CrateType::Staticlib
| CrateType::Cdylib
| CrateType::ProcMacro => {
fmts = Some(list);
break;
}
_ => {}
}
}
let Some(fmts) = fmts else {
return Err(errors::LinkRlibError::MissingFormat);
};
for &cnum in crates {
match fmts.get(cnum.as_usize() - 1) {
Some(&Linkage::NotLinked | &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. The rlib primarily contains
/// the object file of the crate, but it also contains all of the object files from native
/// libraries. This is done by unzipping native libraries and inserting all of the contents into
/// this archive.
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_rmeta_file(sess, codegen_results.metadata.raw_data());
let metadata = emit_metadata(sess, &metadata, tmpdir);
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() {
match lib.kind {
NativeLibKind::Static { bundle: None | Some(true), whole_archive: Some(true) }
if flavor == RlibFlavor::Normal && sess.opts.unstable_opts.packed_bundled_libs => {}
NativeLibKind::Static { bundle: None | Some(true), whole_archive: Some(true) }
if flavor == RlibFlavor::Normal =>
{
// Don't allow mixing +bundle with +whole_archive since an rlib may contain
// multiple native libs, some of which are +whole-archive and some of which are
// -whole-archive and it isn't clear how we can currently handle such a
// situation correctly.
// See https://github.com/rust-lang/rust/issues/88085#issuecomment-901050897
sess.emit_err(errors::IncompatibleLinkingModifiers);
}
NativeLibKind::Static { bundle: None | Some(true), .. } => {}
NativeLibKind::Static { bundle: Some(false), .. }
| NativeLibKind::Dylib { .. }
| NativeLibKind::Framework { .. }
| NativeLibKind::RawDylib
| NativeLibKind::LinkArg
| NativeLibKind::Unspecified => continue,
}
if let Some(name) = lib.name {
let location =
find_native_static_library(name.as_str(), lib.verbatim, &lib_search_paths, sess);
if sess.opts.unstable_opts.packed_bundled_libs && flavor == RlibFlavor::Normal {
packed_bundled_libs.push(find_native_static_library(
lib.filename.unwrap().as_str(),
Some(true),
&lib_search_paths,
sess,
));
continue;
}
ab.add_archive(&location, Box::new(|_| false)).unwrap_or_else(|error| {
sess.emit_fatal(errors::AddNativeLibrary { library_path: location, error });
});
}
}
for (raw_dylib_name, raw_dylib_imports) in
collate_raw_dylibs(sess, &codegen_results.crate_info.used_libraries)?
{
let output_path = archive_builder_builder.create_dll_import_lib(
sess,
&raw_dylib_name,
&raw_dylib_imports,
tmpdir.as_ref(),
);
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(
sess: &Session,
used_libraries: &[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 matches!(lib.verbatim, Some(true)) { "" } else { ".dll" };
let name = format!("{}{}", lib.name.expect("unnamed raw-dylib library"), 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, &mut |cnum, path| {
let name = codegen_results.crate_info.crate_name[&cnum];
let native_libs = &codegen_results.crate_info.native_libraries[&cnum];
// Here when we include the rlib into our staticlib we need to make a
// decision whether to include the extra object files along the way.
// These extra object files come from statically included native
// libraries, but they may be cfg'd away with #[link(cfg(..))].
//
// This unstable feature, though, only needs liblibc to work. The only
// use case there is where musl is statically included in liblibc.rlib,
// so if we don't want the included version we just need to skip it. As
// a result the logic here is that if *any* linked library is cfg'd away
// we just skip all object files.
//
// Clearly this is not sufficient for a general purpose feature, and
// we'd want to read from the library's metadata to determine which
// object files come from where and selectively skip them.
let skip_object_files = native_libs.iter().any(|lib| {
matches!(lib.kind, NativeLibKind::Static { bundle: None | Some(true), .. })
&& !relevant_lib(sess, lib)
});
let lto = are_upstream_rust_objects_already_included(sess)
&& !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
// Ignoring obj file starting with the crate name
// as simple comparison is not enough - there
// might be also an extra name suffix
let obj_start = name.as_str().to_owned();
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;
}
// Otherwise if this is *not* a rust object and we're skipping
// objects then skip this file
if skip_object_files && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
return true;
}
// ok, don't skip this
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);
if !all_native_libs.is_empty() {
if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
print_native_static_libs(sess, &all_native_libs);
}
}
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 dwp_out_filename = executable_out_filename.with_extension("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<'arena>(&'arena self, data: Mmap) -> &'arena Mmap {
(*self.arena_mmap.alloc(data)).borrow()
}
}
impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
fn alloc_data<'arena>(&'arena self, data: Vec<u8>) -> &'arena [u8] {
(*self.arena_data.alloc(data)).borrow()
}
fn alloc_relocation<'arena>(&'arena self, data: Relocations) -> &'arena Relocations {
(*self.arena_relocations.alloc(data)).borrow()
}
fn read_input<'arena>(&'arena self, path: &Path) -> std::io::Result<&'arena [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 = package.finish()?.write()?;
let mut output_stream = BufWriter::new(
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(dwp_out_filename)?,
);
output_stream.write_all(&output)?;
output_stream.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 &(ref k, ref 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());
}
if sess.opts.prints.contains(&PrintRequest::LinkArgs) {
println!("{:?}", &cmd);
}
// 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_string(&output);
// FIXME: Add UI tests for this error.
let err = errors::LinkingFailed {
linker_path: &linker_path,
exit_status: prog.status,
command: &cmd,
escaped_output: &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.note_without_error("`link.exe` returned an unexpected error");
if is_vs_installed && has_linker {
// the linker is broken
sess.note_without_error(
"the Visual Studio build tools may need to be repaired \
using the Visual Studio installer",
);
sess.note_without_error(
"or a necessary component may be missing from the \
\"C++ build tools\" workload",
);
} else if is_vs_installed {
// the linker is not installed
sess.note_without_error(
"in the Visual Studio installer, ensure the \
\"C++ build tools\" workload is selected",
);
} else {
// visual studio is not installed
sess.note_without_error(
"you may need to install Visual Studio build tools with the \
\"C++ build tools\" workload",
);
}
}
}
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;
let mut linker_error = {
if linker_not_found {
sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
} else {
sess.struct_err(&format!(
"could not exec the linker `{}`",
linker_path.display()
))
}
};
linker_error.note(&e.to_string());
if !linker_not_found {
linker_error.note(&format!("{:?}", &cmd));
}
linker_error.emit();
if sess.target.is_like_msvc && linker_not_found {
sess.note_without_error(
"the msvc targets depend on the msvc linker \
but `link.exe` was not found",
);
sess.note_without_error(
"please ensure that Visual Studio 2017 or later, or Build Tools \
for Visual Studio were installed with the Visual C++ option.",
);
sess.note_without_error("VS Code is a different product, and is not sufficient.");
}
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();
match prog {
Ok(prog) => {
if !prog.status.success() {
let mut output = prog.stderr.clone();
output.extend_from_slice(&prog.stdout);
sess.struct_warn(&format!(
"processing debug info with `dsymutil` failed: {}",
prog.status
))
.note(&escape_string(&output))
.emit();
}
}
Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
}
}
// On MSVC packed debug information is produced by the linker itself so
// there's no need to do anything else here.
SplitDebuginfo::Packed if sess.target.is_like_windows => {}