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)>,
36 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
37 fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self {
38 use rustc_codegen_ssa::back::link::archive_search_paths;
40 let (src_archives, entries) = if let Some(input) = input {
41 let mut archive = ar::Archive::new(File::open(input).unwrap());
42 let mut entries = Vec::new();
45 while let Some(entry) = archive.next_entry() {
46 let entry = entry.unwrap();
48 String::from_utf8(entry.header().identifier().to_vec()).unwrap(),
49 ArchiveEntry::FromArchive {
57 (vec![(input.to_owned(), archive)], entries)
64 dst: output.to_path_buf(),
65 lib_search_paths: archive_search_paths(sess),
66 use_gnu_style_archive: sess.target.options.archive_format == "gnu",
67 // FIXME fix builtin ranlib on macOS
68 no_builtin_ranlib: sess.target.options.is_like_osx,
72 update_symbols: false,
76 fn src_files(&mut self) -> Vec<String> {
77 self.entries.iter().map(|(name, _)| name.clone()).collect()
80 fn remove_file(&mut self, name: &str) {
84 .position(|(entry_name, _)| entry_name == name)
85 .expect("Tried to remove file not existing in src archive");
86 self.entries.remove(index);
89 fn add_file(&mut self, file: &Path) {
91 file.file_name().unwrap().to_str().unwrap().to_string(),
92 ArchiveEntry::File(file.to_owned()),
96 fn add_native_library(&mut self, name: rustc_span::symbol::Symbol) {
97 let location = find_library(name, &self.lib_search_paths, self.sess);
98 self.add_archive(location.clone(), |_| false)
101 "failed to add native library {}: {}",
102 location.to_string_lossy(),
114 ) -> std::io::Result<()> {
115 let obj_start = name.to_owned();
117 self.add_archive(rlib.to_owned(), move |fname: &str| {
118 // Ignore metadata files, no matter the name.
119 if fname == METADATA_FILENAME {
123 // Don't include Rust objects if LTO is enabled
124 if lto && fname.starts_with(&obj_start) && fname.ends_with(".o") {
128 // Otherwise if this is *not* a rust object and we're skipping
129 // objects then skip this file
130 if skip_objects && (!fname.starts_with(&obj_start) || !fname.ends_with(".o")) {
134 // ok, don't skip this
139 fn update_symbols(&mut self) {
140 self.update_symbols = true;
145 Bsd(ar::Builder<File>),
146 Gnu(ar::GnuBuilder<File>),
149 let sess = self.sess;
151 let mut symbol_table = BTreeMap::new();
153 let mut entries = Vec::new();
155 for (entry_name, entry) in self.entries {
156 // FIXME only read the symbol table of the object files to avoid having to keep all
157 // object files in memory at once, or read them twice.
158 let data = match entry {
159 ArchiveEntry::FromArchive {
163 // FIXME read symbols from symtab
165 let (ref _src_archive_path, ref mut src_archive) =
166 self.src_archives[archive_index];
167 let mut entry = src_archive.jump_to_entry(entry_index).unwrap();
168 let mut data = Vec::new();
169 entry.read_to_end(&mut data).unwrap();
172 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
174 "error while reading object file during archive building: {}",
180 if !self.no_builtin_ranlib {
181 match object::File::parse(&data) {
184 entry_name.as_bytes().to_vec(),
187 .filter_map(|symbol| {
188 if symbol.is_undefined()
190 || symbol.kind() != SymbolKind::Data
191 && symbol.kind() != SymbolKind::Text
192 && symbol.kind() != SymbolKind::Tls
196 symbol.name().map(|name| name.as_bytes().to_vec()).ok()
199 .collect::<Vec<_>>(),
203 let err = err.to_string();
204 if err == "Unknown file magic" {
205 // Not an object file; skip it.
208 "error parsing `{}` during archive creation: {}",
216 entries.push((entry_name, data));
219 let mut builder = if self.use_gnu_style_archive {
222 File::create(&self.dst).unwrap_or_else(|err| {
224 "error opening destination during archive building: {}",
230 .map(|(name, _)| name.as_bytes().to_vec())
232 ar::GnuSymbolTableFormat::Size32,
240 File::create(&self.dst).unwrap_or_else(|err| {
242 "error opening destination during archive building: {}",
253 for (entry_name, data) in entries.into_iter() {
254 let header = ar::Header::new(entry_name.into_bytes(), data.len() as u64);
256 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
257 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
262 std::mem::drop(builder);
264 if self.no_builtin_ranlib {
265 let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
267 // Run ranlib to be able to link the archive
268 let status = std::process::Command::new(ranlib)
271 .expect("Couldn't run ranlib");
273 if !status.success() {
275 .fatal(&format!("Ranlib exited with code {:?}", status.code()));
281 impl<'a> ArArchiveBuilder<'a> {
282 fn add_archive<F>(&mut self, archive_path: PathBuf, mut skip: F) -> std::io::Result<()>
284 F: FnMut(&str) -> bool + 'static,
286 let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
287 let archive_index = self.src_archives.len();
290 while let Some(entry) = archive.next_entry() {
292 let file_name = String::from_utf8(entry.header().identifier().to_vec())
293 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
294 if !skip(&file_name) {
297 ArchiveEntry::FromArchive {
306 self.src_archives.push((archive_path, archive));