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) -> Self {
36 dst: output.to_path_buf(),
37 use_gnu_style_archive: sess.target.archive_format == "gnu",
38 // FIXME fix builtin ranlib on macOS
39 no_builtin_ranlib: sess.target.is_like_osx,
46 fn add_file(&mut self, file: &Path) {
48 file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
49 ArchiveEntry::File(file.to_owned()),
53 fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
55 F: FnMut(&str) -> bool + 'static,
57 let read_cache = ReadCache::new(std::fs::File::open(&archive_path)?);
58 let archive = ArchiveFile::parse(&read_cache).unwrap();
59 let archive_index = self.src_archives.len();
61 for entry in archive.members() {
62 let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
63 let file_name = String::from_utf8(entry.name().to_vec())
64 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
65 if !skip(&file_name) {
67 file_name.into_bytes(),
68 ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
73 self.src_archives.push(read_cache.into_inner());
77 fn build(mut self) -> bool {
79 Bsd(ar::Builder<File>),
80 Gnu(ar::GnuBuilder<File>),
85 let mut symbol_table = BTreeMap::new();
87 let mut entries = Vec::new();
89 for (entry_name, entry) in self.entries {
90 // FIXME only read the symbol table of the object files to avoid having to keep all
91 // object files in memory at once, or read them twice.
92 let data = match entry {
93 ArchiveEntry::FromArchive { archive_index, file_range } => {
94 // FIXME read symbols from symtab
95 let src_read_cache = &mut self.src_archives[archive_index];
97 src_read_cache.seek(io::SeekFrom::Start(file_range.0)).unwrap();
98 let mut data = std::vec::from_elem(0, usize::try_from(file_range.1).unwrap());
99 src_read_cache.read_exact(&mut data).unwrap();
103 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
105 "error while reading object file during archive building: {}",
111 if !self.no_builtin_ranlib {
112 match object::File::parse(&*data) {
118 .filter_map(|symbol| {
119 if symbol.is_undefined() || symbol.is_local() {
122 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
125 .collect::<Vec<_>>(),
129 let err = err.to_string();
130 if err == "Unknown file magic" {
131 // Not an object file; skip it.
134 "error parsing `{}` during archive creation: {}",
135 String::from_utf8_lossy(&entry_name),
143 entries.push((entry_name, data));
146 let mut builder = if self.use_gnu_style_archive {
149 File::create(&self.dst).unwrap_or_else(|err| {
151 "error opening destination during archive building: {}",
155 entries.iter().map(|(name, _)| name.clone()).collect(),
156 ar::GnuSymbolTableFormat::Size32,
164 File::create(&self.dst).unwrap_or_else(|err| {
166 "error opening destination during archive building: {}",
176 let any_members = !entries.is_empty();
179 for (entry_name, data) in entries.into_iter() {
180 let header = ar::Header::new(entry_name, data.len() as u64);
182 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
183 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
188 std::mem::drop(builder);
190 if self.no_builtin_ranlib {
191 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
193 // Run ranlib to be able to link the archive
194 let status = std::process::Command::new(ranlib)
197 .expect("Couldn't run ranlib");
199 if !status.success() {
200 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
207 fn sess(&self) -> &Session {
211 fn create_dll_import_lib(
214 _dll_imports: &[rustc_session::cstore::DllImport],
217 bug!("creating dll imports is not supported");