1 //! Creation of ar archives like for the lib and staticlib crate type
3 use std::collections::BTreeMap;
5 use std::path::{Path, PathBuf};
7 use rustc_codegen_ssa::back::archive::ArchiveBuilder;
8 use rustc_session::Session;
10 use object::{Object, ObjectSymbol, SymbolKind};
14 FromArchive { archive_index: usize, entry_index: usize },
18 pub(crate) struct ArArchiveBuilder<'a> {
21 use_gnu_style_archive: bool,
22 no_builtin_ranlib: bool,
24 src_archives: Vec<(PathBuf, ar::Archive<File>)>,
25 // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
26 // the end of an archive for linkers to not get confused.
27 entries: Vec<(String, ArchiveEntry)>,
30 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
31 fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self {
32 let (src_archives, entries) = if let Some(input) = input {
33 let mut archive = ar::Archive::new(File::open(input).unwrap());
34 let mut entries = Vec::new();
37 while let Some(entry) = archive.next_entry() {
38 let entry = entry.unwrap();
40 String::from_utf8(entry.header().identifier().to_vec()).unwrap(),
41 ArchiveEntry::FromArchive { archive_index: 0, entry_index: i },
46 (vec![(input.to_owned(), archive)], entries)
53 dst: output.to_path_buf(),
54 use_gnu_style_archive: sess.target.archive_format == "gnu",
55 // FIXME fix builtin ranlib on macOS
56 no_builtin_ranlib: sess.target.is_like_osx,
63 fn src_files(&mut self) -> Vec<String> {
64 self.entries.iter().map(|(name, _)| name.clone()).collect()
67 fn remove_file(&mut self, name: &str) {
71 .position(|(entry_name, _)| entry_name == name)
72 .expect("Tried to remove file not existing in src archive");
73 self.entries.remove(index);
76 fn add_file(&mut self, file: &Path) {
78 file.file_name().unwrap().to_str().unwrap().to_string(),
79 ArchiveEntry::File(file.to_owned()),
83 fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
85 F: FnMut(&str) -> bool + 'static,
87 let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
88 let archive_index = self.src_archives.len();
91 while let Some(entry) = archive.next_entry() {
93 let file_name = String::from_utf8(entry.header().identifier().to_vec())
94 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
95 if !skip(&file_name) {
97 .push((file_name, ArchiveEntry::FromArchive { archive_index, entry_index: i }));
102 self.src_archives.push((archive_path.to_owned(), archive));
106 fn update_symbols(&mut self) {}
110 Bsd(ar::Builder<File>),
111 Gnu(ar::GnuBuilder<File>),
114 let sess = self.sess;
116 let mut symbol_table = BTreeMap::new();
118 let mut entries = Vec::new();
120 for (entry_name, entry) in self.entries {
121 // FIXME only read the symbol table of the object files to avoid having to keep all
122 // object files in memory at once, or read them twice.
123 let data = match entry {
124 ArchiveEntry::FromArchive { archive_index, entry_index } => {
125 // FIXME read symbols from symtab
127 let (ref _src_archive_path, ref mut src_archive) =
128 self.src_archives[archive_index];
129 let mut entry = src_archive.jump_to_entry(entry_index).unwrap();
130 let mut data = Vec::new();
131 entry.read_to_end(&mut data).unwrap();
134 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
136 "error while reading object file during archive building: {}",
142 if !self.no_builtin_ranlib {
143 match object::File::parse(&*data) {
146 entry_name.as_bytes().to_vec(),
149 .filter_map(|symbol| {
150 if symbol.is_undefined()
152 || symbol.kind() != SymbolKind::Data
153 && symbol.kind() != SymbolKind::Text
154 && symbol.kind() != SymbolKind::Tls
158 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
161 .collect::<Vec<_>>(),
165 let err = err.to_string();
166 if err == "Unknown file magic" {
167 // Not an object file; skip it.
170 "error parsing `{}` during archive creation: {}",
178 entries.push((entry_name, data));
181 let mut builder = if self.use_gnu_style_archive {
184 File::create(&self.dst).unwrap_or_else(|err| {
186 "error opening destination during archive building: {}",
190 entries.iter().map(|(name, _)| name.as_bytes().to_vec()).collect(),
191 ar::GnuSymbolTableFormat::Size32,
199 File::create(&self.dst).unwrap_or_else(|err| {
201 "error opening destination during archive building: {}",
212 for (entry_name, data) in entries.into_iter() {
213 let header = ar::Header::new(entry_name.into_bytes(), 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()));
238 fn inject_dll_import_lib(
241 _dll_imports: &[rustc_middle::middle::cstore::DllImport],
242 _tmpdir: &rustc_data_structures::temp_dir::MaybeTempDir,
244 bug!("injecting dll imports is not supported");