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> {
22 use_gnu_style_archive: bool,
23 no_builtin_ranlib: bool,
25 src_archives: Vec<File>,
26 // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
27 // the end of an archive for linkers to not get confused.
28 entries: Vec<(Vec<u8>, ArchiveEntry)>,
31 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
32 fn new(sess: &'a Session) -> Self {
35 use_gnu_style_archive: sess.target.archive_format == "gnu",
36 // FIXME fix builtin ranlib on macOS
37 no_builtin_ranlib: sess.target.is_like_osx,
44 fn add_file(&mut self, file: &Path) {
46 file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
47 ArchiveEntry::File(file.to_owned()),
51 fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
53 F: FnMut(&str) -> bool + 'static,
55 let read_cache = ReadCache::new(std::fs::File::open(&archive_path)?);
56 let archive = ArchiveFile::parse(&read_cache).unwrap();
57 let archive_index = self.src_archives.len();
59 for entry in archive.members() {
60 let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
61 let file_name = String::from_utf8(entry.name().to_vec())
62 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
63 if !skip(&file_name) {
65 file_name.into_bytes(),
66 ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
71 self.src_archives.push(read_cache.into_inner());
75 fn build(mut self, output: &Path) -> bool {
77 Bsd(ar::Builder<File>),
78 Gnu(ar::GnuBuilder<File>),
83 let mut symbol_table = BTreeMap::new();
85 let mut entries = Vec::new();
87 for (mut entry_name, entry) in self.entries {
88 // FIXME only read the symbol table of the object files to avoid having to keep all
89 // object files in memory at once, or read them twice.
90 let data = match entry {
91 ArchiveEntry::FromArchive { archive_index, file_range } => {
92 // FIXME read symbols from symtab
93 let src_read_cache = &mut self.src_archives[archive_index];
95 src_read_cache.seek(io::SeekFrom::Start(file_range.0)).unwrap();
96 let mut data = std::vec::from_elem(0, usize::try_from(file_range.1).unwrap());
97 src_read_cache.read_exact(&mut data).unwrap();
101 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
103 "error while reading object file during archive building: {}",
109 if !self.no_builtin_ranlib {
110 if symbol_table.contains_key(&entry_name) {
111 // The ar crate can't handle creating a symbol table in case of multiple archive
112 // members with the same name. Work around this by prepending a number until we
113 // get a unique name.
115 let new_name = format!("{}_", i)
118 .chain(entry_name.iter().copied())
119 .collect::<Vec<_>>();
120 if !symbol_table.contains_key(&new_name) {
121 entry_name = new_name;
127 match object::File::parse(&*data) {
133 .filter_map(|symbol| {
134 if symbol.is_undefined() || symbol.is_local() {
137 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
140 .collect::<Vec<_>>(),
144 let err = err.to_string();
145 if err == "Unknown file magic" {
146 // Not an object file; skip it.
149 "error parsing `{}` during archive creation: {}",
150 String::from_utf8_lossy(&entry_name),
158 entries.push((entry_name, data));
161 let mut builder = if self.use_gnu_style_archive {
164 File::create(output).unwrap_or_else(|err| {
166 "error opening destination during archive building: {}",
170 entries.iter().map(|(name, _)| name.clone()).collect(),
171 ar::GnuSymbolTableFormat::Size32,
179 File::create(output).unwrap_or_else(|err| {
181 "error opening destination during archive building: {}",
191 let any_members = !entries.is_empty();
194 for (entry_name, data) in entries.into_iter() {
195 let header = ar::Header::new(entry_name, data.len() as u64);
197 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
198 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
203 std::mem::drop(builder);
205 if self.no_builtin_ranlib {
206 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
208 // Run ranlib to be able to link the archive
209 let status = std::process::Command::new(ranlib)
212 .expect("Couldn't run ranlib");
214 if !status.success() {
215 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
222 fn create_dll_import_lib(
225 _dll_imports: &[rustc_session::cstore::DllImport],
228 bug!("creating dll imports is not supported");