-
-
Notifications
You must be signed in to change notification settings - Fork 15.5k
Expand file tree
/
Copy patharchive.rs
More file actions
1357 lines (1221 loc) · 48.7 KB
/
Copy patharchive.rs
File metadata and controls
1357 lines (1221 loc) · 48.7 KB
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 std::env;
use std::error::Error;
use std::ffi::OsString;
use std::fs::{self, File};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use ar_archive_writer::{
ArchiveKind, COFFShortExport, MachineTypes, NewArchiveMember, write_archive_to_stream,
};
pub use ar_archive_writer::{DEFAULT_OBJECT_READER, ObjectReader};
use object::Endianness;
use object::read::archive::{ArchiveFile, ArchiveKind as ObjectArchiveKind};
use object::read::macho::FatArch;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
use rustc_data_structures::memmap::Mmap;
use rustc_fs_util::TempDirBuilder;
use rustc_metadata::EncodedMetadata;
use rustc_session::Session;
use rustc_span::Symbol;
use rustc_target::spec::Arch;
use tracing::trace;
use super::metadata::{create_compressed_metadata_file, search_for_section};
use super::rmeta_link::{self, RmetaLink};
use crate::common;
// Public for ArchiveBuilderBuilder::extract_bundled_libs
pub use crate::errors::ExtractBundledLibsError;
use crate::errors::{
ArchiveBuildFailure, DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary,
ErrorWritingDEFFile, UnknownArchiveKind,
};
/// An item to be included in an import library.
/// This is a slimmed down version of `COFFShortExport` from `ar-archive-writer`.
pub struct ImportLibraryItem {
/// The name to be exported.
pub name: String,
/// The ordinal to be exported, if any.
pub ordinal: Option<u16>,
/// The original, decorated name if `name` is not decorated.
pub symbol_name: Option<String>,
/// True if this is a data export, false if it is a function export.
pub is_data: bool,
}
impl ImportLibraryItem {
fn into_coff_short_export(self, sess: &Session) -> COFFShortExport {
let import_name = (sess.target.arch == Arch::Arm64EC).then(|| self.name.clone());
COFFShortExport {
name: self.name,
ext_name: None,
symbol_name: self.symbol_name,
import_name,
export_as: None,
ordinal: self.ordinal.unwrap_or(0),
noname: self.ordinal.is_some(),
data: self.is_data,
private: false,
constant: false,
}
}
}
pub trait ArchiveBuilderBuilder {
fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder + 'a>;
fn create_dylib_metadata_wrapper(
&self,
sess: &Session,
metadata: &EncodedMetadata,
symbol_name: &str,
) -> Vec<u8> {
create_compressed_metadata_file(sess, metadata, symbol_name)
}
/// Creates a DLL Import Library <https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-creation#creating-an-import-library>.
/// and returns the path on disk to that import library.
/// This functions doesn't take `self` so that it can be called from
/// `linker_with_args`, which is specialized on `ArchiveBuilder` but
/// doesn't take or create an instance of that type.
fn create_dll_import_lib(
&self,
sess: &Session,
lib_name: &str,
items: Vec<ImportLibraryItem>,
output_path: &Path,
) {
if common::is_mingw_gnu_toolchain(&sess.target) {
// The binutils linker used on -windows-gnu targets cannot read the import
// libraries generated by LLVM: in our attempts, the linker produced an .EXE
// that loaded but crashed with an AV upon calling one of the imported
// functions. Therefore, use binutils to create the import library instead,
// by writing a .DEF file to the temp dir and calling binutils's dlltool.
create_mingw_dll_import_lib(sess, lib_name, items, output_path);
} else {
trace!("creating import library");
trace!(" dll_name {:#?}", lib_name);
trace!(" output_path {}", output_path.display());
trace!(
" import names: {}",
items
.iter()
.map(|ImportLibraryItem { name, .. }| name.clone())
.collect::<Vec<_>>()
.join(", "),
);
// All import names are Rust identifiers and therefore cannot contain \0 characters.
// FIXME: when support for #[link_name] is implemented, ensure that the import names
// still don't contain any \0 characters. Also need to check that the names don't
// contain substrings like " @" or "NONAME" that are keywords or otherwise reserved
// in definition files.
let mut file = match fs::File::create_new(&output_path) {
Ok(file) => file,
Err(error) => sess
.dcx()
.emit_fatal(ErrorCreatingImportLibrary { lib_name, error: error.to_string() }),
};
let exports =
items.into_iter().map(|item| item.into_coff_short_export(sess)).collect::<Vec<_>>();
let machine = match &sess.target.arch {
Arch::X86_64 => MachineTypes::AMD64,
Arch::X86 => MachineTypes::I386,
Arch::AArch64 => MachineTypes::ARM64,
Arch::Arm64EC => MachineTypes::ARM64EC,
Arch::Arm => MachineTypes::ARMNT,
cpu => panic!("unsupported cpu type {cpu}"),
};
if let Err(error) = ar_archive_writer::write_import_library(
&mut file,
lib_name,
&exports,
machine,
!sess.target.is_like_msvc,
// Enable compatibility with MSVC's `/WHOLEARCHIVE` flag.
// Without this flag a duplicate symbol error would be emitted
// when linking a rust staticlib using `/WHOLEARCHIVE`.
// See #129020
true,
&[],
) {
sess.dcx()
.emit_fatal(ErrorCreatingImportLibrary { lib_name, error: error.to_string() });
}
}
}
fn extract_bundled_libs<'a>(
&'a self,
rlib: &'a Path,
outdir: &Path,
bundled_lib_file_names: &FxIndexSet<Symbol>,
) -> Result<(), ExtractBundledLibsError<'a>> {
let archive_map = unsafe {
Mmap::map(
File::open(rlib)
.map_err(|e| ExtractBundledLibsError::OpenFile { rlib, error: Box::new(e) })?,
)
.map_err(|e| ExtractBundledLibsError::MmapFile { rlib, error: Box::new(e) })?
};
let archive = ArchiveFile::parse(&*archive_map)
.map_err(|e| ExtractBundledLibsError::ParseArchive { rlib, error: Box::new(e) })?;
for entry in archive.members() {
let entry = entry
.map_err(|e| ExtractBundledLibsError::ReadEntry { rlib, error: Box::new(e) })?;
let data = entry
.data(&*archive_map)
.map_err(|e| ExtractBundledLibsError::ArchiveMember { rlib, error: Box::new(e) })?;
let name = std::str::from_utf8(entry.name())
.map_err(|e| ExtractBundledLibsError::ConvertName { rlib, error: Box::new(e) })?;
if !bundled_lib_file_names.contains(&Symbol::intern(name)) {
continue; // We need to extract only native libraries.
}
let data = search_for_section(rlib, data, ".bundled_lib").map_err(|e| {
ExtractBundledLibsError::ExtractSection { rlib, error: Box::<dyn Error>::from(e) }
})?;
std::fs::write(&outdir.join(&name), data)
.map_err(|e| ExtractBundledLibsError::WriteFile { rlib, error: Box::new(e) })?;
}
Ok(())
}
}
fn create_mingw_dll_import_lib(
sess: &Session,
lib_name: &str,
items: Vec<ImportLibraryItem>,
output_path: &Path,
) {
let def_file_path = output_path.with_extension("def");
let def_file_content = format!(
"EXPORTS\n{}",
items
.into_iter()
.map(|ImportLibraryItem { name, ordinal, .. }| {
match ordinal {
Some(n) => format!("{name} @{n} NONAME"),
None => name,
}
})
.collect::<Vec<String>>()
.join("\n")
);
match std::fs::write(&def_file_path, def_file_content) {
Ok(_) => {}
Err(e) => {
sess.dcx().emit_fatal(ErrorWritingDEFFile { error: e });
}
};
// --no-leading-underscore: For the `import_name_type` feature to work, we need to be
// able to control the *exact* spelling of each of the symbols that are being imported:
// hence we don't want `dlltool` adding leading underscores automatically.
let dlltool = find_binutils_dlltool(sess);
// temp_prefix doesn't handle paths with spaces so
// use a relative path and set the current working directory
let cwd = output_path.parent().unwrap_or(output_path);
let temp_prefix = lib_name;
// dlltool target architecture args from:
// https://github.com/llvm/llvm-project-release-prs/blob/llvmorg-15.0.6/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp#L69
let (dlltool_target_arch, dlltool_target_bitness) = match &sess.target.arch {
Arch::X86_64 => ("i386:x86-64", "--64"),
Arch::X86 => ("i386", "--32"),
Arch::AArch64 => ("arm64", "--64"),
Arch::Arm => ("arm", "--32"),
arch => panic!("unsupported arch {arch}"),
};
let mut dlltool_cmd = std::process::Command::new(&dlltool);
dlltool_cmd
.arg("-d")
.arg(def_file_path)
.arg("-D")
.arg(lib_name)
.arg("-l")
.arg(&output_path)
.arg("-m")
.arg(dlltool_target_arch)
.arg("-f")
.arg(dlltool_target_bitness)
.arg("--no-leading-underscore")
.arg("--temp-prefix")
.arg(temp_prefix)
.current_dir(cwd);
match dlltool_cmd.output() {
Err(e) => {
sess.dcx().emit_fatal(ErrorCallingDllTool {
dlltool_path: dlltool.to_string_lossy(),
error: e,
});
}
// dlltool returns '0' on failure, so check for error output instead.
Ok(output) if !output.stderr.is_empty() => {
sess.dcx().emit_fatal(DlltoolFailImportLibrary {
dlltool_path: dlltool.to_string_lossy(),
dlltool_args: dlltool_cmd
.get_args()
.map(|arg| arg.to_string_lossy())
.collect::<Vec<_>>()
.join(" "),
stdout: String::from_utf8_lossy(&output.stdout),
stderr: String::from_utf8_lossy(&output.stderr),
})
}
_ => {}
}
}
fn find_binutils_dlltool(sess: &Session) -> OsString {
assert!(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc);
if let Some(dlltool_path) = &sess.opts.cg.dlltool {
return dlltool_path.clone().into_os_string();
}
let tool_name: OsString = if sess.host.options.is_like_windows {
// If we're compiling on Windows, always use "dlltool.exe".
"dlltool.exe"
} else {
// On other platforms, use the architecture-specific name.
match sess.target.arch {
Arch::X86_64 => "x86_64-w64-mingw32-dlltool",
Arch::X86 => "i686-w64-mingw32-dlltool",
Arch::AArch64 => "aarch64-w64-mingw32-dlltool",
// For non-standard architectures (e.g., aarch32) fallback to "dlltool".
_ => "dlltool",
}
}
.into();
// NOTE: it's not clear how useful it is to explicitly search PATH.
for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
let full_path = dir.join(&tool_name);
if full_path.is_file() {
return full_path.into_os_string();
}
}
// The user didn't specify the location of the dlltool binary, and we weren't able
// to find the appropriate one on the PATH. Just return the name of the tool
// and let the invocation fail with a hopefully useful error message.
tool_name
}
pub trait ArchiveBuilder {
fn add_file(&mut self, path: &Path);
fn add_archive(
&mut self,
archive: &Path,
skip: Option<Box<dyn FnMut(&str, Option<&RmetaLink>) -> bool + 'static>>,
) -> io::Result<()>;
fn build(self: Box<Self>, output: &Path) -> bool;
fn set_hide_symbols(&mut self, keep: FxHashSet<String>);
fn set_rename_symbols(&mut self, keep: FxHashSet<String>, suffix: String);
}
fn target_archive_format_to_object_kind(format: &str) -> Option<ObjectArchiveKind> {
match format {
"gnu" => Some(ObjectArchiveKind::Gnu),
"bsd" => Some(ObjectArchiveKind::Bsd),
"darwin" => Some(ObjectArchiveKind::Bsd64),
"coff" => Some(ObjectArchiveKind::Coff),
"aix_big" => Some(ObjectArchiveKind::AixBig),
_ => None,
}
}
fn archive_kinds_compatible(actual: ObjectArchiveKind, expected: ObjectArchiveKind) -> bool {
if actual == expected {
return true;
}
matches!(
(actual, expected),
// An archive without long filenames or symbol table is detected as Unknown;
// this is compatible with any target format.
(ObjectArchiveKind::Unknown, _)
// 64-bit symbol table variants are compatible with their 32-bit counterparts
| (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Gnu)
| (ObjectArchiveKind::Gnu, ObjectArchiveKind::Gnu64)
| (ObjectArchiveKind::Bsd64, ObjectArchiveKind::Bsd)
| (ObjectArchiveKind::Bsd, ObjectArchiveKind::Bsd64)
// GNU and COFF archives share the same magic and member header format;
// only the symbol table layout differs.
| (ObjectArchiveKind::Gnu, ObjectArchiveKind::Coff)
| (ObjectArchiveKind::Coff, ObjectArchiveKind::Gnu)
| (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Coff)
)
}
fn archive_kind_display_name(kind: ObjectArchiveKind) -> String {
match kind {
ObjectArchiveKind::Gnu | ObjectArchiveKind::Gnu64 => "GNU".to_string(),
ObjectArchiveKind::Bsd => "BSD".to_string(),
ObjectArchiveKind::Bsd64 => "Darwin".to_string(),
ObjectArchiveKind::Coff => "COFF".to_string(),
ObjectArchiveKind::AixBig => "AIX big".to_string(),
_ => format!("{kind:?}"),
}
}
pub struct ArArchiveBuilderBuilder;
impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder {
fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder + 'a> {
Box::new(ArArchiveBuilder::new(sess, &DEFAULT_OBJECT_READER))
}
}
#[must_use = "must call build() to finish building the archive"]
pub struct ArArchiveBuilder<'a> {
sess: &'a Session,
object_reader: &'static ObjectReader,
src_archives: Vec<(PathBuf, Mmap)>,
// Don't use an `HashMap` here, as the order is important. `lib.rmeta` needs
// to be at the end of an archive in some cases for linkers to not get confused.
entries: Vec<(Vec<u8>, ArchiveEntry)>,
hide_symbols: Option<FxHashSet<String>>,
rename_symbols: Option<(FxHashSet<String>, String)>,
}
#[derive(Debug)]
enum ArchiveEntry {
FromArchive { archive_index: usize, file_range: (u64, u64) },
File(PathBuf),
}
impl<'a> ArArchiveBuilder<'a> {
pub fn new(sess: &'a Session, object_reader: &'static ObjectReader) -> ArArchiveBuilder<'a> {
ArArchiveBuilder {
sess,
object_reader,
src_archives: vec![],
entries: vec![],
hide_symbols: None,
rename_symbols: None,
}
}
pub fn set_hide_symbols(&mut self, keep: FxHashSet<String>) {
self.hide_symbols = Some(keep);
}
pub fn set_rename_symbols(&mut self, keep: FxHashSet<String>, suffix: String) {
self.rename_symbols = Some((keep, suffix));
}
}
fn try_filter_fat_archs(
archs: &[impl FatArch],
target_arch: object::Architecture,
archive_path: &Path,
archive_map_data: &[u8],
) -> io::Result<Option<PathBuf>> {
let desired = match archs.iter().find(|a| a.architecture() == target_arch) {
Some(a) => a,
None => return Ok(None),
};
let (mut new_f, extracted_path) = tempfile::Builder::new()
.suffix(archive_path.file_name().unwrap())
.tempfile()?
.keep()
.unwrap();
new_f.write_all(
desired.data(archive_map_data).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?,
)?;
Ok(Some(extracted_path))
}
pub fn try_extract_macho_fat_archive(
sess: &Session,
archive_path: &Path,
) -> io::Result<Option<PathBuf>> {
let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? };
let target_arch = match sess.target.arch {
Arch::AArch64 => object::Architecture::Aarch64,
Arch::X86_64 => object::Architecture::X86_64,
_ => return Ok(None),
};
if let Ok(h) = object::read::macho::MachOFatFile32::parse(&*archive_map) {
let archs = h.arches();
try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map)
} else if let Ok(h) = object::read::macho::MachOFatFile64::parse(&*archive_map) {
let archs = h.arches();
try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map)
} else {
// Not a FatHeader at all, just return None.
Ok(None)
}
}
impl<'a> ArchiveBuilder for ArArchiveBuilder<'a> {
fn add_archive(
&mut self,
archive_path: &Path,
mut skip: Option<Box<dyn FnMut(&str, Option<&RmetaLink>) -> bool + 'static>>,
) -> io::Result<()> {
let mut archive_path = archive_path.to_path_buf();
if self.sess.target.llvm_target.contains("-apple-macosx")
&& let Some(new_archive_path) = try_extract_macho_fat_archive(self.sess, &archive_path)?
{
archive_path = new_archive_path
}
if self.src_archives.iter().any(|archive| archive.0 == archive_path) {
return Ok(());
}
let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? };
let archive = ArchiveFile::parse(&*archive_map)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let metadata_link =
skip.as_ref().and_then(|_| rmeta_link::read(&archive, &archive_map, &archive_path));
let archive_index = self.src_archives.len();
if let Some(expected_kind) =
target_archive_format_to_object_kind(&self.sess.target.archive_format)
{
let actual_kind = archive.kind();
if !archive_kinds_compatible(actual_kind, expected_kind) {
self.sess.dcx().emit_warn(crate::errors::IncompatibleArchiveFormat {
path: archive_path.clone(),
actual: archive_kind_display_name(actual_kind),
expected: archive_kind_display_name(expected_kind),
});
}
}
for entry in archive.members() {
let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let file_name = String::from_utf8(entry.name().to_vec())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
let drop = skip.as_mut().is_some_and(|f| f(&file_name, metadata_link.as_ref()));
if !drop {
if entry.is_thin() {
let member_path = archive_path.parent().unwrap().join(Path::new(&file_name));
self.entries.push((file_name.into_bytes(), ArchiveEntry::File(member_path)));
} else {
self.entries.push((
file_name.into_bytes(),
ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
));
}
}
}
self.src_archives.push((archive_path, archive_map));
Ok(())
}
/// Adds an arbitrary file to this archive
fn add_file(&mut self, file: &Path) {
self.entries.push((
file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
ArchiveEntry::File(file.to_owned()),
));
}
/// Combine the provided files, rlibs, and native libraries into a single
/// `Archive`.
fn build(self: Box<Self>, output: &Path) -> bool {
let sess = self.sess;
match self.build_inner(output) {
Ok(any_members) => any_members,
Err(error) => {
sess.dcx().emit_fatal(ArchiveBuildFailure { path: output.to_owned(), error })
}
}
}
fn set_hide_symbols(&mut self, keep: FxHashSet<String>) {
self.hide_symbols = Some(keep);
}
fn set_rename_symbols(&mut self, keep: FxHashSet<String>, suffix: String) {
self.rename_symbols = Some((keep, suffix));
}
}
impl<'a> ArArchiveBuilder<'a> {
fn build_inner(self, output: &Path) -> io::Result<bool> {
let archive_kind = match &*self.sess.target.archive_format {
"gnu" => ArchiveKind::Gnu,
"bsd" => ArchiveKind::Bsd,
"darwin" => ArchiveKind::Darwin,
"coff" => ArchiveKind::Coff,
"aix_big" => ArchiveKind::AixBig,
kind => {
self.sess.dcx().emit_fatal(UnknownArchiveKind { kind });
}
};
let mut entries = Vec::new();
// When hiding or renaming symbols, we need a global two-pass approach:
// 1: collect all non-exported defined symbol names across ALL .o files
// 2: apply hide/rename to each .o file
// For rename, this ensures cross-object-file references remain consistent.
let should_hide = self.hide_symbols.is_some();
let should_rename = self.rename_symbols.is_some();
// Collect the internal symbol set in a dedicated scope so the borrow on
// self.hide_symbols / self.rename_symbols is released before the application loop.
let (global_internal_set, rename_suffix): (Option<FxHashSet<String>>, Option<String>) = {
if !should_hide && !should_rename {
(None, None)
} else {
let keep: &FxHashSet<String> = self
.rename_symbols
.as_ref()
.map(|(k, _)| k)
.or(self.hide_symbols.as_ref())
.unwrap();
let suffix = self.rename_symbols.as_ref().map(|(_, s)| s.clone());
let mut all_names: FxHashSet<String> = FxHashSet::default();
for (entry_name, entry) in &self.entries {
if !entry_name.ends_with(b".rcgu.o") {
continue;
}
let data: Option<Box<dyn AsRef<[u8]>>> = match entry {
ArchiveEntry::FromArchive { archive_index, file_range } => {
let src_archive = &self.src_archives[*archive_index];
let d = &src_archive.1[file_range.0 as usize
..file_range.0 as usize + file_range.1 as usize];
Some(Box::new(d) as Box<dyn AsRef<[u8]>>)
}
ArchiveEntry::File(file) => {
let file = File::open(file);
match file {
Ok(f) => unsafe {
Mmap::map(f).ok().map(|m| Box::new(m) as Box<dyn AsRef<[u8]>>)
},
Err(_) => None,
}
}
};
if let Some(data) = data {
let d = data.as_ref().as_ref();
elf_collect_rename_set(d, keep, &mut all_names);
macho_collect_rename_set(d, keep, &mut all_names);
}
}
(Some(all_names), suffix)
}
};
for (entry_name, entry) in self.entries {
let data: Box<dyn AsRef<[u8]>> =
match entry {
ArchiveEntry::FromArchive { archive_index, file_range } => {
let src_archive = &self.src_archives[archive_index];
let archive_data = &src_archive.1;
let start = file_range.0 as usize;
let end = start + file_range.1 as usize;
let Some(data) = archive_data.get(start..end) else {
return Err(io_error_context(
"invalid archive member",
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"archive member at offset {start} with size {} \
exceeds archive size {} in `{}`",
file_range.1,
archive_data.len(),
src_archive.0.display(),
),
),
));
};
Box::new(data) as Box<dyn AsRef<[u8]>>
}
ArchiveEntry::File(file) => unsafe {
Box::new(
Mmap::map(File::open(file).map_err(|err| {
io_error_context("failed to open object file", err)
})?)
.map_err(|err| io_error_context("failed to map object file", err))?,
) as Box<dyn AsRef<[u8]>>
},
};
let data: Box<dyn AsRef<[u8]>> = if let Some(ref internal_set) = global_internal_set {
if !entry_name.ends_with(b".rcgu.o") {
data
} else if should_rename {
let suffix = rename_suffix.as_ref().unwrap();
if let Some(renamed) =
elf_apply_rename(data.as_ref().as_ref(), internal_set, suffix, should_hide)
{
Box::new(renamed)
} else if let Some(renamed) = macho_apply_rename(
data.as_ref().as_ref(),
internal_set,
suffix,
should_hide,
) {
Box::new(renamed)
} else {
data
}
} else {
if let Some(hidden) = elf_apply_hide(data.as_ref().as_ref(), internal_set) {
Box::new(hidden)
} else if let Some(hidden) =
macho_apply_hide(data.as_ref().as_ref(), internal_set)
{
Box::new(hidden)
} else {
data
}
}
} else {
data
};
entries.push(NewArchiveMember {
buf: data,
object_reader: self.object_reader,
member_name: String::from_utf8(entry_name).unwrap(),
mtime: 0,
uid: 0,
gid: 0,
perms: 0o644,
})
}
// Write to a temporary file first before atomically renaming to the final name.
// This prevents programs (including rustc) from attempting to read a partial archive.
// It also enables writing an archive with the same filename as a dependency on Windows as
// required by a test.
// The tempfile crate currently uses 0o600 as mode for the temporary files and directories
// it creates. We need it to be the default mode for back compat reasons however. (See
// #107495) To handle this we are telling tempfile to create a temporary directory instead
// and then inside this directory create a file using File::create.
let archive_tmpdir = TempDirBuilder::new()
.suffix(".temp-archive")
.tempdir_in(output.parent().unwrap_or_else(|| Path::new("")))
.map_err(|err| {
io_error_context("couldn't create a directory for the temp file", err)
})?;
let archive_tmpfile_path = archive_tmpdir.path().join("tmp.a");
let archive_tmpfile = File::create_new(&archive_tmpfile_path)
.map_err(|err| io_error_context("couldn't create the temp file", err))?;
let mut archive_tmpfile = BufWriter::new(archive_tmpfile);
write_archive_to_stream(
&mut archive_tmpfile,
&entries,
archive_kind,
false,
/* is_ec = */ Some(self.sess.target.arch == Arch::Arm64EC),
)?;
archive_tmpfile.flush()?;
drop(archive_tmpfile);
let any_entries = !entries.is_empty();
drop(entries);
// Drop src_archives to unmap all input archives, which is necessary if we want to write the
// output archive to the same location as an input archive on Windows.
drop(self.src_archives);
fs::rename(archive_tmpfile_path, output)
.map_err(|err| io_error_context("failed to rename archive file", err))?;
archive_tmpdir
.close()
.map_err(|err| io_error_context("failed to remove temporary directory", err))?;
Ok(any_entries)
}
}
fn io_error_context(context: &str, err: io::Error) -> io::Error {
io::Error::new(io::ErrorKind::Other, format!("{context}: {err}"))
}
/// Layout constants that differ between ELF32 and ELF64 symbol table entries.
struct ElfSymLayout {
sym_entry_size: usize,
st_info_offset: usize,
st_other_offset: usize,
is_64: bool,
}
impl ElfSymLayout {
const ELF64: ElfSymLayout =
ElfSymLayout { sym_entry_size: 24, st_info_offset: 4, st_other_offset: 5, is_64: true };
const ELF32: ElfSymLayout =
ElfSymLayout { sym_entry_size: 16, st_info_offset: 12, st_other_offset: 13, is_64: false };
}
/// Parsed ELF symbol table information, ready for symbol iteration.
struct ElfSymtab<'a> {
endian: Endianness,
sym_offset: usize,
sym_count: usize,
strtab_data: &'a [u8],
layout: &'static ElfSymLayout,
/// File offset of section header table.
e_shoff: usize,
/// Number of section headers.
e_shnum: usize,
/// Section header index of the strtab linked to the symtab.
strtab_section_index: usize,
}
impl<'a> ElfSymtab<'a> {
fn sym_off(&self, i: usize) -> usize {
self.sym_offset + i * self.layout.sym_entry_size
}
fn binding(&self, data: &[u8], i: usize) -> u8 {
let off = self.sym_off(i);
data[off + self.layout.st_info_offset] >> 4
}
fn is_defined(&self, data: &[u8], i: usize) -> bool {
use object::elf;
let off = self.sym_off(i) + self.layout.st_other_offset + 1;
let bytes: [u8; 2] = data[off..off + 2].try_into().unwrap_or([0, 0]);
let shndx = match self.endian {
Endianness::Little => u16::from_le_bytes(bytes),
Endianness::Big => u16::from_be_bytes(bytes),
};
shndx != elf::SHN_UNDEF as u16
}
/// Read the symbol name from the linked strtab.
fn read_name(&self, data: &[u8], i: usize) -> Option<String> {
let off = self.sym_off(i);
let name_bytes: [u8; 4] = data[off..off + 4].try_into().ok()?;
let name_off: usize = match self.endian {
Endianness::Little => u32::from_le_bytes(name_bytes),
Endianness::Big => u32::from_be_bytes(name_bytes),
} as usize;
if name_off >= self.strtab_data.len() {
return None;
}
let end = self.strtab_data[name_off..]
.iter()
.position(|&b| b == 0)
.unwrap_or(self.strtab_data.len() - name_off);
let name = std::str::from_utf8(&self.strtab_data[name_off..name_off + end]).ok()?;
Some(name.to_string())
}
}
/// Internal helper: parse ELF symtab using the generic `FileHeader` API.
fn elf_parse_symtab<'data, Elf: object::read::elf::FileHeader<Endian = Endianness>>(
data: &'data [u8],
layout: &'static ElfSymLayout,
) -> Option<ElfSymtab<'data>>
where
u64: From<Elf::Word>,
{
use object::elf;
use object::read::elf::SectionHeader as _;
let endian = match Elf::parse(data) {
Ok(h) => match h.endian() {
Ok(e) => e,
Err(_) => return None,
},
Err(_) => return None,
};
let header = Elf::parse(data).unwrap();
let sections = match header.sections(endian, data) {
Ok(s) => s,
Err(_) => return None,
};
let e_shoff = u64::from(header.e_shoff(endian)) as usize;
let e_shnum = sections.len();
for section in sections.iter() {
if section.sh_type(endian) != elf::SHT_SYMTAB {
continue;
}
let strtab_index = section.sh_link(endian) as usize;
let strtab_section = match sections.section(object::SectionIndex(strtab_index)) {
Ok(s) => s,
Err(_) => continue,
};
let strtab_data = match strtab_section.data(endian, data) {
Ok(d) => d,
Err(_) => continue,
};
let sym_offset = u64::from(section.sh_offset(endian)) as usize;
let sym_size = u64::from(section.sh_size(endian)) as usize;
let sym_count = sym_size / layout.sym_entry_size;
return Some(ElfSymtab {
endian,
sym_offset,
sym_count,
strtab_data,
layout,
e_shoff,
e_shnum,
strtab_section_index: strtab_index,
});
}
None
}
/// Detect ELF class and parse symtab.
fn elf_symtab_info(data: &[u8]) -> Option<ElfSymtab<'_>> {
use object::elf;
if data.len() < 16 || &data[0..4] != elf::ELFMAG {
return None;
}
match data[4] {
elf::ELFCLASS64 => {
elf_parse_symtab::<elf::FileHeader64<Endianness>>(data, &ElfSymLayout::ELF64)
}
elf::ELFCLASS32 => {
elf_parse_symtab::<elf::FileHeader32<Endianness>>(data, &ElfSymLayout::ELF32)
}
_ => None,
}
}
/// Collect defined GLOBAL/WEAK symbol names from an ELF object that are NOT in
/// `keep_symbols`. These are the names that should be renamed.
fn elf_collect_rename_set(
data: &[u8],
keep_symbols: &FxHashSet<String>,
out_set: &mut FxHashSet<String>,
) {
use object::elf;
let Some(tab) = elf_symtab_info(data) else { return };
for i in 1..tab.sym_count {
let off = tab.sym_off(i);
if off + tab.layout.sym_entry_size > data.len() {
break;
}
let binding = tab.binding(data, i);
if binding != elf::STB_GLOBAL && binding != elf::STB_WEAK {
continue;
}
if !tab.is_defined(data, i) {
continue;
}
if let Some(name) = tab.read_name(data, i) {
if !keep_symbols.contains(&name) {
out_set.insert(name);
}
}
}
}
/// For ELF object files, hide GLOBAL/WEAK symbols whose names are in
/// `hide_set` by setting their visibility to `STV_HIDDEN`.
fn elf_apply_hide(data: &[u8], hide_set: &FxHashSet<String>) -> Option<Vec<u8>> {
use object::elf;
let tab = elf_symtab_info(data)?;
if tab.sym_count <= 1 {
return None;
}
let mut result: Option<Vec<u8>> = None;
for i in 1..tab.sym_count {
let off = tab.sym_off(i);
if off + tab.layout.sym_entry_size > data.len() {
break;
}
let binding = tab.binding(data, i);
if binding != elf::STB_GLOBAL && binding != elf::STB_WEAK {
continue;
}
if !tab.is_defined(data, i) {
continue;
}
if let Some(name) = tab.read_name(data, i) {
if hide_set.contains(&name) {
let buf = result.get_or_insert_with(|| data.to_vec());
let other = &mut buf[off + tab.layout.st_other_offset];
*other = (*other & !0x03) | elf::STV_HIDDEN;
}
}
}
result
}
/// For ELF object files, rename GLOBAL/WEAK symbols whose names are in
/// `rename_set` by appending `suffix`, and set their visibility to `STV_HIDDEN`.
///
/// move strtab to end: builds a new strtab with renamed
/// names appended, places it at the end of the file, and patches the strtab
/// section header + ELF header. No other section offsets change.
fn elf_apply_rename(
data: &[u8],
rename_set: &FxHashSet<String>,
suffix: &str,
hide: bool,
) -> Option<Vec<u8>> {
use object::elf;
let tab = elf_symtab_info(data)?;
if tab.sym_count <= 1 {
return None;
}
// collect matching symbol names from this file
let mut matched_names: FxHashSet<String> = FxHashSet::default();
for i in 1..tab.sym_count {
let off = tab.sym_off(i);
if off + tab.layout.sym_entry_size > data.len() {
break;
}
let binding = tab.binding(data, i);
if binding != elf::STB_GLOBAL && binding != elf::STB_WEAK {
continue;
}
if let Some(name) = tab.read_name(data, i) {
if rename_set.contains(&name) {
matched_names.insert(name);
}
}
}
if matched_names.is_empty() {
return None;
}
let mut new_strtab: Vec<u8> = tab.strtab_data.to_vec();