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::{find_library, ArchiveBuilder};
8 use rustc_codegen_ssa::METADATA_FILENAME;
9 use rustc_session::Session;
11 use object::{Object, ObjectSymbol, SymbolKind};
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<(PathBuf, ar::Archive<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<(String, 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 mut archive = ar::Archive::new(File::open(input).unwrap());
41 let mut entries = Vec::new();
44 while let Some(entry) = archive.next_entry() {
45 let entry = entry.unwrap();
47 String::from_utf8(entry.header().identifier().to_vec()).unwrap(),
48 ArchiveEntry::FromArchive {
56 (vec![(input.to_owned(), archive)], entries)
63 dst: output.to_path_buf(),
64 lib_search_paths: archive_search_paths(sess),
65 use_gnu_style_archive: sess.target.archive_format == "gnu",
66 // FIXME fix builtin ranlib on macOS
67 no_builtin_ranlib: sess.target.is_like_osx,
74 fn src_files(&mut self) -> Vec<String> {
75 self.entries.iter().map(|(name, _)| name.clone()).collect()
78 fn remove_file(&mut self, name: &str) {
82 .position(|(entry_name, _)| entry_name == name)
83 .expect("Tried to remove file not existing in src archive");
84 self.entries.remove(index);
87 fn add_file(&mut self, file: &Path) {
89 file.file_name().unwrap().to_str().unwrap().to_string(),
90 ArchiveEntry::File(file.to_owned()),
94 fn add_native_library(&mut self, name: rustc_span::symbol::Symbol) {
95 let location = find_library(name, &self.lib_search_paths, self.sess);
96 self.add_archive(location.clone(), |_| false)
99 "failed to add native library {}: {}",
100 location.to_string_lossy(),
112 ) -> std::io::Result<()> {
113 let obj_start = name.to_owned();
115 self.add_archive(rlib.to_owned(), move |fname: &str| {
116 // Ignore metadata files, no matter the name.
117 if fname == METADATA_FILENAME {
121 // Don't include Rust objects if LTO is enabled
122 if lto && fname.starts_with(&obj_start) && fname.ends_with(".o") {
126 // Otherwise if this is *not* a rust object and we're skipping
127 // objects then skip this file
128 if skip_objects && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
132 // ok, don't skip this
137 fn update_symbols(&mut self) {}
141 Bsd(ar::Builder<File>),
142 Gnu(ar::GnuBuilder<File>),
145 let sess = self.sess;
147 let mut symbol_table = BTreeMap::new();
149 let mut entries = Vec::new();
151 for (entry_name, entry) in self.entries {
152 // FIXME only read the symbol table of the object files to avoid having to keep all
153 // object files in memory at once, or read them twice.
154 let data = match entry {
155 ArchiveEntry::FromArchive {
159 // FIXME read symbols from symtab
161 let (ref _src_archive_path, ref mut src_archive) =
162 self.src_archives[archive_index];
163 let mut entry = src_archive.jump_to_entry(entry_index).unwrap();
164 let mut data = Vec::new();
165 entry.read_to_end(&mut data).unwrap();
168 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
170 "error while reading object file during archive building: {}",
176 if !self.no_builtin_ranlib {
177 match object::File::parse(&data) {
180 entry_name.as_bytes().to_vec(),
183 .filter_map(|symbol| {
184 if symbol.is_undefined()
186 || symbol.kind() != SymbolKind::Data
187 && symbol.kind() != SymbolKind::Text
188 && symbol.kind() != SymbolKind::Tls
192 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
195 .collect::<Vec<_>>(),
199 let err = err.to_string();
200 if err == "Unknown file magic" {
201 // Not an object file; skip it.
204 "error parsing `{}` during archive creation: {}",
212 entries.push((entry_name, data));
215 let mut builder = if self.use_gnu_style_archive {
218 File::create(&self.dst).unwrap_or_else(|err| {
220 "error opening destination during archive building: {}",
226 .map(|(name, _)| name.as_bytes().to_vec())
228 ar::GnuSymbolTableFormat::Size32,
236 File::create(&self.dst).unwrap_or_else(|err| {
238 "error opening destination during archive building: {}",
249 for (entry_name, data) in entries.into_iter() {
250 let header = ar::Header::new(entry_name.into_bytes(), data.len() as u64);
252 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
253 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
258 std::mem::drop(builder);
260 if self.no_builtin_ranlib {
261 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
263 // Run ranlib to be able to link the archive
264 let status = std::process::Command::new(ranlib)
267 .expect("Couldn't run ranlib");
269 if !status.success() {
271 .fatal(&format!("Ranlib exited with code {:?}", status.code()));
277 impl<'a> ArArchiveBuilder<'a> {
278 fn add_archive<F>(&mut self, archive_path: PathBuf, mut skip: F) -> std::io::Result<()>
280 F: FnMut(&str) -> bool + 'static,
282 let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
283 let archive_index = self.src_archives.len();
286 while let Some(entry) = archive.next_entry() {
288 let file_name = String::from_utf8(entry.header().identifier().to_vec())
289 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
290 if !skip(&file_name) {
293 ArchiveEntry::FromArchive {
302 self.src_archives.push((archive_path, archive));