]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/archive.rs
Rollup merge of #88553 - theo-lw:issue-88276, r=estebank
[rust.git] / compiler / rustc_codegen_cranelift / src / archive.rs
1 //! Creation of ar archives like for the lib and staticlib crate type
2
3 use std::collections::BTreeMap;
4 use std::fs::File;
5 use std::path::{Path, PathBuf};
6
7 use rustc_codegen_ssa::back::archive::ArchiveBuilder;
8 use rustc_session::Session;
9
10 use object::{Object, ObjectSymbol, SymbolKind};
11
12 #[derive(Debug)]
13 enum ArchiveEntry {
14     FromArchive { archive_index: usize, entry_index: usize },
15     File(PathBuf),
16 }
17
18 pub(crate) struct ArArchiveBuilder<'a> {
19     sess: &'a Session,
20     dst: PathBuf,
21     use_gnu_style_archive: bool,
22     no_builtin_ranlib: bool,
23
24     src_archives: Vec<(PathBuf, ar::Archive<File>)>,
25     // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
26     // the end of an archive for linkers to not get confused.
27     entries: Vec<(String, ArchiveEntry)>,
28 }
29
30 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
31     fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self {
32         let (src_archives, entries) = if let Some(input) = input {
33             let mut archive = ar::Archive::new(File::open(input).unwrap());
34             let mut entries = Vec::new();
35
36             let mut i = 0;
37             while let Some(entry) = archive.next_entry() {
38                 let entry = entry.unwrap();
39                 entries.push((
40                     String::from_utf8(entry.header().identifier().to_vec()).unwrap(),
41                     ArchiveEntry::FromArchive { archive_index: 0, entry_index: i },
42                 ));
43                 i += 1;
44             }
45
46             (vec![(input.to_owned(), archive)], entries)
47         } else {
48             (vec![], Vec::new())
49         };
50
51         ArArchiveBuilder {
52             sess,
53             dst: output.to_path_buf(),
54             use_gnu_style_archive: sess.target.archive_format == "gnu",
55             // FIXME fix builtin ranlib on macOS
56             no_builtin_ranlib: sess.target.is_like_osx,
57
58             src_archives,
59             entries,
60         }
61     }
62
63     fn src_files(&mut self) -> Vec<String> {
64         self.entries.iter().map(|(name, _)| name.clone()).collect()
65     }
66
67     fn remove_file(&mut self, name: &str) {
68         let index = self
69             .entries
70             .iter()
71             .position(|(entry_name, _)| entry_name == name)
72             .expect("Tried to remove file not existing in src archive");
73         self.entries.remove(index);
74     }
75
76     fn add_file(&mut self, file: &Path) {
77         self.entries.push((
78             file.file_name().unwrap().to_str().unwrap().to_string(),
79             ArchiveEntry::File(file.to_owned()),
80         ));
81     }
82
83     fn add_archive<F>(&mut self, archive_path: &Path, mut skip: F) -> std::io::Result<()>
84     where
85         F: FnMut(&str) -> bool + 'static,
86     {
87         let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
88         let archive_index = self.src_archives.len();
89
90         let mut i = 0;
91         while let Some(entry) = archive.next_entry() {
92             let entry = entry?;
93             let file_name = String::from_utf8(entry.header().identifier().to_vec())
94                 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
95             if !skip(&file_name) {
96                 self.entries
97                     .push((file_name, ArchiveEntry::FromArchive { archive_index, entry_index: i }));
98             }
99             i += 1;
100         }
101
102         self.src_archives.push((archive_path.to_owned(), archive));
103         Ok(())
104     }
105
106     fn update_symbols(&mut self) {}
107
108     fn build(mut self) {
109         enum BuilderKind {
110             Bsd(ar::Builder<File>),
111             Gnu(ar::GnuBuilder<File>),
112         }
113
114         let sess = self.sess;
115
116         let mut symbol_table = BTreeMap::new();
117
118         let mut entries = Vec::new();
119
120         for (entry_name, entry) in self.entries {
121             // FIXME only read the symbol table of the object files to avoid having to keep all
122             // object files in memory at once, or read them twice.
123             let data = match entry {
124                 ArchiveEntry::FromArchive { archive_index, entry_index } => {
125                     // FIXME read symbols from symtab
126                     use std::io::Read;
127                     let (ref _src_archive_path, ref mut src_archive) =
128                         self.src_archives[archive_index];
129                     let mut entry = src_archive.jump_to_entry(entry_index).unwrap();
130                     let mut data = Vec::new();
131                     entry.read_to_end(&mut data).unwrap();
132                     data
133                 }
134                 ArchiveEntry::File(file) => std::fs::read(file).unwrap_or_else(|err| {
135                     sess.fatal(&format!(
136                         "error while reading object file during archive building: {}",
137                         err
138                     ));
139                 }),
140             };
141
142             if !self.no_builtin_ranlib {
143                 match object::File::parse(&*data) {
144                     Ok(object) => {
145                         symbol_table.insert(
146                             entry_name.as_bytes().to_vec(),
147                             object
148                                 .symbols()
149                                 .filter_map(|symbol| {
150                                     if symbol.is_undefined()
151                                         || symbol.is_local()
152                                         || symbol.kind() != SymbolKind::Data
153                                             && symbol.kind() != SymbolKind::Text
154                                             && symbol.kind() != SymbolKind::Tls
155                                     {
156                                         None
157                                     } else {
158                                         symbol.name().map(|name| name.as_bytes().to_vec()).ok()
159                                     }
160                                 })
161                                 .collect::<Vec<_>>(),
162                         );
163                     }
164                     Err(err) => {
165                         let err = err.to_string();
166                         if err == "Unknown file magic" {
167                             // Not an object file; skip it.
168                         } else {
169                             sess.fatal(&format!(
170                                 "error parsing `{}` during archive creation: {}",
171                                 entry_name, err
172                             ));
173                         }
174                     }
175                 }
176             }
177
178             entries.push((entry_name, data));
179         }
180
181         let mut builder = if self.use_gnu_style_archive {
182             BuilderKind::Gnu(
183                 ar::GnuBuilder::new(
184                     File::create(&self.dst).unwrap_or_else(|err| {
185                         sess.fatal(&format!(
186                             "error opening destination during archive building: {}",
187                             err
188                         ));
189                     }),
190                     entries.iter().map(|(name, _)| name.as_bytes().to_vec()).collect(),
191                     ar::GnuSymbolTableFormat::Size32,
192                     symbol_table,
193                 )
194                 .unwrap(),
195             )
196         } else {
197             BuilderKind::Bsd(
198                 ar::Builder::new(
199                     File::create(&self.dst).unwrap_or_else(|err| {
200                         sess.fatal(&format!(
201                             "error opening destination during archive building: {}",
202                             err
203                         ));
204                     }),
205                     symbol_table,
206                 )
207                 .unwrap(),
208             )
209         };
210
211         // Add all files
212         for (entry_name, data) in entries.into_iter() {
213             let header = ar::Header::new(entry_name.into_bytes(), data.len() as u64);
214             match builder {
215                 BuilderKind::Bsd(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
216                 BuilderKind::Gnu(ref mut builder) => builder.append(&header, &mut &*data).unwrap(),
217             }
218         }
219
220         // Finalize archive
221         std::mem::drop(builder);
222
223         if self.no_builtin_ranlib {
224             let ranlib = crate::toolchain::get_toolchain_binary(self.sess, "ranlib");
225
226             // Run ranlib to be able to link the archive
227             let status = std::process::Command::new(ranlib)
228                 .arg(self.dst)
229                 .status()
230                 .expect("Couldn't run ranlib");
231
232             if !status.success() {
233                 self.sess.fatal(&format!("Ranlib exited with code {:?}", status.code()));
234             }
235         }
236     }
237
238     fn inject_dll_import_lib(
239         &mut self,
240         _lib_name: &str,
241         _dll_imports: &[rustc_middle::middle::cstore::DllImport],
242         _tmpdir: &rustc_data_structures::temp_dir::MaybeTempDir,
243     ) {
244         bug!("injecting dll imports is not supported");
245     }
246 }