1 //! Creation of ar archives like for the lib and staticlib crate type
3 use std::collections::BTreeMap;
5 use std::io::{self, Read, Seek};
6 use std::path::{Path, PathBuf};
8 use rustc_codegen_ssa::back::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
9 use rustc_session::Session;
11 use object::read::archive::ArchiveFile;
12 use object::{Object, ObjectSymbol, ReadCache};
16 FromArchive { archive_index: usize, file_range: (u64, u64) },
20 pub(crate) struct ArArchiveBuilderBuilder;
22 impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder {
23 fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder<'a> + 'a> {
24 Box::new(ArArchiveBuilder {
26 use_gnu_style_archive: sess.target.archive_format == "gnu",
27 // FIXME fix builtin ranlib on macOS
28 no_builtin_ranlib: sess.target.is_like_osx,
35 fn create_dll_import_lib(
39 _dll_imports: &[rustc_session::cstore::DllImport],
41 _is_direct_dependency: bool,
43 bug!("creating dll imports is not supported");
47 pub(crate) struct ArArchiveBuilder<'a> {
49 use_gnu_style_archive: bool,
50 no_builtin_ranlib: bool,
52 src_archives: Vec<File>,
53 // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
54 // the end of an archive for linkers to not get confused.
55 entries: Vec<(Vec<u8>, ArchiveEntry)>,
58 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
59 fn add_file(&mut self, file: &Path) {
61 file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
62 ArchiveEntry::File(file.to_owned()),
69 mut skip: Box<dyn FnMut(&str) -> bool + 'static>,
70 ) -> std::io::Result<()> {
71 let read_cache = ReadCache::new(std::fs::File::open(&archive_path)?);
72 let archive = ArchiveFile::parse(&read_cache).unwrap();
73 let archive_index = self.src_archives.len();
75 for entry in archive.members() {
76 let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
77 let file_name = String::from_utf8(entry.name().to_vec())
78 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
79 if !skip(&file_name) {
81 file_name.into_bytes(),
82 ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
87 self.src_archives.push(read_cache.into_inner());
91 fn build(mut self: Box<Self>, output: &Path) -> bool {
93 Bsd(ar::Builder<File>),
94 Gnu(ar::GnuBuilder<File>),
99 let mut symbol_table = BTreeMap::new();
101 let mut entries = Vec::new();
103 for (mut entry_name, entry) in self.entries {
104 // FIXME only read the symbol table of the object files to avoid having to keep all
105 // object files in memory at once, or read them twice.
106 let data = match entry {
107 ArchiveEntry::FromArchive { archive_index, file_range } => {
108 // FIXME read symbols from symtab
109 let src_read_cache = &mut self.src_archives[archive_index];
111 src_read_cache.seek(io::SeekFrom::Start(file_range.0)).unwrap();
112 let mut data = std::vec::from_elem(0, usize::try_from(file_range.1).unwrap());
113 src_read_cache.read_exact(&mut data).unwrap();
117 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
119 "error while reading object file during archive building: {}",
125 if !self.no_builtin_ranlib {
126 if symbol_table.contains_key(&entry_name) {
127 // The ar crate can't handle creating a symbol table in case of multiple archive
128 // members with the same name. Work around this by prepending a number until we
129 // get a unique name.
131 let new_name = format!("{}_", i)
134 .chain(entry_name.iter().copied())
135 .collect::<Vec<_>>();
136 if !symbol_table.contains_key(&new_name) {
137 entry_name = new_name;
143 match object::File::parse(&*data) {
149 .filter_map(|symbol| {
150 if symbol.is_undefined() || symbol.is_local() {
153 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
156 .collect::<Vec<_>>(),
160 let err = err.to_string();
161 if err == "Unknown file magic" {
162 // Not an object file; skip it.
163 } else if object::read::archive::ArchiveFile::parse(&*data).is_ok() {
164 // Nested archive file; skip it.
167 "error parsing `{}` during archive creation: {}",
168 String::from_utf8_lossy(&entry_name),
176 entries.push((entry_name, data));
179 let mut builder = if self.use_gnu_style_archive {
182 File::create(output).unwrap_or_else(|err| {
184 "error opening destination during archive building: {}",
188 entries.iter().map(|(name, _)| name.clone()).collect(),
189 ar::GnuSymbolTableFormat::Size32,
197 File::create(output).unwrap_or_else(|err| {
199 "error opening destination during archive building: {}",
209 let any_members = !entries.is_empty();
212 for (entry_name, data) in entries.into_iter() {
213 let header = ar::Header::new(entry_name, data.len() as u64);
215 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
216 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
221 std::mem::drop(builder);
223 if self.no_builtin_ranlib {
224 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
226 // Run ranlib to be able to link the archive
227 let status = std::process::Command::new(ranlib)
230 .expect("Couldn't run ranlib");
232 if !status.success() {
233 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));