1 //! Creation of ar archives like for the lib and staticlib crate type
3 use std::collections::BTreeMap;
4 use std::convert::TryFrom;
6 use std::io::{self, Read, Seek};
7 use std::path::{Path, PathBuf};
9 use rustc_codegen_ssa::back::archive::{find_library, ArchiveBuilder};
10 use rustc_codegen_ssa::METADATA_FILENAME;
11 use rustc_session::Session;
13 use object::read::archive::ArchiveFile;
14 use object::{Object, ObjectSymbol, ReadCache, SymbolKind};
18 FromArchive { archive_index: usize, file_range: (u64, u64) },
22 pub(crate) struct ArArchiveBuilder<'a> {
25 lib_search_paths: Vec<PathBuf>,
26 use_gnu_style_archive: bool,
27 no_builtin_ranlib: bool,
29 src_archives: Vec<File>,
30 // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
31 // the end of an archive for linkers to not get confused.
32 entries: Vec<(Vec<u8>, ArchiveEntry)>,
35 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
36 fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self {
37 use rustc_codegen_ssa::back::link::archive_search_paths;
39 let (src_archives, entries) = if let Some(input) = input {
40 let read_cache = ReadCache::new(File::open(input).unwrap());
41 let archive = ArchiveFile::parse(&read_cache).unwrap();
42 let mut entries = Vec::new();
44 for entry in archive.members() {
45 let entry = entry.unwrap();
47 entry.name().to_vec(),
48 ArchiveEntry::FromArchive { archive_index: 0, file_range: entry.file_range() },
52 (vec![read_cache.into_inner()], entries)
59 dst: output.to_path_buf(),
60 lib_search_paths: archive_search_paths(sess),
61 use_gnu_style_archive: sess.target.archive_format == "gnu",
62 // FIXME fix builtin ranlib on macOS
63 no_builtin_ranlib: sess.target.is_like_osx,
70 fn src_files(&mut self) -> Vec<String> {
71 self.entries.iter().map(|(name, _)| String::from_utf8(name.clone()).unwrap()).collect()
74 fn remove_file(&mut self, name: &str) {
78 .position(|(entry_name, _)| entry_name == name.as_bytes())
79 .expect("Tried to remove file not existing in src archive");
80 self.entries.remove(index);
83 fn add_file(&mut self, file: &Path) {
85 file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
86 ArchiveEntry::File(file.to_owned()),
90 fn add_native_library(&mut self, name: rustc_span::symbol::Symbol, verbatim: bool) {
91 let location = find_library(name, verbatim, &self.lib_search_paths, self.sess);
92 self.add_archive(location.clone(), |_| false).unwrap_or_else(|e| {
93 panic!("failed to add native library {}: {}", location.to_string_lossy(), e);
103 ) -> io::Result<()> {
104 self.add_archive(rlib.to_owned(), move |fname: &str| {
105 // Ignore metadata files, no matter the name.
106 if fname == METADATA_FILENAME {
110 // Don't include Rust objects if LTO is enabled
111 if lto && fname.starts_with(name) && fname.ends_with(".o") {
115 // Otherwise if this is *not* a rust object and we're skipping
116 // objects then skip this file
117 if skip_objects && (!fname.starts_with(name) || !fname.ends_with(".o")) {
121 // ok, don't skip this
126 fn update_symbols(&mut self) {}
130 Bsd(ar::Builder<File>),
131 Gnu(ar::GnuBuilder<File>),
134 let sess = self.sess;
136 let mut symbol_table = BTreeMap::new();
138 let mut entries = Vec::new();
140 for (entry_name, entry) in self.entries {
141 // FIXME only read the symbol table of the object files to avoid having to keep all
142 // object files in memory at once, or read them twice.
143 let data = match entry {
144 ArchiveEntry::FromArchive { archive_index, file_range } => {
145 // FIXME read symbols from symtab
146 let src_read_cache = &mut self.src_archives[archive_index];
148 src_read_cache.seek(io::SeekFrom::Start(file_range.0)).unwrap();
149 let mut data = std::vec::from_elem(0, usize::try_from(file_range.1).unwrap());
150 src_read_cache.read_exact(&mut data).unwrap();
154 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
156 "error while reading object file during archive building: {}",
162 if !self.no_builtin_ranlib {
163 match object::File::parse(&*data) {
169 .filter_map(|symbol| {
170 if symbol.is_undefined()
172 || symbol.kind() != SymbolKind::Data
173 && symbol.kind() != SymbolKind::Text
174 && symbol.kind() != SymbolKind::Tls
178 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
181 .collect::<Vec<_>>(),
185 let err = err.to_string();
186 if err == "Unknown file magic" {
187 // Not an object file; skip it.
190 "error parsing `{}` during archive creation: {}",
191 String::from_utf8_lossy(&entry_name),
199 entries.push((entry_name, data));
202 let mut builder = if self.use_gnu_style_archive {
205 File::create(&self.dst).unwrap_or_else(|err| {
207 "error opening destination during archive building: {}",
211 entries.iter().map(|(name, _)| name.clone()).collect(),
212 ar::GnuSymbolTableFormat::Size32,
220 File::create(&self.dst).unwrap_or_else(|err| {
222 "error opening destination during archive building: {}",
233 for (entry_name, data) in entries.into_iter() {
234 let header = ar::Header::new(entry_name, data.len() as u64);
236 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
237 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
242 std::mem::drop(builder);
244 if self.no_builtin_ranlib {
245 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
247 // Run ranlib to be able to link the archive
248 let status = std::process::Command::new(ranlib)
251 .expect("Couldn't run ranlib");
253 if !status.success() {
254 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
259 fn inject_dll_import_lib(
262 _dll_imports: &[rustc_middle::middle::cstore::DllImport],
263 _tmpdir: &rustc_data_structures::temp_dir::MaybeTempDir,
265 bug!("injecting dll imports is not supported");
269 impl<'a> ArArchiveBuilder<'a> {
270 fn add_archive<F>(&mut self, archive_path: PathBuf, mut skip: F) -> io::Result<()>
272 F: FnMut(&str) -> bool,
274 let read_cache = ReadCache::new(std::fs::File::open(&archive_path)?);
275 let archive = ArchiveFile::parse(&read_cache).unwrap();
276 let archive_index = self.src_archives.len();
278 for entry in archive.members() {
279 let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
280 let file_name = String::from_utf8(entry.name().to_vec())
281 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
282 if !skip(&file_name) {
284 file_name.into_bytes(),
285 ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
290 self.src_archives.push(read_cache.into_inner());