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;
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 ArArchiveBuilder<'a> {
23 use_gnu_style_archive: bool,
24 no_builtin_ranlib: bool,
26 src_archives: Vec<File>,
27 // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
28 // the end of an archive for linkers to not get confused.
29 entries: Vec<(Vec<u8>, ArchiveEntry)>,
32 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
33 fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self {
34 let (src_archives, entries) = if let Some(input) = input {
35 let read_cache = ReadCache::new(File::open(input).unwrap());
36 let archive = ArchiveFile::parse(&read_cache).unwrap();
37 let mut entries = Vec::new();
39 for entry in archive.members() {
40 let entry = entry.unwrap();
42 entry.name().to_vec(),
43 ArchiveEntry::FromArchive { archive_index: 0, file_range: entry.file_range() },
47 (vec![read_cache.into_inner()], entries)
54 dst: output.to_path_buf(),
55 use_gnu_style_archive: sess.target.archive_format == "gnu",
56 // FIXME fix builtin ranlib on macOS
57 no_builtin_ranlib: sess.target.is_like_osx,
64 fn add_file(&mut self, file: &Path) {
66 file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
67 ArchiveEntry::File(file.to_owned()),
71 fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
73 F: FnMut(&str) -> bool + 'static,
75 let read_cache = ReadCache::new(std::fs::File::open(&archive_path)?);
76 let archive = ArchiveFile::parse(&read_cache).unwrap();
77 let archive_index = self.src_archives.len();
79 for entry in archive.members() {
80 let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
81 let file_name = String::from_utf8(entry.name().to_vec())
82 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
83 if !skip(&file_name) {
85 file_name.into_bytes(),
86 ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
91 self.src_archives.push(read_cache.into_inner());
97 Bsd(ar::Builder<File>),
98 Gnu(ar::GnuBuilder<File>),
101 let sess = self.sess;
103 let mut symbol_table = BTreeMap::new();
105 let mut entries = Vec::new();
107 for (entry_name, entry) in self.entries {
108 // FIXME only read the symbol table of the object files to avoid having to keep all
109 // object files in memory at once, or read them twice.
110 let data = match entry {
111 ArchiveEntry::FromArchive { archive_index, file_range } => {
112 // FIXME read symbols from symtab
113 let src_read_cache = &mut self.src_archives[archive_index];
115 src_read_cache.seek(io::SeekFrom::Start(file_range.0)).unwrap();
116 let mut data = std::vec::from_elem(0, usize::try_from(file_range.1).unwrap());
117 src_read_cache.read_exact(&mut data).unwrap();
121 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
123 "error while reading object file during archive building: {}",
129 if !self.no_builtin_ranlib {
130 match object::File::parse(&*data) {
136 .filter_map(|symbol| {
137 if symbol.is_undefined() || symbol.is_local() {
140 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
143 .collect::<Vec<_>>(),
147 let err = err.to_string();
148 if err == "Unknown file magic" {
149 // Not an object file; skip it.
152 "error parsing `{}` during archive creation: {}",
153 String::from_utf8_lossy(&entry_name),
161 entries.push((entry_name, data));
164 let mut builder = if self.use_gnu_style_archive {
167 File::create(&self.dst).unwrap_or_else(|err| {
169 "error opening destination during archive building: {}",
173 entries.iter().map(|(name, _)| name.clone()).collect(),
174 ar::GnuSymbolTableFormat::Size32,
182 File::create(&self.dst).unwrap_or_else(|err| {
184 "error opening destination during archive building: {}",
195 for (entry_name, data) in entries.into_iter() {
196 let header = ar::Header::new(entry_name, data.len() as u64);
198 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
199 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
204 std::mem::drop(builder);
206 if self.no_builtin_ranlib {
207 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
209 // Run ranlib to be able to link the archive
210 let status = std::process::Command::new(ranlib)
213 .expect("Couldn't run ranlib");
215 if !status.success() {
216 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
221 fn inject_dll_import_lib(
224 _dll_imports: &[rustc_session::cstore::DllImport],
225 _tmpdir: &rustc_data_structures::temp_dir::MaybeTempDir,
227 bug!("injecting dll imports is not supported");