]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/archive.rs
Auto merge of #102573 - RalfJung:mirisync, r=oli-obk
[rust.git] / compiler / rustc_codegen_gcc / src / archive.rs
1 use std::fs::File;
2 use std::path::{Path, PathBuf};
3
4 use crate::errors::RanlibFailure;
5
6 use rustc_codegen_ssa::back::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
7 use rustc_session::Session;
8
9 use rustc_session::cstore::DllImport;
10
11 struct ArchiveConfig<'a> {
12     sess: &'a Session,
13     use_native_ar: bool,
14     use_gnu_style_archive: bool,
15 }
16
17 #[derive(Debug)]
18 enum ArchiveEntry {
19     FromArchive {
20         archive_index: usize,
21         entry_index: usize,
22     },
23     File(PathBuf),
24 }
25
26 pub struct ArArchiveBuilderBuilder;
27
28 impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder {
29     fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder<'a> + 'a> {
30         let config = ArchiveConfig {
31             sess,
32             use_native_ar: false,
33             // FIXME test for linux and System V derivatives instead
34             use_gnu_style_archive: sess.target.options.archive_format == "gnu",
35         };
36
37         Box::new(ArArchiveBuilder {
38             config,
39             src_archives: vec![],
40             entries: vec![],
41         })
42     }
43
44     fn create_dll_import_lib(
45         &self,
46         _sess: &Session,
47         _lib_name: &str,
48         _dll_imports: &[DllImport],
49         _tmpdir: &Path,
50     ) -> PathBuf {
51         unimplemented!();
52     }
53 }
54
55 pub struct ArArchiveBuilder<'a> {
56     config: ArchiveConfig<'a>,
57     src_archives: Vec<(PathBuf, ar::Archive<File>)>,
58     // Don't use `HashMap` here, as the order is important. `rust.metadata.bin` must always be at
59     // the end of an archive for linkers to not get confused.
60     entries: Vec<(String, ArchiveEntry)>,
61 }
62
63 impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
64     fn add_file(&mut self, file: &Path) {
65         self.entries.push((
66             file.file_name().unwrap().to_str().unwrap().to_string(),
67             ArchiveEntry::File(file.to_owned()),
68         ));
69     }
70
71     fn add_archive(
72         &mut self,
73         archive_path: &Path,
74         mut skip: Box<dyn FnMut(&str) -> bool + 'static>,
75     ) -> std::io::Result<()> {
76         let mut archive = ar::Archive::new(std::fs::File::open(&archive_path)?);
77         let archive_index = self.src_archives.len();
78
79         let mut i = 0;
80         while let Some(entry) = archive.next_entry() {
81             let entry = entry?;
82             let file_name = String::from_utf8(entry.header().identifier().to_vec())
83                 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
84             if !skip(&file_name) {
85                 self.entries
86                     .push((file_name, ArchiveEntry::FromArchive { archive_index, entry_index: i }));
87             }
88             i += 1;
89         }
90
91         self.src_archives.push((archive_path.to_owned(), archive));
92         Ok(())
93     }
94
95     fn build(mut self: Box<Self>, output: &Path) -> bool {
96         use std::process::Command;
97
98         fn add_file_using_ar(archive: &Path, file: &Path) {
99             Command::new("ar")
100                 .arg("r") // add or replace file
101                 .arg("-c") // silence created file message
102                 .arg(archive)
103                 .arg(&file)
104                 .status()
105                 .unwrap();
106         }
107
108         enum BuilderKind<'a> {
109             Bsd(ar::Builder<File>),
110             Gnu(ar::GnuBuilder<File>),
111             NativeAr(&'a Path),
112         }
113
114         let mut builder = if self.config.use_native_ar {
115             BuilderKind::NativeAr(output)
116         } else if self.config.use_gnu_style_archive {
117             BuilderKind::Gnu(ar::GnuBuilder::new(
118                 File::create(output).unwrap(),
119                 self.entries
120                     .iter()
121                     .map(|(name, _)| name.as_bytes().to_vec())
122                     .collect(),
123             ))
124         } else {
125             BuilderKind::Bsd(ar::Builder::new(File::create(output).unwrap()))
126         };
127
128         let any_members = !self.entries.is_empty();
129
130         // Add all files
131         for (entry_name, entry) in self.entries.into_iter() {
132             match entry {
133                 ArchiveEntry::FromArchive {
134                     archive_index,
135                     entry_index,
136                 } => {
137                     let (ref src_archive_path, ref mut src_archive) =
138                         self.src_archives[archive_index];
139                     let entry = src_archive.jump_to_entry(entry_index).unwrap();
140                     let header = entry.header().clone();
141
142                     match builder {
143                         BuilderKind::Bsd(ref mut builder) => {
144                             builder.append(&header, entry).unwrap()
145                         }
146                         BuilderKind::Gnu(ref mut builder) => {
147                             builder.append(&header, entry).unwrap()
148                         }
149                         BuilderKind::NativeAr(archive_file) => {
150                             Command::new("ar")
151                                 .arg("x")
152                                 .arg(src_archive_path)
153                                 .arg(&entry_name)
154                                 .status()
155                                 .unwrap();
156                             add_file_using_ar(archive_file, Path::new(&entry_name));
157                             std::fs::remove_file(entry_name).unwrap();
158                         }
159                     }
160                 }
161                 ArchiveEntry::File(file) =>
162                     match builder {
163                         BuilderKind::Bsd(ref mut builder) => {
164                             builder
165                                 .append_file(entry_name.as_bytes(), &mut File::open(file).expect("file for bsd builder"))
166                                 .unwrap()
167                         },
168                         BuilderKind::Gnu(ref mut builder) => {
169                             builder
170                                 .append_file(entry_name.as_bytes(), &mut File::open(&file).expect(&format!("file {:?} for gnu builder", file)))
171                                 .unwrap()
172                         },
173                         BuilderKind::NativeAr(archive_file) => add_file_using_ar(archive_file, &file),
174                     },
175             }
176         }
177
178         // Finalize archive
179         std::mem::drop(builder);
180
181         // Run ranlib to be able to link the archive
182         let status =
183             std::process::Command::new("ranlib").arg(output).status().expect("Couldn't run ranlib");
184
185         if !status.success() {
186             self.config.sess.emit_fatal(RanlibFailure::new(status.code()));
187         }
188
189         any_members
190     }
191 }